@veltdev/sdk-dev 4.5.9-beta.12 → 4.5.9-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/velt.js +3 -3
package/velt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var SNIPPYLY_VERSION = '4.5.9-beta.
|
|
1
|
+
var SNIPPYLY_VERSION = '4.5.9-beta.13';
|
|
2
2
|
(function(m,w){"use strict";function rt(){var e=K.splice(0,K.length);for(ie=0;e.length;)e.shift().call(null,e.shift())}function me(e,t){for(var n=0,r=e.length;n<r;n++)Te(e[n],t)}function ot(e){for(var t,n=0,r=e.length;n<r;n++)t=e[n],U(t,q[pe(t)])}function fe(e){return function(t){Lt(t)&&(Te(t,e),L.length&&me(t.querySelectorAll(L),e))}}function pe(e){var t=le.call(e,"is"),n=e.nodeName.toUpperCase(),r=v.call(D,t?Y+t.toUpperCase():x+n);return t&&-1<r&&!De(n,t)?-1:r}function De(e,t){return-1<L.indexOf(e+'[is="'+t+'"]')}function Ie(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,o=e.target,l=e[W]||2,a=e[He]||3;!ce||o&&o!==t||!t[y]||r==="style"||e.prevValue===e.newValue&&(e.newValue!==""||n!==l&&n!==a)||t[y](r,n===l?null:e.prevValue,n===a?null:e.newValue)}function Fe(e){var t=fe(e);return function(n){K.push(t,n.target),ie&&clearTimeout(ie),ie=setTimeout(rt,1)}}function de(e){nt&&(nt=!1,e.currentTarget.removeEventListener(Ze,de)),L.length&&me((e.target||u).querySelectorAll(L),e.detail===E?E:b),R&&at()}function lt(e,t){var n=this;Ye.call(n,e,t),Me.call(n,{target:n})}function Se(e,t,n){var r=t.apply(e,n),o=pe(r);return-1<o&&U(r,q[o]),n.pop()&&L.length&&ot(r.querySelectorAll(L)),r}function he(e,t){Tt(e,t),$?$.observe(e,gt):(ue&&(e.setAttribute=lt,e[H]=Ee(e),e[g](st,Me)),e[g](N,Ie)),e[k]&&ce&&(e.created=!0,e[k](),e.created=!1)}function at(){for(var e,t=0,n=G.length;t<n;t++)e=G[t],V.contains(e)||(n--,G.splice(t--,1),Te(e,E))}function Ve(e){throw new Error("A "+e+" type is already registered")}function Te(e,t){var n,r,o=pe(e);-1<o&&!Mt.call(e,"TEMPLATE")&&(Q(e,q[o]),o=0,t!==b||e[b]?t!==E||e[E]||(e[b]=!1,e[E]=!0,r="disconnected",o=1):(e[E]=!1,e[b]=!0,r="connected",o=1,R&&v.call(G,e)<0&&G.push(e)),o&&(n=e[t+O]||e[r+O])&&n.call(e))}function z(){}function Pe(e,t,n){var r=n&&n[_]||"",o=t.prototype,l=Ce(o),a=t.observedAttributes||ye,s={prototype:l};oe(l,k,{value:function(){if(te)te=!1;else if(!this[B]){this[B]=!0,new t(this),o[k]&&o[k].call(this);var i=j[ne.get(t)];(!Z||i.create.length>1)&&_e(this)}}}),oe(l,y,{value:function(i){-1<v.call(a,i)&&o[y]&&o[y].apply(this,arguments)}}),o[qe]&&oe(l,ut,{value:o[qe]}),o[Be]&&oe(l,ct,{value:o[Be]}),r&&(s[_]=r),e=e.toUpperCase(),j[e]={constructor:t,create:r?[r,re(e)]:[e]},ne.set(t,e),u[S](e.toLowerCase(),s),Le(e),P[e].r()}function Re(e){var t=j[e.toUpperCase()];return t&&t.constructor}function Ue(e){return typeof e=="string"?e:e&&e.is||""}function _e(e){for(var t,n=e[y],r=n?e.attributes:ye,o=r.length;o--;)t=r[o],n.call(e,t.name||t.nodeName,null,t.value||t.nodeValue)}function Le(e){return e=e.toUpperCase(),e in P||(P[e]={},P[e].p=new Xe(function(t){P[e].r=t})),P[e].p}function ke(){C&&delete m.customElements,I(m,"customElements",{configurable:!0,value:new z}),I(m,"CustomElementRegistry",{configurable:!0,value:z});for(var e=it.get(/^HTML[A-Z]*[a-z]/),t=e.length;t--;(function(n){var r=m[n];if(r){m[n]=function(o){var l,a;return o||(o=this),o[B]||(te=!0,l=j[ne.get(o.constructor)],a=Z&&l.create.length===1,o=a?Reflect.construct(r,ye,l.constructor):u.createElement.apply(u,l.create),o[B]=!0,te=!1,a||_e(o)),o},m[n].prototype=r.prototype;try{r.prototype.constructor=m[n]}catch{dt=!0,I(r,B,{value:m[n]})}}})(e[t]));u.createElement=function(n,r){var o=Ue(r);return o?Ae.call(this,n,re(o)):Ae.call(this,n)},et||(Oe=!0,u[S](""))}var u=m.document,T=m.Object,it=(function(e){var t,n,r,o,l=/^[A-Z]+[a-z]/,a=function(p){var f,h=[];for(f in i)p.test(f)&&h.push(f);return h},s=function(p,f){(f=f.toLowerCase())in i||(i[p]=(i[p]||[]).concat(f),i[f]=i[f.toUpperCase()]=p)},i=(T.create||T)(null),c={};for(n in e)for(o in e[n])for(r=e[n][o],i[o]=r,t=0;t<r.length;t++)i[r[t].toLowerCase()]=i[r[t].toUpperCase()]=o;return c.get=function(p){return typeof p=="string"?i[p]||(l.test(p)?[]:""):a(p)},c.set=function(p,f){return l.test(p)?s(p,f):s(f,p),c},c})({collections:{HTMLAllCollection:["all"],HTMLCollection:["forms"],HTMLFormControlsCollection:["elements"],HTMLOptionsCollection:["options"]},elements:{Element:["element"],HTMLAnchorElement:["a"],HTMLAppletElement:["applet"],HTMLAreaElement:["area"],HTMLAttachmentElement:["attachment"],HTMLAudioElement:["audio"],HTMLBRElement:["br"],HTMLBaseElement:["base"],HTMLBodyElement:["body"],HTMLButtonElement:["button"],HTMLCanvasElement:["canvas"],HTMLContentElement:["content"],HTMLDListElement:["dl"],HTMLDataElement:["data"],HTMLDataListElement:["datalist"],HTMLDetailsElement:["details"],HTMLDialogElement:["dialog"],HTMLDirectoryElement:["dir"],HTMLDivElement:["div"],HTMLDocument:["document"],HTMLElement:["element","abbr","address","article","aside","b","bdi","bdo","cite","code","command","dd","dfn","dt","em","figcaption","figure","footer","header","i","kbd","mark","nav","noscript","rp","rt","ruby","s","samp","section","small","strong","sub","summary","sup","u","var","wbr"],HTMLEmbedElement:["embed"],HTMLFieldSetElement:["fieldset"],HTMLFontElement:["font"],HTMLFormElement:["form"],HTMLFrameElement:["frame"],HTMLFrameSetElement:["frameset"],HTMLHRElement:["hr"],HTMLHeadElement:["head"],HTMLHeadingElement:["h1","h2","h3","h4","h5","h6"],HTMLHtmlElement:["html"],HTMLIFrameElement:["iframe"],HTMLImageElement:["img"],HTMLInputElement:["input"],HTMLKeygenElement:["keygen"],HTMLLIElement:["li"],HTMLLabelElement:["label"],HTMLLegendElement:["legend"],HTMLLinkElement:["link"],HTMLMapElement:["map"],HTMLMarqueeElement:["marquee"],HTMLMediaElement:["media"],HTMLMenuElement:["menu"],HTMLMenuItemElement:["menuitem"],HTMLMetaElement:["meta"],HTMLMeterElement:["meter"],HTMLModElement:["del","ins"],HTMLOListElement:["ol"],HTMLObjectElement:["object"],HTMLOptGroupElement:["optgroup"],HTMLOptionElement:["option"],HTMLOutputElement:["output"],HTMLParagraphElement:["p"],HTMLParamElement:["param"],HTMLPictureElement:["picture"],HTMLPreElement:["pre"],HTMLProgressElement:["progress"],HTMLQuoteElement:["blockquote","q","quote"],HTMLScriptElement:["script"],HTMLSelectElement:["select"],HTMLShadowElement:["shadow"],HTMLSlotElement:["slot"],HTMLSourceElement:["source"],HTMLSpanElement:["span"],HTMLStyleElement:["style"],HTMLTableCaptionElement:["caption"],HTMLTableCellElement:["td","th"],HTMLTableColElement:["col","colgroup"],HTMLTableElement:["table"],HTMLTableRowElement:["tr"],HTMLTableSectionElement:["thead","tbody","tfoot"],HTMLTemplateElement:["template"],HTMLTextAreaElement:["textarea"],HTMLTimeElement:["time"],HTMLTitleElement:["title"],HTMLTrackElement:["track"],HTMLUListElement:["ul"],HTMLUnknownElement:["unknown","vhgroupv","vkeygen"],HTMLVideoElement:["video"]},nodes:{Attr:["node"],Audio:["audio"],CDATASection:["node"],CharacterData:["node"],Comment:["#comment"],Document:["#document"],DocumentFragment:["#document-fragment"],DocumentType:["node"],HTMLDocument:["#document"],Image:["img"],Option:["option"],ProcessingInstruction:["node"],ShadowRoot:["#shadow-root"],Text:["#text"],XMLDocument:["xml"]}});typeof w!="object"&&(w={type:w||"auto"});var K,Me,X,Ee,$,ve,Q,U,A,S="registerElement",xe=1e5*m.Math.random()>>0,H="__"+S+xe,g="addEventListener",b="attached",O="Callback",E="detached",_="extends",y="attributeChanged"+O,ut=b+O,qe="connected"+O,Be="disconnected"+O,k="created"+O,ct=E+O,W="ADDITION",He="REMOVAL",N="DOMAttrModified",Ze="DOMContentLoaded",st="DOMSubtreeModified",x="<",Y="=",mt=/^[A-Z][._A-Z0-9]*-[-._A-Z0-9]*$/,ft=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],D=[],q=[],L="",V=u.documentElement,v=D.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},ge=T.prototype,be=ge.hasOwnProperty,J=ge.isPrototypeOf,I=T.defineProperty,ye=[],ee=T.getOwnPropertyDescriptor,je=T.getOwnPropertyNames,pt=T.getPrototypeOf,Ge=T.setPrototypeOf,ze=!!T.__proto__,dt=!1,B="__dreCEv1",C=m.customElements,Z=!/^force/.test(w.type)&&!!(C&&C.define&&C.get&&C.whenDefined),Ke=T.create||T,ht=m.Map||function(){var e,t=[],n=[];return{get:function(r){return n[v.call(t,r)]},set:function(r,o){e=v.call(t,r),e<0?n[t.push(r)-1]=o:n[e]=o}}},Xe=m.Promise||function(e){function t(l){for(r=!0;n.length;)n.shift()(l)}var n=[],r=!1,o={catch:function(){return o},then:function(l){return n.push(l),r&&setTimeout(t,1),o}};return e(t),o},te=!1,j=Ke(null),P=Ke(null),ne=new ht,re=function(e){return e.toLowerCase()},Ce=T.create||function e(t){return t?(e.prototype=t,new e):this},Tt=Ge||(ze?function(e,t){return e.__proto__=t,e}:je&&ee?(function(){function e(t,n){for(var r,o=je(n),l=0,a=o.length;l<a;l++)r=o[l],be.call(t,r)||I(t,r,ee(n,r))}return function(t,n){do e(t,n);while((n=pt(n))&&!J.call(n,t));return t}})():function(e,t){for(var n in t)e[n]=t[n];return e}),F=m.MutationObserver||m.WebKitMutationObserver,$e=m.HTMLAnchorElement,d=(m.HTMLElement||m.Element||m.Node).prototype,R=!J.call(d,V),oe=R?function(e,t,n){return e[t]=n.value,e}:I,Lt=R?function(e){return e.nodeType===1}:function(e){return J.call(d,e)},G=R&&[],Qe=d.attachShadow,We=d.cloneNode,Mt=d.closest||function(e){for(var t=this;t&&t.nodeName!==e;)t=t.parentNode;return t},we=d.dispatchEvent,le=d.getAttribute,Et=d.hasAttribute,vt=d.removeAttribute,Ye=d.setAttribute,ae=u.createElement,Ht=u.importNode,Ae=ae,gt=F&&{attributes:!0,characterData:!0,attributeOldValue:!0},Je=F||function(e){ue=!1,V.removeEventListener(N,Je)},ie=0,et=S in u&&!/^force-all/.test(w.type),tt=!0,Oe=!1,ue=!0,nt=!0,ce=!0;if(F&&(A=u.createElement("div"),A.innerHTML="<div><div></div></div>",new F(function(e,t){if(e[0]&&e[0].type=="childList"&&!e[0].removedNodes[0].childNodes.length){A=ee(d,"innerHTML");var n=A&&A.set;n&&I(d,"innerHTML",{set:function(r){for(;this.lastChild;)this.removeChild(this.lastChild);n.call(this,r)}})}t.disconnect(),A=null}).observe(A,{childList:!0,subtree:!0}),A.innerHTML=""),et||(Ge||ze?(Q=function(e,t){J.call(t,e)||he(e,t)},U=he):(Q=function(e,t){e[H]||(e[H]=T(!0),he(e,t))},U=Q),R?(ue=!1,(function(){var e=ee(d,g),t=e.value,n=function(l){var a=new CustomEvent(N,{bubbles:!0});a.attrName=l,a.prevValue=le.call(this,l),a.newValue=null,a[He]=a.attrChange=2,vt.call(this,l),we.call(this,a)},r=function(l,a){var s=Et.call(this,l),i=s&&le.call(this,l),c=new CustomEvent(N,{bubbles:!0});Ye.call(this,l,a),c.attrName=l,c.prevValue=s?i:null,c.newValue=a,s?c.MODIFICATION=c.attrChange=1:c[W]=c.attrChange=0,we.call(this,c)},o=function(l){var a,s=l.currentTarget,i=s[H],c=l.propertyName;i.hasOwnProperty(c)&&(i=i[c],a=new CustomEvent(N,{bubbles:!0}),a.attrName=i.name,a.prevValue=i.value||null,a.newValue=i.value=s[c]||null,a.prevValue==null?a[W]=a.attrChange=0:a.MODIFICATION=a.attrChange=1,we.call(s,a))};e.value=function(l,a,s){l===N&&this[y]&&this.setAttribute!==r&&(this[H]={className:{name:"class",value:this.className}},this.setAttribute=r,this.removeAttribute=n,t.call(this,"propertychange",o)),t.call(this,l,a,s)},I(d,g,e)})()):F||(V[g](N,Je),V.setAttribute(H,1),V.removeAttribute(H),ue&&(Me=function(e){var t,n,r,o=this;if(o===e.target){t=o[H],o[H]=n=Ee(o);for(r in n){if(!(r in t))return X(0,o,r,t[r],n[r],W);if(n[r]!==t[r])return X(1,o,r,t[r],n[r],"MODIFICATION")}for(r in t)if(!(r in n))return X(2,o,r,t[r],n[r],He)}},X=function(e,t,n,r,o,l){var a={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:o};a[l]=e,Ie(a)},Ee=function(e){for(var t,n,r={},o=e.attributes,l=0,a=o.length;l<a;l++)t=o[l],(n=t.name)!=="setAttribute"&&(r[n]=t.value);return r})),u[S]=function(e,t){if(n=e.toUpperCase(),tt&&(tt=!1,F?($=(function(i,c){function p(f,h){for(var M=0,se=f.length;M<se;h(f[M++]));}return new F(function(f){for(var h,M,se,Ne=0,bt=f.length;Ne<bt;Ne++)h=f[Ne],h.type==="childList"?(p(h.addedNodes,i),p(h.removedNodes,c)):(M=h.target,ce&&M[y]&&h.attributeName!=="style"&&(se=le.call(M,h.attributeName))!==h.oldValue&&M[y](h.attributeName,h.oldValue,se))})})(fe(b),fe(E)),ve=function(i){return $.observe(i,{childList:!0,subtree:!0}),i},ve(u),Qe&&(d.attachShadow=function(){return ve(Qe.apply(this,arguments))})):(K=[],u[g]("DOMNodeInserted",Fe(b)),u[g]("DOMNodeRemoved",Fe(E))),u[g](Ze,de),u[g]("readystatechange",de),u.importNode=function(i,c){switch(i.nodeType){case 1:return Se(u,Ht,[i,!!c]);case 11:for(var p=u.createDocumentFragment(),f=i.childNodes,h=f.length,M=0;M<h;M++)p.appendChild(u.importNode(f[M],!!c));return p;default:return We.call(i,!!c)}},d.cloneNode=function(i){return Se(this,We,[!!i])}),Oe)return Oe=!1;if(-2<v.call(D,Y+n)+v.call(D,x+n)&&Ve(e),!mt.test(n)||-1<v.call(ft,n))throw new Error("The type "+e+" is invalid");var n,r,o=function(){return a?u.createElement(s,n):u.createElement(s)},l=t||ge,a=be.call(l,_),s=a?t[_].toUpperCase():n;return a&&-1<v.call(D,x+s)&&Ve(s),r=D.push((a?Y:x)+n)-1,L=L.concat(L.length?",":"",a?s+'[is="'+e.toLowerCase()+'"]':s),o.prototype=q[r]=be.call(l,"prototype")?l.prototype:Ce(d),L.length&&me(u.querySelectorAll(L),b),o},u.createElement=Ae=function(e,t){var n=Ue(t),r=n?ae.call(u,e,re(n)):ae.call(u,e),o=""+e,l=v.call(D,(n?Y:x)+(n||o).toUpperCase()),a=-1<l;return n&&(r.setAttribute("is",n=n.toLowerCase()),a&&(a=De(o.toUpperCase(),n))),ce=!u.createElement.innerHTMLHelper,a&&U(r,q[l]),r}),addEventListener("beforeunload",function(){delete u.createElement,delete u.importNode,delete u[S]},!1),z.prototype={constructor:z,define:Z?function(e,t,n){if(n)Pe(e,t,n);else{var r=e.toUpperCase();j[r]={constructor:t,create:[r]},ne.set(t,r),C.define(e,t)}}:Pe,get:Z?function(e){return C.get(e)||Re(e)}:Re,whenDefined:Z?function(e){return Xe.race([C.whenDefined(e),Le(e)])}:Le},!C||/^force/.test(w.type))ke();else if(!w.noBuiltIn)try{(function(e,t,n){var r=new RegExp(`^<a\\s+is=('|")`+n+"\\1></a>$");if(t[_]="a",e.prototype=Ce($e.prototype),e.prototype.constructor=e,m.customElements.define(n,e,t),!r.test(u.createElement("a",{is:n}).outerHTML)||!r.test(new e().outerHTML))throw t})(function e(){return Reflect.construct($e,[],e)},{},"document-register-element-a"+xe)}catch{ke()}if(!w.noBuiltIn)try{if(ae.call(u,"a","a").outerHTML.indexOf("is")<0)throw{}}catch{re=function(t){return{is:t.toLowerCase()}}}})(window);
|
|
3
3
|
|
|
4
4
|
var TSe=Object.create;var zA=Object.defineProperty,DSe=Object.defineProperties,wSe=Object.getOwnPropertyDescriptor,OSe=Object.getOwnPropertyDescriptors,ASe=Object.getOwnPropertyNames,HA=Object.getOwnPropertySymbols,zY=Object.getPrototypeOf,u8=Object.prototype.hasOwnProperty,GY=Object.prototype.propertyIsEnumerable,PSe=Reflect.get;var HY=(i,o,n)=>o in i?zA(i,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[o]=n,E=(i,o)=>{for(var n in o||={})u8.call(o,n)&&HY(i,n,o[n]);if(HA)for(var n of HA(o))GY.call(o,n)&&HY(i,n,o[n]);return i},D=(i,o)=>DSe(i,OSe(o));var sy=(i,o)=>{var n={};for(var e in i)u8.call(i,e)&&o.indexOf(e)<0&&(n[e]=i[e]);if(i!=null&&HA)for(var e of HA(i))o.indexOf(e)<0&&GY.call(i,e)&&(n[e]=i[e]);return n};var MSe=(i,o)=>()=>(o||i((o={exports:{}}).exports,o),o.exports),GA=(i,o)=>{for(var n in o)zA(i,n,{get:o[n],enumerable:!0})},kSe=(i,o,n,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of ASe(o))!u8.call(i,t)&&t!==n&&zA(i,t,{get:()=>o[t],enumerable:!(e=wSe(o,t))||e.enumerable});return i};var WY=(i,o,n)=>(n=i!=null?TSe(zY(i)):{},kSe(o||!i||!i.__esModule?zA(n,"default",{value:i,enumerable:!0}):n,i));var Mp=(i,o,n)=>PSe(zY(i),n,o);var Q=(i,o,n)=>new Promise((e,t)=>{var r=c=>{try{s(n.next(c))}catch(p){t(p)}},a=c=>{try{s(n.throw(c))}catch(p){t(p)}},s=c=>c.done?e(c.value):Promise.resolve(c.value).then(r,a);s((n=n.apply(i,o)).next())});var cY=MSe((p3o,lY)=>{"use strict";var Dt={};Dt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Dt.localCName=Dt.generateIdentifier();Dt.splitLines=function(i){return i.trim().split(`
|
|
@@ -178,7 +178,7 @@ Content-Type: `+p.contentType+`\r
|
|
|
178
178
|
/>
|
|
179
179
|
</svg>
|
|
180
180
|
`},gt.CommentAnnotationPriorityMap={P0:{id:"P0",name:"P0",color:"var(--velt-error, #FF7162)",lightColor:"var(--velt-error-light, #F7E7E7) "},P1:{id:"P1",name:"P1",color:"var(--velt-warning, #ECB000)",lightColor:"var(--velt-warning-light, #FEFCEA)"},P2:{id:"P2",name:"P2",color:"var(--velt-text-7, #777E91)",lightColor:"var(--velt-background-1, #F3F3F5)"}},gt.WorkspaceRoles=[{id:so.COMMENTER?.toLowerCase(),name:so.COMMENTER,description:"Can comment on this project",permissions:[]},{id:so.ADMIN?.toLowerCase(),name:so.ADMIN,description:"Can comment on all projects and has access to the portal",permissions:[]}],gt.DocumentAccessTypeMap={[Ei.PUBLIC]:{id:Ei.PUBLIC,name:Ei.PUBLIC,description:"Anyone with link can view"},[Ei.RESTRICTED]:{id:Ei.RESTRICTED,name:Ei.RESTRICTED,description:"Only people with access can view"}},gt.DocumentAccessTypeMapSF={[Ei.PUBLIC]:{id:Ei.PUBLIC,name:Ei.PUBLIC,description:"Anyone with the link can comment after logging in."},[Ei.RESTRICTED]:{id:Ei.RESTRICTED,name:Ei.RESTRICTED,description:"Only people added to this project can comment."}},gt.CommentCategoryMap={bug:{id:"bug",name:"Bug",color:"#FF7162"},feedback:{id:"feedback",name:"Feedback",color:"#00C48C"},question:{id:"question",name:"Question",color:"#FFD166"}},gt.OVERLAY_POSITIONS=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"start",overlayY:"top"},{originX:"end",originY:"bottom",overlayX:"end",overlayY:"top"},{originX:"center",originY:"bottom",overlayX:"center",overlayY:"top"},{originX:"start",originY:"top",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"top",overlayX:"end",overlayY:"bottom"},{originX:"center",originY:"top",overlayX:"center",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"}],gt.OVERLAY_POSITIONS_FOR_POPOVER_MODE=[{originX:"end",originY:"top",overlayX:"start",overlayY:"top"},{originX:"end",originY:"center",overlayX:"start",overlayY:"center"},{originX:"end",originY:"bottom",overlayX:"start",overlayY:"bottom"},{originX:"start",originY:"top",overlayX:"end",overlayY:"top"},{originX:"start",originY:"center",overlayX:"end",overlayY:"center"},{originX:"start",originY:"bottom",overlayX:"end",overlayY:"bottom"}],gt.VIDEO_EDITOR={ZOOM_IN_DURATION:500,ZOOM_OUT_DURATION:500,DEFAULT_ZOOM_FACTOR:1.5,MAX_ZOOM_FACTOR:3,ZOOM_FACTOR_OPTIONS:[{value:2,label:"2x"},{value:1.7,label:"1.7x"},{value:1.5,label:"1.5x"},{value:1.2,label:"1.2x"}],MIN_DRAG_AREA_MULTIPLIER:.015,PREFERRED_SECTION_DURATION_MULTIPLIER:.15,SELECTION_MIN_DRAG_DISTANCE:2,MIN_DURATION_THRESHOLD:.01,TIME_BUFFER:.1,SHORT_VIDEO_THRESHOLD:3,SMALL_VIDEO_THRESHOLD:5,MILLISECOND_PRECISION_MULTIPLIER:1e3,TENTH_SECOND_PRECISION_MULTIPLIER:10,DEBOUNCE_DELAY:200,DECIMAL_PRECISION:2,MAX_MARKER_COUNT:10,MARKER_INTERVAL:5,FAST_TIMEOUT:50,STANDARD_TIMEOUT:100,RECTANGLE_POSITIONING:{FULL_PERCENT:100,HALF_PERCENT:50,QUARTER_PERCENT:25},EASING:{QUAD_IN_OUT_MULTIPLIER:2,QUAD_IN_OUT_POWER:2,HALF_THRESHOLD:.5},PERCENTAGE:{HALF:50,FULL:100},MILLISECONDS_TO_SECONDS:1e3};var U=gt;var Rn=(i,o=0)=>{try{let n=3735928559^o,e=1103547991^o;for(let t=0,r;t<i.length;t++)r=i.charCodeAt(t),n=Math.imul(n^r,2654435761),e=Math.imul(e^r,1597334677);return n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),4294967296*(2097151&e)+(n>>>0)}catch(n){return nt.catch("Error in cyrb53: ",n),0}},d7e=()=>{try{return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+i/4).toString(16))}catch(i){return nt.catch("Error in uuidv4: ",i),""}},Et=i=>{try{return wa.hashStr(i)}catch(o){return nt.catch("Error in hashStr: ",o),i}},Tle=i=>{try{return!i||i.trim().length===0?void 0:wa.hashStr(i)}catch(o){nt.catch("Error in hashForAnchor: ",o);return}},br=i=>Rn(i).toString(),jH=i=>Et(i),Qa=i=>Et(i).toString(),Ui=i=>Et(i).toString(),tm=i=>{try{if(i)return typeof i=="string"?wa.hashStr(i):Array.isArray(i)?wa.hashStr(i.join("-")):"";{let o=d7e();return wa.hashStr(o)}}catch(o){return nt.catch("Error in getMultiThreadAnnotationId: ",o),""}},eo=(i,o,n)=>{try{if(i&&o){if(i.featureAllowList&&i.featureAllowList.length&&!i.featureAllowList.includes(n)||i.userIdAllowList&&i.userIdAllowList.length&&!i.userIdAllowList.includes(o.userId)||i.userGroupIdAllowList&&i.userGroupIdAllowList.length&&!i.userGroupIdAllowList.includes(o.groupId||"")||i.userPlanAllowList&&i.userPlanAllowList.length&&!i.userPlanAllowList.includes(o.plan||""))return!1;if(i.urlAllowList){let e=window.location.href;if(i.urlAllowList.length&&!i.urlAllowList.filter(t=>e.includes(t)).length)return!1}return!0}return!1}catch(e){return nt.catch("Error in isFeatureAllowed: ",e),!1}},on=()=>{try{let i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o="";for(let n=0;n<20;n++)o+=i.charAt(Math.floor(Math.random()*i.length));return o}catch(i){return nt.catch("Error in utils generateId: ",i),""}},Pg=i=>{try{let o=0;if(i){let n=new Date().getTime();o=Math.abs(n-i)}return o}catch(o){return nt.catch("Error in utils getFirebaseTimeDiffInMins: ",o),0}};var Dle=()=>{try{return Dn.debugMode||!!sessionStorage.getItem("debugMode")||!!sessionStorage.getItem("forceDebugMode")}catch(i){return nt.catch("Error in showLogs: ",i),!1}},wle=()=>{try{return!!sessionStorage.getItem("debugPerfMode")}catch(i){return nt.catch("Error in showPerfLogs: ",i),!1}},er=i=>{try{return typeof i!="object"?Object.assign({},...Object.keys(i).sort().map(o=>({[o]:i[o]&&typeof i[o]=="object"?er(i[o]):i[o]}))):i}catch(o){return nt.catch("Error in sortObjectByKeys: ",o),i}},UH=i=>{try{return i!==null&&typeof i=="object"&&!Array.isArray(i)}catch{return!1}},ic=i=>{try{return UH(i)?Object.fromEntries(Object.entries(i).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,UH(n)?ic(n):Array.isArray(n)?n.map(e=>UH(e)?ic(e):e):n])):i}catch{return i}},vk=(i,o)=>{try{return typeof o!="object"||o===null?i===o:typeof i!="object"||i===null?!1:Array.isArray(o)?Array.isArray(i)?o.every(n=>i.some(e=>vk(e,n))):!1:Object.keys(o).every(n=>Object.prototype.hasOwnProperty.call(i,n)?vk(i[n],o[n]):!1)}catch{return!1}},$H=(i,o,n)=>Q(null,null,function*(){try{let e=yield p7e(o),t=new Uint8Array(new TextEncoder().encode(n)).slice(0,16),r=new TextEncoder().encode(i),a=yield window.crypto.subtle.encrypt({name:"AES-CBC",iv:t},e,r);return btoa(String.fromCharCode(...new Uint8Array(a)))}catch(e){return nt.catch("Error in encrypt: ",e),i}}),HH=(i,o,n)=>Q(null,null,function*(){try{let e=yield m7e(o),t=new Uint8Array(new TextEncoder().encode(n)).slice(0,16),r=new Uint8Array(atob(i).split("").map(s=>s.charCodeAt(0))),a=yield window.crypto.subtle.decrypt({name:"AES-CBC",iv:t},e,r);return new TextDecoder().decode(a)}catch(e){return nt.catch("Error in decrypt: ",e),i}}),m7e=i=>Q(null,null,function*(){try{let o=new TextEncoder().encode(i),n=new Uint8Array(32);return n.fill(0),n.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",n,"AES-CBC",!1,["decrypt"])}catch(o){throw nt.catch("Error in importDecryptKey:",o),o}}),bl=(i,o)=>Q(null,null,function*(){try{let n="Velt"+o;return yield $H(JSON.stringify(i),n,Et(n))}catch(n){return nt.catch("Error in encryptData: ",n),i}}),j0=(i,o)=>Q(null,null,function*(){try{let n="Velt"+o,e=yield HH(i,n,Et(n));return JSON.parse(e)}catch(n){return nt.catch("Error in decryptData: ",n),null}}),yk=i=>{try{switch(i?.region){case"asiaSouthEast1":return"asiaSouthEast1";case"asiaNorthEast1":return"asiaNorthEast1";case"europeWest1":return"europeWest1";default:return"usCentral1"}}catch(o){return nt.catch("Error in getRegion: ",o),"usCentral1"}},p7e=i=>Q(null,null,function*(){try{let o=new TextEncoder().encode(i),n=new Uint8Array(32);return n.fill(0),n.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",n,"AES-CBC",!1,["encrypt"])}catch(o){throw nt.catch("Error in importKey:",o),o}}),Ole=i=>{try{if(i&&typeof i=="object"){let o=er(i);return Rn(JSON.stringify(o))}else return null}catch(o){return nt.catch("Error in utils generateLocationId: ",o),null}},Gi=(i,o=[])=>(i?.tagName?.toLowerCase().indexOf("velt-")>=0&&![U.TAGS.VELT_VIDEO_PLAYER.toLowerCase()].includes(i?.tagName?.toLowerCase())||i?.tagName?.toLowerCase().indexOf("snippyly-")>=0||i?.className?.split&&(i?.className?.split(" ")?.indexOf("snippyly-overlay-panel")>=0||i?.className?.split(" ")?.indexOf("cdk-overlay-container")>=0))&&!o?.includes(i?.tagName?.toLowerCase())?!0:i?.parentNode&&Gi(i?.parentNode,o),Di=i=>{try{return!!document?.body?.contains(i)}catch(o){return nt.catch("Error in utils isElementInsideBody: ",o),!1}};var gi=(i,o)=>{try{return Object.prototype.toString.call(i)===Object.prototype.toString.call(o)?Object.prototype.toString.call(i)==="[object Object]"||Object.prototype.toString.call(i)==="[object Array]"?Object.keys(i).length!==Object.keys(o).length?!1:Object.keys(i).every(n=>gi(i[n],o[n])):i===o:!1}catch(n){return nt.catch("Error in utils deepCompare: ",n),!1}},$0=(i,o,n=1)=>{try{if(o){let e=g7e(o.textContent,i,n);if(e>=0){let t=(o?.ownerDocument).createNodeIterator(o,NodeFilter.SHOW_TEXT),r,a=[];for(;r=t.nextNode();)a.push(r);let s=[],c=e,p=i.length,g=c+p,f=0;for(let I=0;I<a.length;I++){let T=a[I],N=f;if(f+=T.textContent?.length,f>=c&&!s.length?s.push({textNode:T,startOffset:c-N}):f>=c&&f<g&&s.push({textNode:T}),f>=g){if(s.length===1&&s[0].textNode===T){s.push({textNode:T,endOffset:c-N+i.length});break}let G=p;s.forEach(z=>{G-=z.textNode.textContent?.length-(z.startOffset||0)}),s.push({textNode:T,endOffset:G});break}}return s}}return[]}catch(e){return nt.catch("Error in utils calculateNodes: ",e),[]}},g7e=(i,o,n=1)=>{try{if(i?.includes(o)){let e=i.split(o,n);return e.length===n?e.join(o).length:-1}else return-1}catch(e){return nt.catch("Error in utils getTextPosition: ",e),-1}},Qh=(i,o,n,e,t)=>{try{let r=new Range;r.setStart(i,o),r.setEnd(n,e);let a=r.toString(),s=0;if(i.nodeType===Node.TEXT_NODE){let c=i,p="";if(c)for(;c=c.previousSibling;)p=(c.textContent||"")+p;if(p){let g=new RegExp(id(t),"g");s=(p.match(g)||[]).length}}if(a){let c=new RegExp(id(t),"g");return(a.match(c)||[]).length+s}else return s}catch(r){return nt.catch("Error in utils getSelectedTextOccurrenceInRange: ",r),0}},id=i=>{try{return i&&typeof i=="string"?i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):i}catch(o){return nt.catch("Error in utils escapeRegExp: ",o),i}},H0=i=>{try{return i==null?null:i.scrollHeight>i.clientHeight?i:H0(i?.parentNode)}catch(o){return nt.catch("Error in utils getScrollableParent: ",o),null}},Ag=i=>{try{return i==null?[]:i.scrollHeight>i.clientHeight?[i,...Ag(i?.parentNode)]:Ag(i?.parentNode)}catch(o){return nt.catch("Error in utils getScrollableParents: ",o),[]}},zH=(i,o)=>{try{if(i&&o){let n=i.getBoundingClientRect(),e=o.getBoundingClientRect(),t=n.top-e.top+(o.tagName?.toLowerCase()==="html"?0:o.scrollTop),r=n.left-e.left;return{top:t,left:r}}else return null}catch(n){return nt.catch("Error in utils getRelativeTopLeftPosition: ",n),null}},z0=(i,o)=>`${Rn(i+"_"+o)}`,Mi=()=>{try{let i=new co;return i.url=window.location.href,i.path=window.location.pathname,i.queryParams=window.location.search,i.baseUrl=window.location.origin,i.title=document.title,i}catch(i){nt.catch("Error in utils getPageInfo: ",i);return}},pp=i=>{try{return i?i?.hasAttribute&&i?.hasAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED)?!0:pp(i?.parentElement):!1}catch(o){return nt.catch("Error in utils isCommentDisabledOnElement: ",o),!1}},Sk=i=>{try{return i?i?.hasAttribute&&i?.hasAttribute(U.ATTRIBUTES.VELT_TAG_DISABLED)?!0:Sk(i?.parentElement):!1}catch(o){return nt.catch("Error in utils isTagDisabledOnElement: ",o),!1}},bk=i=>{try{return i?i?.hasAttribute&&i?.hasAttribute(U.ATTRIBUTES.VELT_ARROW_DISABLED)?!0:bk(i?.parentElement):!1}catch(o){return nt.catch("Error in utils isArrowDisabledOnElement: ",o),!1}},Ik=i=>{try{return i?i?.hasAttribute&&i?.hasAttribute(U.ATTRIBUTES.VELT_AREA_DISABLED)?!0:Ik(i?.parentElement):!1}catch(o){return nt.catch("Error in utils isAreaDisabledOnElement: ",o),!1}},Ek=i=>{try{return i?i?.hasAttribute&&i?.hasAttribute(U.ATTRIBUTES.VELT_RECORDER_DISABLED)?!0:Ek(i?.parentElement):!1}catch(o){return nt.catch("Error in utils isRecorderDisabledOnElement: ",o),!1}};var ga=()=>{try{return window?.Snippyly?.version}catch(i){return nt.catch("Error in utils getSdkVersion: ",i),null}},GH=i=>{try{return Object.fromEntries(Object.entries(i).filter(([o,n])=>n!==void 0))}catch(o){return nt.catch("Error in utils removeUndefinedKeys: ",o),i}},xk=i=>{try{let o=new URL(i);return Object.values(U.URL_PARAMS).forEach(n=>{o.searchParams.delete(n)}),o.href}catch(o){return nt.catch("Error in utils excludeSnippylyParamsFromUrl: ",o),i}},zs=i=>{try{navigator.clipboard.writeText(i)}catch(o){nt.catch("Error in copyToClipboard: ",o)}},eI=i=>{try{let o=Ale(i);return o&&typeof o=="string"&&o.includes("/svg")&&(o=o.split("/svg")[0]+"/*[name()='svg']"),o}catch(o){nt.catch("Error in utils getXPath:",o)}},Ale=i=>{try{if(i){if(typeof i=="string")return document.evaluate(i,document,null,0,null);if(!i||i.nodeType!=1)return"";if(i.id&&i?.tagName?.toLowerCase()!=="svg"&&document.querySelectorAll(`[id='${i.id}']`)?.length===1)return"//*[@id='"+i.id+"']";let o=[].filter.call(i.parentNode?.children?i.parentNode?.children:[],function(n){return n.tagName==i.tagName});return Ale(i.parentNode)+"/"+i.tagName.toLowerCase()+(o.length>1?"["+([].indexOf.call(o,i)+1)+"]":"")}}catch(o){nt.catch("Error in utils calculateXPath:",o)}},Ple=i=>{try{let o=[];return i.forEach(n=>{let e={};e.commonAncestorContainer=u7e(n.commonAncestorContainer),e.text=n.toString(),e.occurrence=Qh(n.commonAncestorContainer,0,n.startContainer,n.startOffset,n.toString())+1,o.push(e)}),o}catch{return[]}},u7e=i=>{try{if(i.nodeType===Node.TEXT_NODE){let o=1,n=i.previousSibling;for(;n;)n.nodeType===Node.TEXT_NODE&&o++,n=n.previousSibling;return eI(i.parentElement)}else return eI(i)}catch(o){return nt.catch("Error in utils getXPathForText: ",o),eI(i)}},WH=(i,o)=>{try{return i?i?.hasAttribute&&(o&&i.hasAttribute("contenteditable")||i?.getAttribute(U.ATTRIBUTES.VELT_LIVE_SELECTION_ENABLED)==="true")?i:WH(i?.parentElement,o):null}catch(n){return nt.catch("Error in utils getSelectionEnabledElement: ",n),null}},Tk=i=>{try{let o,n=[],e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null);for(;o=e.nextNode();)n.push(o);return n}catch(o){return nt.catch("Error in utils getTextNodesInsideElement: ",o),[]}},Mle=i=>{try{return i<576||i>=576&&i<767?"Mobile":i>=768&&i<992?"Tablet":i>=992&&i<1520?"Desktop":"Monitor"}catch(o){return nt.catch("Error in utils getDeviceTypeFromDeviceWidth: ",o),""}},nm=i=>new Promise(o=>setTimeout(o,i)),kle=(i,o=0)=>new Promise((n,e)=>{let t=document.createElement("video"),r=navigator.userAgent.includes("Firefox");r&&(t.preload="auto"),t.setAttribute("src",URL.createObjectURL(i)),t.load(),t.addEventListener("error",a=>{e("error when loading video file: "+a)}),t.addEventListener("loadedmetadata",()=>{let a=()=>{if(t.duration<o){e("video is too short.");return}setTimeout(()=>{t.currentTime=o},200),t.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=t.videoWidth,s.height=t.videoHeight;let c=s.getContext("2d");c.drawImage(t,0,0,s.width,s.height),c.canvas.toBlob(p=>{t.remove(),n(p)},"image/jpeg",.75)})};if(r&&t.duration>0&&t.duration<10&&i.size>1e6){(()=>{setTimeout(()=>{t.duration<o&&(o=Math.max(.1,t.duration/2)),a()},1e3)})();return}a()})}),Rle=i=>{try{return new Promise((o,n)=>{let e=new FileReader;e.onloadend=()=>o(e.result),e.readAsDataURL(i)})}catch(o){return nt.catch("Error in utils blobToBase64: ",o),Promise.resolve("")}},qH=(i,o="image/jpeg")=>{try{let n=atob(i.split(",")[1]),e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let r=0;r<n.length;r++)t[r]=n.charCodeAt(r);return new Blob([e],{type:o})}catch(n){return nt.catch("Error in utils base64ToBlob: ",n),null}},Nle=(i,o,n=20)=>new Promise((e,t)=>{let r=new Image;r.crossOrigin="Anonymous",r.onload=()=>{let a=r.width,s=r.height,c=600,p=s/a*c,g="http://www.w3.org/2000/svg",f=document.createElementNS(g,"svg");f.setAttribute("xmlns",g),f.setAttribute("width",c.toString()),f.setAttribute("height",p.toString()),f.setAttribute("viewBox",`0 0 ${c} ${p}`);let I=document.createElementNS(g,"circle"),T=document.createElementNS(g,"polygon"),N=16,G=N+16,z=c/2,J=p/2;if(I.setAttribute("cx",z.toString()),I.setAttribute("cy",J.toString()),I.setAttribute("r",G.toString()),I.setAttribute("fill","lightgrey"),T.setAttribute("points",`${z-N/2},${J-N} ${z-N/2},${J+N} ${z+N},${J}`),T.setAttribute("fill","#ffffff"),f.appendChild(I),f.appendChild(T),o){let be=o.length*16-10,Se=16*1.5,Ae=(c-be)/2,Ce=p-Se-10,fe=document.createElementNS(g,"rect");fe.setAttribute("x",Ae.toString()),fe.setAttribute("y",Ce.toString()),fe.setAttribute("width",be.toString()),fe.setAttribute("height",Se.toString()),fe.setAttribute("fill","#353945b3"),fe.setAttribute("rx","12"),f.appendChild(fe);let we=document.createElementNS(g,"text");we.textContent=o,we.setAttribute("x",(c/2).toString()),we.setAttribute("y",(Ce+16).toString()),we.setAttribute("font-size","16"),we.setAttribute("text-anchor","middle"),we.setAttribute("fill","white"),f.appendChild(we)}let ce=new XMLSerializer().serializeToString(f),ye=new Image,Oe=new Blob([ce],{type:"image/svg+xml;charset=utf-8"}),$e=URL.createObjectURL(Oe);ye.onload=()=>{let Be=document.createElement("canvas");Be.width=c,Be.height=p;let be=Be.getContext("2d");be.beginPath(),be.moveTo(n,0),be.lineTo(c-n,0),be.quadraticCurveTo(c,0,c,n),be.lineTo(c,p-n),be.quadraticCurveTo(c,p,c-n,p),be.lineTo(n,p),be.quadraticCurveTo(0,p,0,p-n),be.lineTo(0,n),be.quadraticCurveTo(0,0,n,0),be.closePath(),be.clip(),be.drawImage(r,0,0,c,p),be.drawImage(ye,0,0,c,p);let Se=Be.toDataURL("image/png");e(Se)},ye.onerror=t,ye.src=$e},r.onerror=t,r.src=i});var Dk=i=>{try{return i?.replace(/[\n\t\u200D]/g,"")?.split(/\s+/)?.filter(e=>e?.trim()?.length)||[]}catch(o){return nt.catch("Error in utils getWords: ",o),[]}},ua=(i,o=[])=>{try{let n=o.map(e=>`[${e}="${i}"]`).join(",");return document.querySelector(n)}catch(n){return nt.catch("Error in utils getElementByAttributes: ",n),null}},Fle=(i,o=[])=>{try{let n=o.map(e=>`[${e}="${i}"]`).join(",");return document.querySelectorAll(n)}catch(n){return nt.catch("Error in utils getElementsByAttributes: ",n),[]}},nd=i=>{try{let o=Math.floor(i/3600),n=Math.floor((i-o*3600)/60),e=Math.floor(i-o*3600-n*60);return o&&o<10&&(o="0"+o),n<10&&(n="0"+n),e<10&&(e="0"+e),(o?o+":":"")+n+":"+e}catch{return""}},Lle=(i,o=10)=>{try{if(!i||!i.currentTime)throw new Error("Invalid video element reference provided");let n=i.currentTime,e=Math.floor(n/o)*o,t=e+o;return{startSlot:nd(e),endSlot:nd(t),timeSlot:nd(e)+" - "+nd(t)}}catch{return null}},G0=(i,o=["@"])=>{try{let n="",e,t=i.getRootNode();if(t instanceof ShadowRoot?e=t?.getSelection():e=window.getSelection(),e?.rangeCount){let r=e.getRangeAt(0),a=r.startOffset,s=r.endOffset,c=r?.commonAncestorContainer?.textContent;c?n=h7e(c,s,o):n=""}return n}catch(n){return nt.catch("Error in utils getWordAtCursor: ",n),""}};var h7e=(i,o,n=["@"])=>{try{let e=-1,t=!1;for(let r of n){let a=i.lastIndexOf(r,o),s=a>0?i.lastIndexOf(r,a-1):-1;if(a>e){let c=Ck(i,a,o),p=_k(i,a,o);if(c||p){if(s!==-1){let g=Ck(i,s,a),f=_k(i,s,a);!g&&!f&&(e=s,t=!0)}}else e=a,t=!0}}return e!==-1&&t?i.substring(e,o):""}catch(e){return nt.catch("Error in utils getStringFromLastAtSymbol: ",e),""}},Ck=(i,o,n)=>{try{if(o===0)return!1;let e=i.charAt(o-1);return!(e===" "||e==="\xA0"||e===`
|
|
181
|
-
`||e===" "||[",",":",";"].includes(e))}catch(e){return nt.catch("Error in utils isHotkeyDisabledForAutocomplete: ",e),!1}},_k=(i,o,n)=>{try{return!!i.substring(o+1,n).startsWith(" ")}catch(e){return nt.catch("Error in utils isHotkeyFollowedBySpace: ",e),!1}},wk=(i,o,n=["@"])=>{try{let e=f7e(i),t=null;try{e&&typeof e.getSelection=="function"&&(t=e.getSelection())}catch{}if(t||(t=window.getSelection()),t?.rangeCount){let r=t.getRangeAt(0),a=r.startOffset,s=r?.commonAncestorContainer?.textContent;if(s){let c=-1;for(let p of n){let g=s.lastIndexOf(p,a),f=g>0?s.lastIndexOf(p,g-1):-1;if(g>c){let I=Ck(s,g,a),T=_k(s,g,a);if(I||T){if(f!==-1){let N=Ck(s,f,g),G=_k(s,f,g);!N&&!G&&(c=f)}}else c=g}}if(c!==-1){let p=s.substring(0,c),g=s.substring(r.endOffset),f=document.createElement("span");f.textContent=o,f.style.color="var(--velt-accent)";let I=Date.now()+"_"+Math.random().toString(36).substr(2,9);f.setAttribute("data-recently-added",I),setTimeout(()=>{f.hasAttribute("data-recently-added")&&f.removeAttribute("data-recently-added")},5e3);let T=r.commonAncestorContainer;if(T.nodeType===Node.TEXT_NODE){let N=T.parentNode;if(N){let G=document.createTextNode(p),z=document.createTextNode(g);N.replaceChild(z,T),N.insertBefore(f,z),N.insertBefore(G,f);try{let J=document.createRange();J.setStartAfter(f),J.collapse(!0),t?.removeAllRanges(),t?.addRange(J)}catch(J){nt.catch("Error positioning cursor after span:",J);try{let ce=document.createRange();ce.selectNodeContents(i),ce.collapse(!1),t?.removeAllRanges(),t?.addRange(ce)}catch(ce){nt.catch("Error with fallback cursor positioning:",ce)}}}}}}}}catch(e){nt.catch("Error in utils replaceWordAtCursor: ",e)}},Ok=()=>{try{let o=window.getSelection()?.getRangeAt(0),n=o?.commonAncestorContainer,e=o?.startContainer,t=o?.endContainer,r=[];r.push(n),r.push(e),r.push(t);let a=!1;for(let s of r)if(s&&Gi(s,[U.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,U.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,U.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,U.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(i){return nt.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",i),!1}},Ble=(i,o,n)=>{try{let e=document.querySelector(`[id=${i}]`);if(e)e.name=o,e.content=n;else{let t=document.createElement("meta");t.id=i,t.name=o,t.content=n,document.getElementsByTagName("head")[0].appendChild(t)}}catch{}},Vle=i=>{try{if(i){let o=document.querySelector(`[id=${i}]`);o&&o.remove()}}catch{}},Ule=()=>{try{let o=new Date().getTimezoneOffset(),n=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${n?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(i){return nt.catch("Error in utils getTimezone: ",i),""}},jle=()=>{try{let i=[];return document.querySelectorAll("*").forEach(n=>{(n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth||["auto","scroll"].includes(getComputedStyle(n).overflow))&&i.push(n)}),i}catch(i){return nt.catch("Error in utils getScrollableElements: ",i),[]}},$le=(i,o)=>Math.sqrt((i.x-o.x)**2+(i.y-o.y)**2),YH=(i,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let n=i;for(;n.children.length>0;){let e=null,t=Number.MAX_SAFE_INTEGER;for(let r=0;r<n.children.length;r++){let a=n.children[r],s=a.getBoundingClientRect(),c={x:s.left+s.width/2,y:s.top+s.height/2},p=$le(c,o);(s.top>=0||s.bottom<=window.innerHeight)&&s.width>0&&s.height>0&&p<=t&&(e=a,t=p)}if(e===null)break;n=e}return n}catch(n){return nt.catch("Error in utils getInnermostElement: ",n),null}},Hle=i=>{try{let{offsetWidth:o,offsetHeight:n,scrollTop:e}=i,t=i,r={x:o/2,y:e+n/2};for(;t.children.length>0;){let a=null,s=Number.MAX_SAFE_INTEGER;for(let c=0;c<t.children.length;c++){let p=t.children[c],g={x:p.offsetLeft+p.offsetWidth/2,y:p.offsetTop+p.offsetHeight/2},f=$le(g,r);p.offsetTop>=0&&p.offsetWidth>0&&p.offsetHeight>0&&f<=s&&(a=p,s=f)}if(a===null)break;t=a}return t}catch(o){return nt.catch("Error in utils getNestedInnermostElement: ",o),null}},zle=()=>{try{let i=window.innerWidth/2,o=window.innerHeight/2,n=document.elementFromPoint(i,o);for(;n&&n.tagName==="BODY";)o+=2,n=document.elementFromPoint(i,o);return n}catch(i){return nt.catch("Error in utils getCenteredBackgroundElement: ",i),null}},KH=(i,o,n=!1)=>{try{let e=i.getBoundingClientRect(),t=o.getBoundingClientRect(),r=o.offsetTop;n&&(r=r-e.height/2+t.height/2),i.scrollTo({top:r,behavior:"smooth"})}catch(e){nt.catch("Error in utils nestedScrollIntoView: ",e)}},Ak=(i,o=!0)=>{try{let n=document.body.getBoundingClientRect(),e=i.getBoundingClientRect(),t=e.top-n.top,r=window.innerHeight,a=t;o&&(a=a-r/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(n){nt.catch("Error in utils scrollIntoView: ",n)}},Gle=(i=!1)=>{try{let o=!0;return i&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return nt.catch("Error in utils isTouchDevice: ",o),!1}},Wle=(i,o,n)=>{try{return(1-n)*i+n*o}catch(e){nt.catch("Error in utils lerp: ",e)}return 0},qle=(i,o)=>{try{if(i===void 0)return i;if(i=i.replace("#",""),i.length===6){let n=parseInt(i,16),e=(n>>16)+o;e>255&&(e=255),e<0&&(e=0);let t=(n&255)+o;t>255&&(t=255),t<0&&(t=0);let r=(n>>8&255)+o;return r>255&&(r=255),r<0&&(r=0),`#${(t|r<<8|e<<16).toString(16)}`}else return i}catch(n){nt.catch("Error in utils multiplyColor: ",n)}return i},Yle=i=>{try{return i in U.TEXT_COLOR_MAP?U.TEXT_COLOR_MAP[i]:"#141416"}catch(o){return nt.catch("Error in generateUserColor:",o),"#141416"}},od=()=>{try{let i=localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(i)return JSON.parse(i)}catch(i){return nt.catch("Error in getDefaultMediaStreamOptions:",i),{}}},Pk=(i,o)=>{try{let n=o*(Math.PI/180),e=Math.cos(n);return e?i/e:i}catch(n){return nt.catch("Error in calculateHypotenuse:",n),0}},ZH=(i,o,n=!0)=>{try{let e=[],t=n?i:i.parentNode;for(;t;)e.push(t),t=t.parentNode;let r=n?o:o.parentNode;for(;r;){if(e.indexOf(r)!==-1)return r;r=r.parentNode}return null}catch(e){return nt.catch("Error in utils findCommonParent: ",e),null}},XH=(i,o,n,e)=>{let t=n.getBoundingClientRect(),r=e.getBoundingClientRect(),a=t.left+i,s=t.top+o,c=a-r.left,p=s-r.top;return{x:c,y:p}},Mg=i=>{try{let o={height:0,width:0};if(typeof i?.getBBox=="function"){let n=i?.getBBox(),e=i?.getBoundingClientRect();o.height=parseFloat(e?.height||n.height||0),o.width=parseFloat(e?.width||n.width||0)}else{let n=window.getComputedStyle(i);if(o.height=i?.clientHeight||parseFloat(n.getPropertyValue("height"))||0,o.width=i?.clientWidth||parseFloat(n.getPropertyValue("width"))||0,i?.getBoundingClientRect&&typeof i?.getBoundingClientRect=="function"){let e=i?.getBoundingClientRect();o?.height||(o.height=e?.height||i?.clientHeight||i?.offsetHeight||0),o?.width||(o.width=e?.width||i?.clientWidth||i?.offsetWidth||0)}}return o}catch(o){return nt.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},im=i=>{try{let o=i;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return nt.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},f7e=i=>{try{let o=i;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){nt.catch("Error in utils findShadowRoot: ",o)}return null};var W0=i=>i===null||typeof i>"u",q0=(i,o)=>{try{return!!i?.closest(`[${o}]`)}catch(n){return nt.catch("Error in utils hasParentWithAttribute: ",n),!1}},QH=(i,o=!0)=>{try{let n=[];if(!i||!(i instanceof HTMLElement))return[];o&&n.push(i);for(let e=0;e<i.children.length;e++){let t=i.children[e];n=n.concat(QH(t))}return n}catch(n){return nt.catch("Error in utils getAllNestedChildren: ",n),[]}},Kle=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(i){return nt.catch("Error in utils isTabActive: ",i),!1}},JH=i=>{try{let o="",n=i?.getAttribute("src");if(n)o=`${Rn(n)}`;else{let e=i?.querySelectorAll("source");if(e&&e.length>0){let r=e[0]?.getAttribute("src");r&&(o=`${Rn(r)}`)}}return o}catch{return""}},qe=i=>{try{return!(i&&(i?.children?.length>0||i?.textContent?.trim()?.length>0))}catch(o){return nt.catch("Error in utils isTemplateEmpty: ",o),!0}},Aa=(i,o)=>{try{if(!i||!o)return;let n=[],e="",t=0;for(let c=0;c<o.length;c++){let p=o[c];p==="["?(t++,t===1&&e&&(n.push(e),e=""),e+=p):p==="]"?(t--,e+=p,t===0&&(n.push(e),e="")):p==="."&&t===0?e&&(n.push(e),e=""):e+=p}e&&n.push(e);let r,a=E({},i),s=n.reduce((c,p)=>{if(c==null)return;Ni(c)&&(r=c,c=c());let g=p.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(g){let I=g[1];if(/^\d+$/.test(I)){let T=parseInt(I,10);return Array.isArray(c)?c[T]:void 0}if(I.startsWith("'")&&I.endsWith("'")||I.startsWith('"')&&I.endsWith('"')){let T=I.slice(1,-1);return c[T]}if(I.includes(".")||I.includes("[")){let T=Aa(a,I);Ni(T)&&(T=T());let N=T?.toString()||"";return c[N]}if(a[I]!==void 0){let T=a[I];return Ni(T)&&(T=T()),c[T]}return c[I]}let f=p;return(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))&&(f=p.slice(1,-1)),f==="length"&&Array.isArray(c)?c.length:c[f]},i);return r?Oi(()=>{try{let c=E({},i);return n.reduce((p,g)=>{if(p==null)return;Ni(p)&&(p=p());let f=g.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(f){let T=f[1];if(/^\d+$/.test(T)){let N=parseInt(T,10);return Array.isArray(p)?p[N]:void 0}if(T.startsWith("'")&&T.endsWith("'")||T.startsWith('"')&&T.endsWith('"')){let N=T.slice(1,-1);return p[N]}if(T.includes(".")||T.includes("[")){let N=Aa(c,T);Ni(N)&&(N=N());let G=N?.toString()||"";return p[G]}if(c[T]!==void 0){let N=c[T];return Ni(N)&&(N=N()),p[N]}return p[T]}let I=g;return(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(I=g.slice(1,-1)),p[I]},i)}catch{return""}}):s}catch{return""}},Jh=(i,o)=>{try{return!!(i?.locationId&&(i.locationId===o?.locationId||o?.location?.id===String(i.locationId))||i?.location?.id&&(i.location.id===o?.location?.id||i.location.id===String(o?.locationId)))}catch(n){return nt.catch("Error in utils isLocationSame: ",n),!1}},Zle=()=>{try{let i=document.activeElement,o=new Set,n=10,e=0;for(;i&&i.shadowRoot&&!(o.has(i)||(o.add(i),i=i.shadowRoot.activeElement,e++,e>n)););return i}catch(i){return nt.catch("Error in utils getActiveElement: ",i),null}},Kt=(i,o)=>{try{return typeof i=="object"&&typeof o=="object"?JSON.stringify(i)===JSON.stringify(o):i===o}catch{return!1}},Y0=i=>{try{let o=JSON.parse(JSON.stringify(i));return i?.clientDocumentId&&(o.documentId=i.clientDocumentId),i?.clientOrganizationId&&(o.organizationId=i.clientOrganizationId),delete o?.clientDocumentId,delete o?.clientOrganizationId,delete o?.veltFolderId,delete o?.parentVeltFolderId,delete o?.pageInfo,o}catch{return i}},Xr=i=>{try{if(!i.some(a=>a?.value?.data))return{};let o=null,n=i.reduce((a,s)=>Math.max(a,s.timestamp),0),e=i.find(a=>a.timestamp===n);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let r=i.map(a=>a.value).reduce((a,s)=>({data:E(E({},a?.data??{}),s?.data??{})}),{});return r.operation=o,r}catch{return{}}},rd=(i,o,n)=>Q(null,null,function*(){try{let e=0;for(;e<=(n.retryCount||0);)try{let t=yield i();if(!t)return{success:!1,statusCode:400,message:`${o} failed: No response received`};if(t.statusCode===void 0)return{success:!1,statusCode:400,message:`${o} failed: Response missing statusCode`};if(t.statusCode!==200){if(e++,e>(n.retryCount||0))return{success:!1,statusCode:t.statusCode,message:`${o} failed after ${e} attempts with status code ${t.statusCode}`};n.retryDelay&&(yield new Promise(r=>setTimeout(r,n.retryDelay)));continue}return t}catch(t){if(e++,e>(n.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${t instanceof Error?t.message:"Unknown error"}`};n.retryDelay&&(yield new Promise(r=>setTimeout(r,n.retryDelay)))}return{success:!1,statusCode:500,message:`${o} failed: Maximum retry attempts exceeded`}}catch(e){return{success:!1,statusCode:500,message:`${o} failed with unexpected error: ${e instanceof Error?e.message:"Unknown error"}`}}}),Xle=i=>{try{return!i||!i?.access?[]:Object.keys(i.access).sort().map(t=>i.access?.[t]?.map(r=>`${t}:${r}`)??[]).reduce((t,r)=>t.flatMap(a=>r.map(s=>[...a,s])),[[]]).map(t=>t.join("_"))}catch(o){return nt.catch("Error in utils generateProcessedContext: ",o),[]}},Qle=i=>{try{if(!i||!i?.access)return[];let o=Object.keys(i.access).sort(),e=(r=>{let a=[],s=Math.pow(2,r.length);for(let c=1;c<s;c++){let p=[];for(let g=0;g<r.length;g++)c&1<<g&&p.push(r[g]);a.push(p)}return a})(o),t=[];for(let r of e){let a=r.map(s=>{let c=i.access?.[s];return c==null?null:`${s}:${c}`}).filter(s=>s!==null);a.length>0&&t.push(a.join("_"))}return[...new Set(t)]}catch(o){return nt.catch("Error in utils generateAllContextCombos: ",o),[]}},Jle=({input:i})=>{try{if(!i||!i?.access)return[];let o=i?.access,n=Object.keys(o).sort(),e=[];for(let r of n){let a=o[r];a!=null&&Array.isArray(a)&&a.length>0&&e.push({key:r,values:a})}return e.length===0?[]:e.reduce((r,{key:a,values:s})=>r.length===0?s.map(c=>[{key:a,value:c}]):r.flatMap(c=>s.map(p=>[...c,{key:a,value:p}])),[]).map(r=>{let a={};return r.forEach(({key:s,value:c})=>{a[s]=c}),{access:a}})}catch(o){return nt.catch("Error in utils expandContextArraysToSingleValues: ",o),[]}},ece=({input:i})=>{try{if(!i||i.length===0)return{access:{}};let o=new Set;i.forEach(e=>{e?.access&&Object.keys(e.access).forEach(t=>o.add(t))});let n={};for(let e of Array.from(o).sort()){let t=new Set;i.forEach(r=>{if(r?.access){let a=r.access[e];a!=null&&t.add(a)}}),n[e]=t.size>0?Array.from(t).sort():null}return{access:n}}catch(o){return nt.catch("Error in utils combineContextsToArrays: ",o),{access:{}}}},ad=t=>Q(null,[t],function*({data:i,getSdkProxy:o,userId:n,methodName:e}){try{let r="sdkproxyencryptionanddecryptiononsdk"+(n??""),a=yield v7e({data:i,key:r}),s=(yield o({veltData:a}))?.data?.data?.veltData||{};return yield j0(s,r)}catch(r){return nt.catch("Error in utils sdkProxyEncryptDecrypt: "+(e??""),r),i}}),v7e=n=>Q(null,[n],function*({data:i,key:o}){try{return yield bl(i,o)}catch{return i}}),ez=(i,o)=>Q(null,null,function*(){try{let n=0;for(;n<=(o.retryCount||0);)try{let e=yield i();if(!e)throw new Error("No response received");return e}catch{if(n++,n>=(o.retryCount||0))return null;o.retryDelay&&(yield new Promise(t=>setTimeout(t,o.retryDelay)))}return null}catch{return null}}),Qr=i=>{try{if(i&&typeof i=="object"){let o=JSON.parse(JSON.stringify(i));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,o}else return null}catch(o){return nt.catch("Error in utils getUserForClient: ",o),null}},Zi=({url:i,apiProxyDomain:o})=>{try{if(o){let n=new URL(i);n.origin&&(i=i.replace(n.origin,o))}return i}catch(n){return nt.catch("Error in utils getResolvedApiUrl: ",n),i}},tce=(i,o)=>{try{if(!i||!(i instanceof Element))return!1;let n,e;if(o&&typeof o.x=="number"&&typeof o.y=="number")n=o.x,e=o.y;else{let r=i.getBoundingClientRect();n=r.left+r.width/2,e=r.top+r.height/2}let t=document.elementFromPoint(n,e);return!(!t||t===i||i.contains(t))}catch{return!1}};var et=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.liveStateSyncEvents=Object.values(K.Events.LiveStateSync||{})?.filter(t=>![K.Events.LiveStateSync.ON_ACTION_TRIGGERED].includes(t)),this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3;try{this.updateDefaultProperties({sdkVersion:ga()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(t){nt.catch("Error in AnalyticsService constructor: ",t)}}updateDefaultProperties(e={}){this.defaultProperties=E(E({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(t){nt.catch("Error in AnalyticsService setInstalledFeature: ",t)}}setFeatureConfig({feature:e,config:t}){try{this.defaultProperties.featureConfigs||(this.defaultProperties.featureConfigs={}),this.defaultProperties.featureConfigs[e]||(this.defaultProperties.featureConfigs[e]={}),this.defaultProperties.featureConfigs[e]=E(E({},this.defaultProperties.featureConfigs[e]),t)}catch(r){nt.catch("Error in AnalyticsService setFeatureConfig: ",r)}}setSF(e){try{this.sf=e}catch(t){nt.catch("Error in AnalyticsService setSF: ",t)}}setAuthService(e){try{this.authService=e}catch(t){nt.catch("Error in AnalyticsService setAuthService: ",t)}}setCommentService(e){try{this.commentService=e}catch(t){nt.catch("Error in AnalyticsService setCommentService: ",t)}}setConfigService(e){try{this.configService=e}catch(t){nt.catch("Error in AnalyticsService setConfigService: ",t)}}setDomService(e){try{this.domService=e}catch(t){nt.catch("Error in AnalyticsService setDomService: ",t)}}setLiveStateService(e){try{this.liveStateService=e}catch(t){nt.catch("Error in AnalyticsService setLiveStateService: ",t)}}setAreaService(e){try{this.areaService=e}catch(t){nt.catch("Error in AnalyticsService setAreaService: ",t)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(t){nt.catch("Error in AnalyticsService setRecorderAnnotationService: ",t)}}setReactionService(e){try{this.reactionService=e}catch(t){nt.catch("Error in AnalyticsService setReactionService: ",t)}}setUserService(e){try{this.userService=e}catch(t){nt.catch("Error in AnalyticsService setUserService: ",t)}}identifyUser(e,t,r={}){try{this.userId=e;let a=typeof t=="object"?JSON.parse(JSON.stringify(t)):t;this.userService?.userDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let s=this.defaultProperties?this.defaultProperties.apiKey:null;if(Dn.production||Dn.staging){let c=Date.now(),p={userId:e,clientUserId:this.user?.userId,traits:D(E({},a),{apiKey:s,forceReset:r?.forceReset,eventTimestamp:c}),properties:D(E({},this.defaultProperties),{eventTimestamp:c}),sf:this.sf,context:this.getContext(),eventTimestamp:c};this.setAnalytics("identify",p)}if(this.userId&&this.draftEvents?.length){let c=this.draftEvents?.slice();this.draftEvents=[],c?.forEach(p=>{switch(p.type){case"track":p?.data?.eventName&&this.trackEvent(p.data.eventName,p.data.properties,p.data.mergeDefaultProperties,p.data.userId,p.data.clientUserId);break;default:break}})}}catch(a){nt.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,t="",r={}){try{if((Dn.production||Dn.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:r,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){nt.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(c){return Q(this,arguments,function*(e,t={},r=!0,a,s){try{if(this.sf&&Ele.includes(e))return;if(Dn.production||Dn.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return;let p=Date.now();if(this.eventRateLimitCache[e]&&p-this.eventRateLimitCache[e].timestamp<this.TIME_WINDOW_MS){if(this.eventRateLimitCache[e].count>=this.EVENT_LIMIT){if(!this.eventRateLimitCache[e].rateLimitExceededEventTriggered){this.eventRateLimitCache[e].rateLimitExceededEventTriggered=!0,this.eventRateLimitCache[e].blockedForSession=!0;let g=E({eventName:e},t||{});this.triggerTrackEvent(K.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,g,r,a,s)}return}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:p,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,t,r,a,s)}else t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.draftEvents.push({type:"track",data:{eventName:e,properties:t,mergeDefaultProperties:r,userId:a,clientUserId:s}})}catch(p){nt.catch("Error in AnalyticsService trackEvent: ",p)}})}triggerTrackEvent(c){return Q(this,arguments,function*(e,t={},r=!0,a,s){try{r&&(t||(t={}),t=E(E({},t),this.defaultProperties));let p;if(t?.annotationId){let f=t.annotationId;if(!p&&this.commentService){let I=this.commentService.getAnnotationById(f);I?.metadata&&(p=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId);let T=this.commentService.getMultiThreadAnnotationById(f);T?.metadata&&(p=T.metadata),T?.targetElementId&&(t.targetElementId=T.targetElementId)}if(!p&&this.recorderAnnotationService){let I=this.recorderAnnotationService.getAnnotationById(f);I?.metadata&&(p=I.metadata)}if(!p&&this.reactionService){let I=this.reactionService.getAnnotationById(f);I?.metadata&&(p=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId)}if(!p&&this.areaService){let I=this.areaService.getAnnotationById(f);I?.metadata&&(p=I.metadata)}}if(p&&typeof p=="object"&&(t=E(E({},t),p)),t&&typeof t=="object"&&(t=D(E({},t),{userId:this.userId||a,clientUserId:this.user?.userId||s}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),t?.sessionTabId||(t.sessionTabId=this.domService?.getTabId()),this.liveStateSyncEvents.includes(e))){let f=this.liveStateService?.getSemStats();f&&!t?.semStats&&(t.semStats=f)}let g={userId:this.userId||a,clientUserId:this.user?.userId||s,event:e,properties:t,sf:this.sf,context:this.getContext(),eventTimestamp:t?.eventTimestamp};return this.setAnalytics("track",g)}catch(p){nt.catch("Error in AnalyticsService triggerTrackEvent: ",p)}})}setAnalytics(e,t){return Q(this,null,function*(){try{return navigator.onLine?Ki(this.functions,Zi({url:Dn.cloudFunction.sa,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({type:e,data:t}).catch(a=>{nt.warn("Error in AnalyticsService setAnalytics promise: ",e,a)}):void 0}catch(r){nt.catch("Error in AnalyticsService setAnalytics: ",r)}})}trackAuthenticatedEvent(e,t={},r=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,t,r):((!t||typeof t!="object")&&(t={}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.authService?.getUser$()?.pipe(Fe(a=>!!a),ot(1))?.subscribe(()=>{this.trackEvent(e,t,r)})))}catch(a){nt.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},t=Mi();return e.os={name:t?.deviceInfo?.osName,version:t?.deviceInfo?.osVersion},e.page={path:t?.path,title:t?.title,url:t?.url},e.screen={height:t?.deviceInfo?.screenHeight,width:t?.deviceInfo?.screenWidth},e.app={name:t?.deviceInfo?.browserName,version:t?.deviceInfo?.browserVersion},e.device={type:t?.deviceInfo?.deviceType},e.timezone=Ule(),e.userAgent=t?.deviceInfo?.userAgent,e}catch(e){nt.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(t){return new(t||o)(ee(Io))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var y=(()=>{let o=class o{get debugMode(){return Dle()}get debugAuthMode(){try{return!!sessionStorage.getItem("debugAuthMode")}catch{return!1}}get debugPerfMode(){return wle()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new ve(!0),this.log("%c[WB] Creating SERVICE LoggingService","color: blue;")}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.catch("Error in LoggingService enableLogs: ",e)}}disableLogs(){try{if(this.logsEnabled$.value===!1)return;this.logsEnabled$.next(!1)}catch(e){this.catch("Error in LoggingService disableLogs: ",e)}}debugAuth(e,...t){this.debugAuthMode&&console.log(e,...t)}log(e,...t){this.debugMode&&console.log(e,...t)}logPerf(e,...t){this.debugPerfMode&&console.log(e,...t)}warn(e,...t){this.debugMode&&console.warn(e,...t)}error(e,...t){this.debugMode&&console.error(e,...t)}debug(e,...t){this.debugMode&&console.debug(e,...t)}info(e,...t){this.debugMode&&console.info(e,...t)}catch(e,t,r,a=!1){try{let s=t?.message;this.logsEnabled$.value&&(s?.toLowerCase()?.includes("permission denied")||s?.toLowerCase()?.includes("permission_denied")||(t!==void 0?console.warn("Velt: ",e,t):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(K.Events.Core.SDK_ERROR,E({sourceMethod:e,message:(t?.message?t?.message:t)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},r||{}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var nce=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ice={};var gp,tz;(function(){var i;function o(be,Se){function Ae(){}Ae.prototype=Se.prototype,be.D=Se.prototype,be.prototype=new Ae,be.prototype.constructor=be,be.C=function(Ce,fe,we){for(var Ne=Array(arguments.length-2),to=2;to<arguments.length;to++)Ne[to-2]=arguments[to];return Se.prototype[fe].apply(Ce,Ne)}}function n(){this.blockSize=-1}function e(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}o(e,n),e.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function t(be,Se,Ae){Ae||(Ae=0);var Ce=Array(16);if(typeof Se=="string")for(var fe=0;16>fe;++fe)Ce[fe]=Se.charCodeAt(Ae++)|Se.charCodeAt(Ae++)<<8|Se.charCodeAt(Ae++)<<16|Se.charCodeAt(Ae++)<<24;else for(fe=0;16>fe;++fe)Ce[fe]=Se[Ae++]|Se[Ae++]<<8|Se[Ae++]<<16|Se[Ae++]<<24;Se=be.g[0],Ae=be.g[1],fe=be.g[2];var we=be.g[3],Ne=Se+(we^Ae&(fe^we))+Ce[0]+3614090360&4294967295;Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[1]+3905402710&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[2]+606105819&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[3]+3250441966&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[4]+4118548399&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[5]+1200080426&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[6]+2821735955&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[7]+4249261313&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[8]+1770035416&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[9]+2336552879&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[10]+4294925233&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[11]+2304563134&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[12]+1804603682&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[13]+4254626195&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[14]+2792965006&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[15]+1236535329&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(fe^we&(Ae^fe))+Ce[1]+4129170786&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[6]+3225465664&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[11]+643717713&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[0]+3921069994&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[5]+3593408605&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[10]+38016083&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[15]+3634488961&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[4]+3889429448&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[9]+568446438&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[14]+3275163606&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[3]+4107603335&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[8]+1163531501&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[13]+2850285829&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[2]+4243563512&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[7]+1735328473&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[12]+2368359562&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(Ae^fe^we)+Ce[5]+4294588738&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[8]+2272392833&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[11]+1839030562&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[14]+4259657740&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[1]+2763975236&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[4]+1272893353&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[7]+4139469664&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[10]+3200236656&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[13]+681279174&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[0]+3936430074&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[3]+3572445317&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[6]+76029189&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[9]+3654602809&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[12]+3873151461&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[15]+530742520&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[2]+3299628645&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(fe^(Ae|~we))+Ce[0]+4096336452&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[7]+1126891415&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[14]+2878612391&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[5]+4237533241&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[12]+1700485571&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[3]+2399980690&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[10]+4293915773&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[1]+2240044497&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[8]+1873313359&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[15]+4264355552&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[6]+2734768916&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[13]+1309151649&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[4]+4149444226&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[11]+3174756917&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[2]+718787259&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[9]+3951481745&4294967295,be.g[0]=be.g[0]+Se&4294967295,be.g[1]=be.g[1]+(fe+(Ne<<21&4294967295|Ne>>>11))&4294967295,be.g[2]=be.g[2]+fe&4294967295,be.g[3]=be.g[3]+we&4294967295}e.prototype.u=function(be,Se){Se===void 0&&(Se=be.length);for(var Ae=Se-this.blockSize,Ce=this.B,fe=this.h,we=0;we<Se;){if(fe==0)for(;we<=Ae;)t(this,be,we),we+=this.blockSize;if(typeof be=="string"){for(;we<Se;)if(Ce[fe++]=be.charCodeAt(we++),fe==this.blockSize){t(this,Ce),fe=0;break}}else for(;we<Se;)if(Ce[fe++]=be[we++],fe==this.blockSize){t(this,Ce),fe=0;break}}this.h=fe,this.o+=Se},e.prototype.v=function(){var be=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);be[0]=128;for(var Se=1;Se<be.length-8;++Se)be[Se]=0;var Ae=8*this.o;for(Se=be.length-8;Se<be.length;++Se)be[Se]=Ae&255,Ae/=256;for(this.u(be),be=Array(16),Se=Ae=0;4>Se;++Se)for(var Ce=0;32>Ce;Ce+=8)be[Ae++]=this.g[Se]>>>Ce&255;return be};function r(be,Se){var Ae=s;return Object.prototype.hasOwnProperty.call(Ae,be)?Ae[be]:Ae[be]=Se(be)}function a(be,Se){this.h=Se;for(var Ae=[],Ce=!0,fe=be.length-1;0<=fe;fe--){var we=be[fe]|0;Ce&&we==Se||(Ae[fe]=we,Ce=!1)}this.g=Ae}var s={};function c(be){return-128<=be&&128>be?r(be,function(Se){return new a([Se|0],0>Se?-1:0)}):new a([be|0],0>be?-1:0)}function p(be){if(isNaN(be)||!isFinite(be))return f;if(0>be)return z(p(-be));for(var Se=[],Ae=1,Ce=0;be>=Ae;Ce++)Se[Ce]=be/Ae|0,Ae*=4294967296;return new a(Se,0)}function g(be,Se){if(be.length==0)throw Error("number format error: empty string");if(Se=Se||10,2>Se||36<Se)throw Error("radix out of range: "+Se);if(be.charAt(0)=="-")return z(g(be.substring(1),Se));if(0<=be.indexOf("-"))throw Error('number format error: interior "-" character');for(var Ae=p(Math.pow(Se,8)),Ce=f,fe=0;fe<be.length;fe+=8){var we=Math.min(8,be.length-fe),Ne=parseInt(be.substring(fe,fe+we),Se);8>we?(we=p(Math.pow(Se,we)),Ce=Ce.j(we).add(p(Ne))):(Ce=Ce.j(Ae),Ce=Ce.add(p(Ne)))}return Ce}var f=c(0),I=c(1),T=c(16777216);i=a.prototype,i.m=function(){if(G(this))return-z(this).m();for(var be=0,Se=1,Ae=0;Ae<this.g.length;Ae++){var Ce=this.i(Ae);be+=(0<=Ce?Ce:4294967296+Ce)*Se,Se*=4294967296}return be},i.toString=function(be){if(be=be||10,2>be||36<be)throw Error("radix out of range: "+be);if(N(this))return"0";if(G(this))return"-"+z(this).toString(be);for(var Se=p(Math.pow(be,6)),Ae=this,Ce="";;){var fe=Oe(Ae,Se).g;Ae=J(Ae,fe.j(Se));var we=((0<Ae.g.length?Ae.g[0]:Ae.h)>>>0).toString(be);if(Ae=fe,N(Ae))return we+Ce;for(;6>we.length;)we="0"+we;Ce=we+Ce}},i.i=function(be){return 0>be?0:be<this.g.length?this.g[be]:this.h};function N(be){if(be.h!=0)return!1;for(var Se=0;Se<be.g.length;Se++)if(be.g[Se]!=0)return!1;return!0}function G(be){return be.h==-1}i.l=function(be){return be=J(this,be),G(be)?-1:N(be)?0:1};function z(be){for(var Se=be.g.length,Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=~be.g[Ce];return new a(Ae,~be.h).add(I)}i.abs=function(){return G(this)?z(this):this},i.add=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0,fe=0;fe<=Se;fe++){var we=Ce+(this.i(fe)&65535)+(be.i(fe)&65535),Ne=(we>>>16)+(this.i(fe)>>>16)+(be.i(fe)>>>16);Ce=Ne>>>16,we&=65535,Ne&=65535,Ae[fe]=Ne<<16|we}return new a(Ae,Ae[Ae.length-1]&-2147483648?-1:0)};function J(be,Se){return be.add(z(Se))}i.j=function(be){if(N(this)||N(be))return f;if(G(this))return G(be)?z(this).j(z(be)):z(z(this).j(be));if(G(be))return z(this.j(z(be)));if(0>this.l(T)&&0>be.l(T))return p(this.m()*be.m());for(var Se=this.g.length+be.g.length,Ae=[],Ce=0;Ce<2*Se;Ce++)Ae[Ce]=0;for(Ce=0;Ce<this.g.length;Ce++)for(var fe=0;fe<be.g.length;fe++){var we=this.i(Ce)>>>16,Ne=this.i(Ce)&65535,to=be.i(fe)>>>16,St=be.i(fe)&65535;Ae[2*Ce+2*fe]+=Ne*St,ce(Ae,2*Ce+2*fe),Ae[2*Ce+2*fe+1]+=we*St,ce(Ae,2*Ce+2*fe+1),Ae[2*Ce+2*fe+1]+=Ne*to,ce(Ae,2*Ce+2*fe+1),Ae[2*Ce+2*fe+2]+=we*to,ce(Ae,2*Ce+2*fe+2)}for(Ce=0;Ce<Se;Ce++)Ae[Ce]=Ae[2*Ce+1]<<16|Ae[2*Ce];for(Ce=Se;Ce<2*Se;Ce++)Ae[Ce]=0;return new a(Ae,0)};function ce(be,Se){for(;(be[Se]&65535)!=be[Se];)be[Se+1]+=be[Se]>>>16,be[Se]&=65535,Se++}function ye(be,Se){this.g=be,this.h=Se}function Oe(be,Se){if(N(Se))throw Error("division by zero");if(N(be))return new ye(f,f);if(G(be))return Se=Oe(z(be),Se),new ye(z(Se.g),z(Se.h));if(G(Se))return Se=Oe(be,z(Se)),new ye(z(Se.g),Se.h);if(30<be.g.length){if(G(be)||G(Se))throw Error("slowDivide_ only works with positive integers.");for(var Ae=I,Ce=Se;0>=Ce.l(be);)Ae=$e(Ae),Ce=$e(Ce);var fe=Be(Ae,1),we=Be(Ce,1);for(Ce=Be(Ce,2),Ae=Be(Ae,2);!N(Ce);){var Ne=we.add(Ce);0>=Ne.l(be)&&(fe=fe.add(Ae),we=Ne),Ce=Be(Ce,1),Ae=Be(Ae,1)}return Se=J(be,fe.j(Se)),new ye(fe,Se)}for(fe=f;0<=be.l(Se);){for(Ae=Math.max(1,Math.floor(be.m()/Se.m())),Ce=Math.ceil(Math.log(Ae)/Math.LN2),Ce=48>=Ce?1:Math.pow(2,Ce-48),we=p(Ae),Ne=we.j(Se);G(Ne)||0<Ne.l(be);)Ae-=Ce,we=p(Ae),Ne=we.j(Se);N(we)&&(we=I),fe=fe.add(we),be=J(be,Ne)}return new ye(fe,be)}i.A=function(be){return Oe(this,be).h},i.and=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)&be.i(Ce);return new a(Ae,this.h&be.h)},i.or=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)|be.i(Ce);return new a(Ae,this.h|be.h)},i.xor=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)^be.i(Ce);return new a(Ae,this.h^be.h)};function $e(be){for(var Se=be.g.length+1,Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=be.i(Ce)<<1|be.i(Ce-1)>>>31;return new a(Ae,be.h)}function Be(be,Se){var Ae=Se>>5;Se%=32;for(var Ce=be.g.length-Ae,fe=[],we=0;we<Ce;we++)fe[we]=0<Se?be.i(we+Ae)>>>Se|be.i(we+Ae+1)<<32-Se:be.i(we+Ae);return new a(fe,be.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,tz=ice.Md5=e,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=p,a.fromString=g,gp=ice.Integer=a}).apply(typeof nce<"u"?nce:typeof self<"u"?self:typeof window<"u"?window:{});var Mk=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},up={};var nz,C7e,K0,iz,tI,kk,oz,rz,az;(function(){var i,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(j,ie,ge){return j==Array.prototype||j==Object.prototype||(j[ie]=ge.value),j};function n(j){j=[typeof globalThis=="object"&&globalThis,j,typeof window=="object"&&window,typeof self=="object"&&self,typeof Mk=="object"&&Mk];for(var ie=0;ie<j.length;++ie){var ge=j[ie];if(ge&&ge.Math==Math)return ge}throw Error("Cannot find global object")}var e=n(this);function t(j,ie){if(ie)e:{var ge=e;j=j.split(".");for(var Te=0;Te<j.length-1;Te++){var We=j[Te];if(!(We in ge))break e;ge=ge[We]}j=j[j.length-1],Te=ge[j],ie=ie(Te),ie!=Te&&ie!=null&&o(ge,j,{configurable:!0,writable:!0,value:ie})}}function r(j,ie){j instanceof String&&(j+="");var ge=0,Te=!1,We={next:function(){if(!Te&&ge<j.length){var st=ge++;return{value:ie(st,j[st]),done:!1}}return Te=!0,{done:!0,value:void 0}}};return We[Symbol.iterator]=function(){return We},We}t("Array.prototype.values",function(j){return j||function(){return r(this,function(ie,ge){return ge})}});var a=a||{},s=this||self;function c(j){var ie=typeof j;return ie=ie!="object"?ie:j?Array.isArray(j)?"array":ie:"null",ie=="array"||ie=="object"&&typeof j.length=="number"}function p(j){var ie=typeof j;return ie=="object"&&j!=null||ie=="function"}function g(j,ie,ge){return j.call.apply(j.bind,arguments)}function f(j,ie,ge){if(!j)throw Error();if(2<arguments.length){var Te=Array.prototype.slice.call(arguments,2);return function(){var We=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(We,Te),j.apply(ie,We)}}return function(){return j.apply(ie,arguments)}}function I(j,ie,ge){return I=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?g:f,I.apply(null,arguments)}function T(j,ie){var ge=Array.prototype.slice.call(arguments,1);return function(){var Te=ge.slice();return Te.push.apply(Te,arguments),j.apply(this,Te)}}function N(j,ie){function ge(){}ge.prototype=ie.prototype,j.aa=ie.prototype,j.prototype=new ge,j.prototype.constructor=j,j.Qb=function(Te,We,st){for(var Lt=Array(arguments.length-2),ho=2;ho<arguments.length;ho++)Lt[ho-2]=arguments[ho];return ie.prototype[We].apply(Te,Lt)}}function G(j){let ie=j.length;if(0<ie){let ge=Array(ie);for(let Te=0;Te<ie;Te++)ge[Te]=j[Te];return ge}return[]}function z(j,ie){for(let ge=1;ge<arguments.length;ge++){let Te=arguments[ge];if(c(Te)){let We=j.length||0,st=Te.length||0;j.length=We+st;for(let Lt=0;Lt<st;Lt++)j[We+Lt]=Te[Lt]}else j.push(Te)}}class J{constructor(ie,ge){this.i=ie,this.j=ge,this.h=0,this.g=null}get(){let ie;return 0<this.h?(this.h--,ie=this.g,this.g=ie.next,ie.next=null):ie=this.i(),ie}}function ce(j){return/^[\s\xa0]*$/.test(j)}function ye(){var j=s.navigator;return j&&(j=j.userAgent)?j:""}function Oe(j){return Oe[" "](j),j}Oe[" "]=function(){};var $e=ye().indexOf("Gecko")!=-1&&!(ye().toLowerCase().indexOf("webkit")!=-1&&ye().indexOf("Edge")==-1)&&!(ye().indexOf("Trident")!=-1||ye().indexOf("MSIE")!=-1)&&ye().indexOf("Edge")==-1;function Be(j,ie,ge){for(let Te in j)ie.call(ge,j[Te],Te,j)}function be(j,ie){for(let ge in j)ie.call(void 0,j[ge],ge,j)}function Se(j){let ie={};for(let ge in j)ie[ge]=j[ge];return ie}let Ae="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ce(j,ie){let ge,Te;for(let We=1;We<arguments.length;We++){Te=arguments[We];for(ge in Te)j[ge]=Te[ge];for(let st=0;st<Ae.length;st++)ge=Ae[st],Object.prototype.hasOwnProperty.call(Te,ge)&&(j[ge]=Te[ge])}}function fe(j){var ie=1;j=j.split(":");let ge=[];for(;0<ie&&j.length;)ge.push(j.shift()),ie--;return j.length&&ge.push(j.join(":")),ge}function we(j){s.setTimeout(()=>{throw j},0)}function Ne(){var j=qt;let ie=null;return j.g&&(ie=j.g,j.g=j.g.next,j.g||(j.h=null),ie.next=null),ie}class to{constructor(){this.h=this.g=null}add(ie,ge){let Te=St.get();Te.set(ie,ge),this.h?this.h.next=Te:this.g=Te,this.h=Te}}var St=new J(()=>new It,j=>j.reset());class It{constructor(){this.next=this.g=this.h=null}set(ie,ge){this.h=ie,this.g=ge,this.next=null}reset(){this.next=this.g=this.h=null}}let bt,Nt=!1,qt=new to,Ht=()=>{let j=s.Promise.resolve(void 0);bt=()=>{j.then(Zt)}};var Zt=()=>{for(var j;j=Ne();){try{j.h.call(j.g)}catch(ge){we(ge)}var ie=St;ie.j(j),100>ie.h&&(ie.h++,j.next=ie.g,ie.g=j)}Nt=!1};function bi(){this.s=this.s,this.C=this.C}bi.prototype.s=!1,bi.prototype.ma=function(){this.s||(this.s=!0,this.N())},bi.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Jt(j,ie){this.type=j,this.g=this.target=ie,this.defaultPrevented=!1}Jt.prototype.h=function(){this.defaultPrevented=!0};var Jn=(function(){if(!s.addEventListener||!Object.defineProperty)return!1;var j=!1,ie=Object.defineProperty({},"passive",{get:function(){j=!0}});try{let ge=()=>{};s.addEventListener("test",ge,ie),s.removeEventListener("test",ge,ie)}catch{}return j})();function Wi(j,ie){if(Jt.call(this,j?j.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,j){var ge=this.type=j.type,Te=j.changedTouches&&j.changedTouches.length?j.changedTouches[0]:null;if(this.target=j.target||j.srcElement,this.g=ie,ie=j.relatedTarget){if($e){e:{try{Oe(ie.nodeName);var We=!0;break e}catch{}We=!1}We||(ie=null)}}else ge=="mouseover"?ie=j.fromElement:ge=="mouseout"&&(ie=j.toElement);this.relatedTarget=ie,Te?(this.clientX=Te.clientX!==void 0?Te.clientX:Te.pageX,this.clientY=Te.clientY!==void 0?Te.clientY:Te.pageY,this.screenX=Te.screenX||0,this.screenY=Te.screenY||0):(this.clientX=j.clientX!==void 0?j.clientX:j.pageX,this.clientY=j.clientY!==void 0?j.clientY:j.pageY,this.screenX=j.screenX||0,this.screenY=j.screenY||0),this.button=j.button,this.key=j.key||"",this.ctrlKey=j.ctrlKey,this.altKey=j.altKey,this.shiftKey=j.shiftKey,this.metaKey=j.metaKey,this.pointerId=j.pointerId||0,this.pointerType=typeof j.pointerType=="string"?j.pointerType:Em[j.pointerType]||"",this.state=j.state,this.i=j,j.defaultPrevented&&Wi.aa.h.call(this)}}N(Wi,Jt);var Em={2:"touch",3:"pen",4:"mouse"};Wi.prototype.h=function(){Wi.aa.h.call(this);var j=this.i;j.preventDefault?j.preventDefault():j.returnValue=!1};var To="closure_listenable_"+(1e6*Math.random()|0),Ra=0;function ya(j,ie,ge,Te,We){this.listener=j,this.proxy=null,this.src=ie,this.type=ge,this.capture=!!Te,this.ha=We,this.key=++Ra,this.da=this.fa=!1}function nl(j){j.da=!0,j.listener=null,j.proxy=null,j.src=null,j.ha=null}function fc(j){this.src=j,this.g={},this.h=0}fc.prototype.add=function(j,ie,ge,Te,We){var st=j.toString();j=this.g[st],j||(j=this.g[st]=[],this.h++);var Lt=Cd(j,ie,Te,We);return-1<Lt?(ie=j[Lt],ge||(ie.fa=!1)):(ie=new ya(ie,this.src,st,!!Te,We),ie.fa=ge,j.push(ie)),ie};function Of(j,ie){var ge=ie.type;if(ge in j.g){var Te=j.g[ge],We=Array.prototype.indexOf.call(Te,ie,void 0),st;(st=0<=We)&&Array.prototype.splice.call(Te,We,1),st&&(nl(ie),j.g[ge].length==0&&(delete j.g[ge],j.h--))}}function Cd(j,ie,ge,Te){for(var We=0;We<j.length;++We){var st=j[We];if(!st.da&&st.listener==ie&&st.capture==!!ge&&st.ha==Te)return We}return-1}var Dp="closure_lm_"+(1e6*Math.random()|0),vc={};function Af(j,ie,ge,Te,We){if(Te&&Te.once)return Cu(j,ie,ge,Te,We);if(Array.isArray(ie)){for(var st=0;st<ie.length;st++)Af(j,ie[st],ge,Te,We);return null}return ge=_d(ge),j&&j[To]?j.K(ie,ge,p(Te)?!!Te.capture:!!Te,We):Pf(j,ie,ge,!1,Te,We)}function Pf(j,ie,ge,Te,We,st){if(!ie)throw Error("Invalid event type");var Lt=p(We)?!!We.capture:!!We,ho=yu(j);if(ho||(j[Dp]=ho=new fc(j)),ge=ho.add(ie,ge,Te,Lt,st),ge.proxy)return ge;if(Te=wp(),ge.proxy=Te,Te.src=j,Te.listener=ge,j.addEventListener)Jn||(We=Lt),We===void 0&&(We=!1),j.addEventListener(ie.toString(),Te,We);else if(j.attachEvent)j.attachEvent(H1(ie.toString()),Te);else if(j.addListener&&j.removeListener)j.addListener(Te);else throw Error("addEventListener and attachEvent are unavailable.");return ge}function wp(){function j(ge){return ie.call(j.src,j.listener,ge)}let ie=a8;return j}function Cu(j,ie,ge,Te,We){if(Array.isArray(ie)){for(var st=0;st<ie.length;st++)Cu(j,ie[st],ge,Te,We);return null}return ge=_d(ge),j&&j[To]?j.L(ie,ge,p(Te)?!!Te.capture:!!Te,We):Pf(j,ie,ge,!0,Te,We)}function _u(j,ie,ge,Te,We){if(Array.isArray(ie))for(var st=0;st<ie.length;st++)_u(j,ie[st],ge,Te,We);else Te=p(Te)?!!Te.capture:!!Te,ge=_d(ge),j&&j[To]?(j=j.i,ie=String(ie).toString(),ie in j.g&&(st=j.g[ie],ge=Cd(st,ge,Te,We),-1<ge&&(nl(st[ge]),Array.prototype.splice.call(st,ge,1),st.length==0&&(delete j.g[ie],j.h--)))):j&&(j=yu(j))&&(ie=j.g[ie.toString()],j=-1,ie&&(j=Cd(ie,ge,Te,We)),(ge=-1<j?ie[j]:null)&&Mf(ge))}function Mf(j){if(typeof j!="number"&&j&&!j.da){var ie=j.src;if(ie&&ie[To])Of(ie.i,j);else{var ge=j.type,Te=j.proxy;ie.removeEventListener?ie.removeEventListener(ge,Te,j.capture):ie.detachEvent?ie.detachEvent(H1(ge),Te):ie.addListener&&ie.removeListener&&ie.removeListener(Te),(ge=yu(ie))?(Of(ge,j),ge.h==0&&(ge.src=null,ie[Dp]=null)):nl(j)}}}function H1(j){return j in vc?vc[j]:vc[j]="on"+j}function a8(j,ie){if(j.da)j=!0;else{ie=new Wi(ie,this);var ge=j.listener,Te=j.ha||j.src;j.fa&&Mf(j),j=ge.call(Te,ie)}return j}function yu(j){return j=j[Dp],j instanceof fc?j:null}var xm="__closure_events_fn_"+(1e9*Math.random()>>>0);function _d(j){return typeof j=="function"?j:(j[xm]||(j[xm]=function(ie){return j.handleEvent(ie)}),j[xm])}function Ko(){bi.call(this),this.i=new fc(this),this.M=this,this.F=null}N(Ko,bi),Ko.prototype[To]=!0,Ko.prototype.removeEventListener=function(j,ie,ge,Te){_u(this,j,ie,ge,Te)};function ea(j,ie){var ge,Te=j.F;if(Te)for(ge=[];Te;Te=Te.F)ge.push(Te);if(j=j.M,Te=ie.type||ie,typeof ie=="string")ie=new Jt(ie,j);else if(ie instanceof Jt)ie.target=ie.target||j;else{var We=ie;ie=new Jt(Te,j),Ce(ie,We)}if(We=!0,ge)for(var st=ge.length-1;0<=st;st--){var Lt=ie.g=ge[st];We=Su(Lt,Te,!0,ie)&&We}if(Lt=ie.g=j,We=Su(Lt,Te,!0,ie)&&We,We=Su(Lt,Te,!1,ie)&&We,ge)for(st=0;st<ge.length;st++)Lt=ie.g=ge[st],We=Su(Lt,Te,!1,ie)&&We}Ko.prototype.N=function(){if(Ko.aa.N.call(this),this.i){var j=this.i,ie;for(ie in j.g){for(var ge=j.g[ie],Te=0;Te<ge.length;Te++)nl(ge[Te]);delete j.g[ie],j.h--}}this.F=null},Ko.prototype.K=function(j,ie,ge,Te){return this.i.add(String(j),ie,!1,ge,Te)},Ko.prototype.L=function(j,ie,ge,Te){return this.i.add(String(j),ie,!0,ge,Te)};function Su(j,ie,ge,Te){if(ie=j.i.g[String(ie)],!ie)return!0;ie=ie.concat();for(var We=!0,st=0;st<ie.length;++st){var Lt=ie[st];if(Lt&&!Lt.da&&Lt.capture==ge){var ho=Lt.listener,ba=Lt.ha||Lt.src;Lt.fa&&Of(j.i,Lt),We=ho.call(ba,Te)!==!1&&We}}return We&&!Te.defaultPrevented}function z1(j,ie,ge){if(typeof j=="function")ge&&(j=I(j,ge));else if(j&&typeof j.handleEvent=="function")j=I(j.handleEvent,j);else throw Error("Invalid listener argument");return 2147483647<Number(ie)?-1:s.setTimeout(j,ie||0)}function kf(j){j.g=z1(()=>{j.g=null,j.i&&(j.i=!1,kf(j))},j.l);let ie=j.h;j.h=null,j.m.apply(null,ie)}class DA extends bi{constructor(ie,ge){super(),this.m=ie,this.l=ge,this.h=null,this.i=!1,this.g=null}j(ie){this.h=arguments,this.g?this.i=!0:kf(this)}N(){super.N(),this.g&&(s.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function yd(j){bi.call(this),this.h=j,this.g={}}N(yd,bi);var bu=[];function Ml(j){Be(j.g,function(ie,ge){this.g.hasOwnProperty(ge)&&Mf(ie)},j),j.g={}}yd.prototype.N=function(){yd.aa.N.call(this),Ml(this)},yd.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Sd=s.JSON.stringify,G1=s.JSON.parse,W1=class{stringify(j){return s.JSON.stringify(j,void 0)}parse(j){return s.JSON.parse(j,void 0)}};function q1(){}q1.prototype.h=null;function Iu(j){return j.h||(j.h=j.i())}function Eu(){}var xu={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Tm(){Jt.call(this,"d")}N(Tm,Jt);function Y1(){Jt.call(this,"c")}N(Y1,Jt);var Dm={},pr=null;function Cc(){return pr=pr||new Ko}Dm.La="serverreachability";function wA(j){Jt.call(this,Dm.La,j)}N(wA,Jt);function Op(j){let ie=Cc();ea(ie,new wA(ie))}Dm.STAT_EVENT="statevent";function Rf(j,ie){Jt.call(this,Dm.STAT_EVENT,j),this.stat=ie}N(Rf,Jt);function ta(j){let ie=Cc();ea(ie,new Rf(ie,j))}Dm.Ma="timingevent";function K1(j,ie){Jt.call(this,Dm.Ma,j),this.size=ie}N(K1,Jt);function Tu(j,ie){if(typeof j!="function")throw Error("Fn must not be null and must be a function");return s.setTimeout(function(){j()},ie)}function Na(){this.g=!0}Na.prototype.xa=function(){this.g=!1};function wm(j,ie,ge,Te,We,st){j.info(function(){if(j.g)if(st)for(var Lt="",ho=st.split("&"),ba=0;ba<ho.length;ba++){var Ri=ho[ba].split("=");if(1<Ri.length){var Fa=Ri[0];Ri=Ri[1];var La=Fa.split("_");Lt=2<=La.length&&La[1]=="type"?Lt+(Fa+"="+Ri+"&"):Lt+(Fa+"=redacted&")}}else Lt=null;else Lt=st;return"XMLHTTP REQ ("+Te+") [attempt "+We+"]: "+ie+`
|
|
181
|
+
`||e===" "||[",",":",";"].includes(e))}catch(e){return nt.catch("Error in utils isHotkeyDisabledForAutocomplete: ",e),!1}},_k=(i,o,n)=>{try{return!!i.substring(o+1,n).startsWith(" ")}catch(e){return nt.catch("Error in utils isHotkeyFollowedBySpace: ",e),!1}},wk=(i,o,n=["@"])=>{try{let e=f7e(i),t=null;try{e&&typeof e.getSelection=="function"&&(t=e.getSelection())}catch{}if(t||(t=window.getSelection()),t?.rangeCount){let r=t.getRangeAt(0),a=r.startOffset,s=r?.commonAncestorContainer?.textContent;if(s){let c=-1;for(let p of n){let g=s.lastIndexOf(p,a),f=g>0?s.lastIndexOf(p,g-1):-1;if(g>c){let I=Ck(s,g,a),T=_k(s,g,a);if(I||T){if(f!==-1){let N=Ck(s,f,g),G=_k(s,f,g);!N&&!G&&(c=f)}}else c=g}}if(c!==-1){let p=s.substring(0,c),g=s.substring(r.endOffset),f=document.createElement("span");f.textContent=o,f.style.color="var(--velt-accent)";let I=Date.now()+"_"+Math.random().toString(36).substr(2,9);f.setAttribute("data-recently-added",I),setTimeout(()=>{f.hasAttribute("data-recently-added")&&f.removeAttribute("data-recently-added")},5e3);let T=r.commonAncestorContainer;if(T.nodeType===Node.TEXT_NODE){let N=T.parentNode;if(N){let G=document.createTextNode(p),z=document.createTextNode(g);N.replaceChild(z,T),N.insertBefore(f,z),N.insertBefore(G,f);try{let J=document.createRange();J.setStartAfter(f),J.collapse(!0),t?.removeAllRanges(),t?.addRange(J)}catch(J){nt.catch("Error positioning cursor after span:",J);try{let ce=document.createRange();ce.selectNodeContents(i),ce.collapse(!1),t?.removeAllRanges(),t?.addRange(ce)}catch(ce){nt.catch("Error with fallback cursor positioning:",ce)}}}}}}}}catch(e){nt.catch("Error in utils replaceWordAtCursor: ",e)}},Ok=()=>{try{let o=window.getSelection()?.getRangeAt(0),n=o?.commonAncestorContainer,e=o?.startContainer,t=o?.endContainer,r=[];r.push(n),r.push(e),r.push(t);let a=!1;for(let s of r)if(s&&Gi(s,[U.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,U.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,U.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,U.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(i){return nt.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",i),!1}},Ble=(i,o,n)=>{try{let e=document.querySelector(`[id=${i}]`);if(e)e.name=o,e.content=n;else{let t=document.createElement("meta");t.id=i,t.name=o,t.content=n,document.getElementsByTagName("head")[0].appendChild(t)}}catch{}},Vle=i=>{try{if(i){let o=document.querySelector(`[id=${i}]`);o&&o.remove()}}catch{}},Ule=()=>{try{let o=new Date().getTimezoneOffset(),n=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${n?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(i){return nt.catch("Error in utils getTimezone: ",i),""}},jle=()=>{try{let i=[];return document.querySelectorAll("*").forEach(n=>{(n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth||["auto","scroll"].includes(getComputedStyle(n).overflow))&&i.push(n)}),i}catch(i){return nt.catch("Error in utils getScrollableElements: ",i),[]}},$le=(i,o)=>Math.sqrt((i.x-o.x)**2+(i.y-o.y)**2),YH=(i,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let n=i;for(;n.children.length>0;){let e=null,t=Number.MAX_SAFE_INTEGER;for(let r=0;r<n.children.length;r++){let a=n.children[r],s=a.getBoundingClientRect(),c={x:s.left+s.width/2,y:s.top+s.height/2},p=$le(c,o);(s.top>=0||s.bottom<=window.innerHeight)&&s.width>0&&s.height>0&&p<=t&&(e=a,t=p)}if(e===null)break;n=e}return n}catch(n){return nt.catch("Error in utils getInnermostElement: ",n),null}},Hle=i=>{try{let{offsetWidth:o,offsetHeight:n,scrollTop:e}=i,t=i,r={x:o/2,y:e+n/2};for(;t.children.length>0;){let a=null,s=Number.MAX_SAFE_INTEGER;for(let c=0;c<t.children.length;c++){let p=t.children[c],g={x:p.offsetLeft+p.offsetWidth/2,y:p.offsetTop+p.offsetHeight/2},f=$le(g,r);p.offsetTop>=0&&p.offsetWidth>0&&p.offsetHeight>0&&f<=s&&(a=p,s=f)}if(a===null)break;t=a}return t}catch(o){return nt.catch("Error in utils getNestedInnermostElement: ",o),null}},zle=()=>{try{let i=window.innerWidth/2,o=window.innerHeight/2,n=document.elementFromPoint(i,o);for(;n&&n.tagName==="BODY";)o+=2,n=document.elementFromPoint(i,o);return n}catch(i){return nt.catch("Error in utils getCenteredBackgroundElement: ",i),null}},KH=(i,o,n=!1)=>{try{let e=i.getBoundingClientRect(),t=o.getBoundingClientRect(),r=o.offsetTop;n&&(r=r-e.height/2+t.height/2),i.scrollTo({top:r,behavior:"smooth"})}catch(e){nt.catch("Error in utils nestedScrollIntoView: ",e)}},Ak=(i,o=!0)=>{try{let n=document.body.getBoundingClientRect(),e=i.getBoundingClientRect(),t=e.top-n.top,r=window.innerHeight,a=t;o&&(a=a-r/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(n){nt.catch("Error in utils scrollIntoView: ",n)}},Gle=(i=!1)=>{try{let o=!0;return i&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return nt.catch("Error in utils isTouchDevice: ",o),!1}},Wle=(i,o,n)=>{try{return(1-n)*i+n*o}catch(e){nt.catch("Error in utils lerp: ",e)}return 0},qle=(i,o)=>{try{if(i===void 0)return i;if(i=i.replace("#",""),i.length===6){let n=parseInt(i,16),e=(n>>16)+o;e>255&&(e=255),e<0&&(e=0);let t=(n&255)+o;t>255&&(t=255),t<0&&(t=0);let r=(n>>8&255)+o;return r>255&&(r=255),r<0&&(r=0),`#${(t|r<<8|e<<16).toString(16)}`}else return i}catch(n){nt.catch("Error in utils multiplyColor: ",n)}return i},Yle=i=>{try{return i in U.TEXT_COLOR_MAP?U.TEXT_COLOR_MAP[i]:"#141416"}catch(o){return nt.catch("Error in generateUserColor:",o),"#141416"}},od=()=>{try{let i=localStorage.getItem(U.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(i)return JSON.parse(i)}catch(i){return nt.catch("Error in getDefaultMediaStreamOptions:",i),{}}},Pk=(i,o)=>{try{let n=o*(Math.PI/180),e=Math.cos(n);return e?i/e:i}catch(n){return nt.catch("Error in calculateHypotenuse:",n),0}},ZH=(i,o,n=!0)=>{try{let e=[],t=n?i:i.parentNode;for(;t;)e.push(t),t=t.parentNode;let r=n?o:o.parentNode;for(;r;){if(e.indexOf(r)!==-1)return r;r=r.parentNode}return null}catch(e){return nt.catch("Error in utils findCommonParent: ",e),null}},XH=(i,o,n,e)=>{let t=n.getBoundingClientRect(),r=e.getBoundingClientRect(),a=t.left+i,s=t.top+o,c=a-r.left,p=s-r.top;return{x:c,y:p}},Mg=i=>{try{let o={height:0,width:0};if(typeof i?.getBBox=="function"){let n=i?.getBBox(),e=i?.getBoundingClientRect();o.height=parseFloat(e?.height||n.height||0),o.width=parseFloat(e?.width||n.width||0)}else{let n=window.getComputedStyle(i);if(o.height=i?.clientHeight||parseFloat(n.getPropertyValue("height"))||0,o.width=i?.clientWidth||parseFloat(n.getPropertyValue("width"))||0,i?.getBoundingClientRect&&typeof i?.getBoundingClientRect=="function"){let e=i?.getBoundingClientRect();o?.height||(o.height=e?.height||i?.clientHeight||i?.offsetHeight||0),o?.width||(o.width=e?.width||i?.clientWidth||i?.offsetWidth||0)}}return o}catch(o){return nt.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},im=i=>{try{let o=i;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return nt.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},f7e=i=>{try{let o=i;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){nt.catch("Error in utils findShadowRoot: ",o)}return null};var W0=i=>i===null||typeof i>"u",q0=(i,o)=>{try{return!!i?.closest(`[${o}]`)}catch(n){return nt.catch("Error in utils hasParentWithAttribute: ",n),!1}},QH=(i,o=!0)=>{try{let n=[];if(!i||!(i instanceof HTMLElement))return[];o&&n.push(i);for(let e=0;e<i.children.length;e++){let t=i.children[e];n=n.concat(QH(t))}return n}catch(n){return nt.catch("Error in utils getAllNestedChildren: ",n),[]}},Kle=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(i){return nt.catch("Error in utils isTabActive: ",i),!1}},JH=i=>{try{let o="",n=i?.getAttribute("src");if(n)o=`${Rn(n)}`;else{let e=i?.querySelectorAll("source");if(e&&e.length>0){let r=e[0]?.getAttribute("src");r&&(o=`${Rn(r)}`)}}return o}catch{return""}},qe=i=>{try{return!(i&&(i?.children?.length>0||i?.textContent?.trim()?.length>0))}catch(o){return nt.catch("Error in utils isTemplateEmpty: ",o),!0}},Aa=(i,o)=>{try{if(!i||!o)return;let n=[],e="",t=0;for(let c=0;c<o.length;c++){let p=o[c];p==="["?(t++,t===1&&e&&(n.push(e),e=""),e+=p):p==="]"?(t--,e+=p,t===0&&(n.push(e),e="")):p==="."&&t===0?e&&(n.push(e),e=""):e+=p}e&&n.push(e);let r,a=E({},i),s=n.reduce((c,p)=>{if(c==null)return;Ni(c)&&(r=c,c=c());let g=p.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(g){let I=g[1];if(/^\d+$/.test(I)){let T=parseInt(I,10);return Array.isArray(c)?c[T]:void 0}if(I.startsWith("'")&&I.endsWith("'")||I.startsWith('"')&&I.endsWith('"')){let T=I.slice(1,-1);return c[T]}if(I.includes(".")||I.includes("[")){let T=Aa(a,I);Ni(T)&&(T=T());let N=T?.toString()||"";return c[N]}if(a[I]!==void 0){let T=a[I];return Ni(T)&&(T=T()),c[T]}return c[I]}let f=p;return(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))&&(f=p.slice(1,-1)),f==="length"&&Array.isArray(c)?c.length:c[f]},i);return r?Oi(()=>{try{let c=E({},i);return n.reduce((p,g)=>{if(p==null)return;Ni(p)&&(p=p());let f=g.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(f){let T=f[1];if(/^\d+$/.test(T)){let N=parseInt(T,10);return Array.isArray(p)?p[N]:void 0}if(T.startsWith("'")&&T.endsWith("'")||T.startsWith('"')&&T.endsWith('"')){let N=T.slice(1,-1);return p[N]}if(T.includes(".")||T.includes("[")){let N=Aa(c,T);Ni(N)&&(N=N());let G=N?.toString()||"";return p[G]}if(c[T]!==void 0){let N=c[T];return Ni(N)&&(N=N()),p[N]}return p[T]}let I=g;return(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(I=g.slice(1,-1)),p[I]},i)}catch{return""}}):s}catch{return""}},Jh=(i,o)=>{try{return!!(i?.locationId&&(i.locationId===o?.locationId||o?.location?.id===String(i.locationId))||i?.location?.id&&(i.location.id===o?.location?.id||i.location.id===String(o?.locationId)))}catch(n){return nt.catch("Error in utils isLocationSame: ",n),!1}},Zle=()=>{try{let i=document.activeElement,o=new Set,n=10,e=0;for(;i&&i.shadowRoot&&!(o.has(i)||(o.add(i),i=i.shadowRoot.activeElement,e++,e>n)););return i}catch(i){return nt.catch("Error in utils getActiveElement: ",i),null}},Kt=(i,o)=>{try{return typeof i=="object"&&typeof o=="object"?JSON.stringify(i)===JSON.stringify(o):i===o}catch{return!1}},Y0=i=>{try{let o=JSON.parse(JSON.stringify(i));return i?.clientDocumentId&&(o.documentId=i.clientDocumentId),i?.clientOrganizationId&&(o.organizationId=i.clientOrganizationId),delete o?.clientDocumentId,delete o?.clientOrganizationId,delete o?.veltFolderId,delete o?.parentVeltFolderId,delete o?.pageInfo,o}catch{return i}},Xr=i=>{try{if(!i.some(a=>a?.value?.data))return{};let o=null,n=i.reduce((a,s)=>Math.max(a,s.timestamp),0),e=i.find(a=>a.timestamp===n);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let r=i.map(a=>a.value).reduce((a,s)=>({data:E(E({},a?.data??{}),s?.data??{})}),{});return r.operation=o,r}catch{return{}}},rd=(i,o,n)=>Q(null,null,function*(){try{let e=0;for(;e<=(n.retryCount||0);)try{let t=yield i();if(!t)return{success:!1,statusCode:400,message:`${o} failed: No response received`};if(t.statusCode===void 0)return{success:!1,statusCode:400,message:`${o} failed: Response missing statusCode`};if(t.statusCode!==200){if(e++,e>(n.retryCount||0))return{success:!1,statusCode:t.statusCode,message:`${o} failed after ${e} attempts with status code ${t.statusCode}`};n.retryDelay&&(yield new Promise(r=>setTimeout(r,n.retryDelay)));continue}return t}catch(t){if(e++,e>(n.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${t instanceof Error?t.message:"Unknown error"}`};n.retryDelay&&(yield new Promise(r=>setTimeout(r,n.retryDelay)))}return{success:!1,statusCode:500,message:`${o} failed: Maximum retry attempts exceeded`}}catch(e){return{success:!1,statusCode:500,message:`${o} failed with unexpected error: ${e instanceof Error?e.message:"Unknown error"}`}}}),Xle=i=>{try{return!i||!i?.access?[]:Object.keys(i.access).sort().map(t=>i.access?.[t]?.map(r=>`${t}:${r}`)??[]).reduce((t,r)=>t.flatMap(a=>r.map(s=>[...a,s])),[[]]).map(t=>t.join("_"))}catch(o){return nt.catch("Error in utils generateProcessedContext: ",o),[]}},Qle=i=>{try{if(!i||!i?.access)return[];let o=Object.keys(i.access).sort(),e=(r=>{let a=[],s=Math.pow(2,r.length);for(let c=1;c<s;c++){let p=[];for(let g=0;g<r.length;g++)c&1<<g&&p.push(r[g]);a.push(p)}return a})(o),t=[];for(let r of e){let a=r.map(s=>{let c=i.access?.[s];return c==null?null:`${s}:${c}`}).filter(s=>s!==null);a.length>0&&t.push(a.join("_"))}return[...new Set(t)]}catch(o){return nt.catch("Error in utils generateAllContextCombos: ",o),[]}},Jle=({input:i})=>{try{if(!i||!i?.access)return[];let o=i?.access,n=Object.keys(o).sort(),e=[];for(let r of n){let a=o[r];a!=null&&Array.isArray(a)&&a.length>0&&e.push({key:r,values:a})}return e.length===0?[]:e.reduce((r,{key:a,values:s})=>r.length===0?s.map(c=>[{key:a,value:c}]):r.flatMap(c=>s.map(p=>[...c,{key:a,value:p}])),[]).map(r=>{let a={};return r.forEach(({key:s,value:c})=>{a[s]=c}),{access:a}})}catch(o){return nt.catch("Error in utils expandContextArraysToSingleValues: ",o),[]}},ece=({input:i})=>{try{if(!i||i.length===0)return{access:{}};let o=new Set;i.forEach(e=>{e?.access&&Object.keys(e.access).forEach(t=>o.add(t))});let n={};for(let e of Array.from(o).sort()){let t=new Set;i.forEach(r=>{if(r?.access){let a=r.access[e];a!=null&&t.add(a)}}),n[e]=t.size>0?Array.from(t).sort():null}return{access:n}}catch(o){return nt.catch("Error in utils combineContextsToArrays: ",o),{access:{}}}},ad=t=>Q(null,[t],function*({data:i,getSdkProxy:o,userId:n,methodName:e}){try{let r="sdkproxyencryptionanddecryptiononsdk"+(n??""),a=yield v7e({data:i,key:r}),s=(yield o({veltData:a}))?.data?.data?.veltData||{};return yield j0(s,r)}catch(r){return nt.catch("Error in utils sdkProxyEncryptDecrypt: "+(e??""),r),i}}),v7e=n=>Q(null,[n],function*({data:i,key:o}){try{return yield bl(i,o)}catch{return i}}),ez=(i,o)=>Q(null,null,function*(){try{let n=0;for(;n<=(o.retryCount||0);)try{let e=yield i();if(!e)throw new Error("No response received");return e}catch{if(n++,n>=(o.retryCount||0))return null;o.retryDelay&&(yield new Promise(t=>setTimeout(t,o.retryDelay)))}return null}catch{return null}}),Qr=i=>{try{if(i&&typeof i=="object"){let o=JSON.parse(JSON.stringify(i));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,o}else return null}catch(o){return nt.catch("Error in utils getUserForClient: ",o),null}},Zi=({url:i,apiProxyDomain:o})=>{try{if(o){let n=new URL(i);n.origin&&(i=i.replace(n.origin,o))}return i}catch(n){return nt.catch("Error in utils getResolvedApiUrl: ",n),i}},tce=(i,o)=>{try{if(!i||!(i instanceof Element))return!1;let n,e;if(o&&typeof o.x=="number"&&typeof o.y=="number")n=o.x,e=o.y;else{let r=i.getBoundingClientRect();n=r.left+r.width/2,e=r.top+r.height/2}let t=document.elementFromPoint(n,e);return!(!t||t===i||i.contains(t))}catch{return!1}};var et=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.liveStateSyncEvents=Object.values(K.Events.LiveStateSync||{})?.filter(t=>![K.Events.LiveStateSync.ON_ACTION_TRIGGERED].includes(t)),this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3;try{this.updateDefaultProperties({sdkVersion:ga()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(t){nt.catch("Error in AnalyticsService constructor: ",t)}}updateDefaultProperties(e={}){this.defaultProperties=E(E({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(t){nt.catch("Error in AnalyticsService setInstalledFeature: ",t)}}setFeatureConfig({feature:e,config:t}){try{this.defaultProperties.featureConfigs||(this.defaultProperties.featureConfigs={}),this.defaultProperties.featureConfigs[e]||(this.defaultProperties.featureConfigs[e]={}),this.defaultProperties.featureConfigs[e]=E(E({},this.defaultProperties.featureConfigs[e]),t)}catch(r){nt.catch("Error in AnalyticsService setFeatureConfig: ",r)}}setSF(e){try{this.sf=e}catch(t){nt.catch("Error in AnalyticsService setSF: ",t)}}setAuthService(e){try{this.authService=e}catch(t){nt.catch("Error in AnalyticsService setAuthService: ",t)}}setCommentService(e){try{this.commentService=e}catch(t){nt.catch("Error in AnalyticsService setCommentService: ",t)}}setConfigService(e){try{this.configService=e}catch(t){nt.catch("Error in AnalyticsService setConfigService: ",t)}}setDomService(e){try{this.domService=e}catch(t){nt.catch("Error in AnalyticsService setDomService: ",t)}}setLiveStateService(e){try{this.liveStateService=e}catch(t){nt.catch("Error in AnalyticsService setLiveStateService: ",t)}}setAreaService(e){try{this.areaService=e}catch(t){nt.catch("Error in AnalyticsService setAreaService: ",t)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(t){nt.catch("Error in AnalyticsService setRecorderAnnotationService: ",t)}}setReactionService(e){try{this.reactionService=e}catch(t){nt.catch("Error in AnalyticsService setReactionService: ",t)}}setUserService(e){try{this.userService=e}catch(t){nt.catch("Error in AnalyticsService setUserService: ",t)}}identifyUser(e,t,r={}){try{this.userId=e;let a=typeof t=="object"?JSON.parse(JSON.stringify(t)):t;this.userService?.userDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let s=this.defaultProperties?this.defaultProperties.apiKey:null;if(Dn.production||Dn.staging){let c=Date.now(),p={userId:e,clientUserId:this.user?.userId,traits:D(E({},a),{apiKey:s,forceReset:r?.forceReset,eventTimestamp:c}),properties:D(E({},this.defaultProperties),{eventTimestamp:c}),sf:this.sf,context:this.getContext(),eventTimestamp:c};this.setAnalytics("identify",p)}if(this.userId&&this.draftEvents?.length){let c=this.draftEvents?.slice();this.draftEvents=[],c?.forEach(p=>{switch(p.type){case"track":p?.data?.eventName&&this.trackEvent(p.data.eventName,p.data.properties,p.data.mergeDefaultProperties,p.data.userId,p.data.clientUserId);break;default:break}})}}catch(a){nt.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,t="",r={}){try{if((Dn.production||Dn.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:r,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){nt.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(c){return Q(this,arguments,function*(e,t={},r=!0,a,s){try{if(this.sf&&Ele.includes(e))return;if(Dn.production||Dn.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return;let p=Date.now();if(this.eventRateLimitCache[e]&&p-this.eventRateLimitCache[e].timestamp<this.TIME_WINDOW_MS){if(this.eventRateLimitCache[e].count>=this.EVENT_LIMIT){if(!this.eventRateLimitCache[e].rateLimitExceededEventTriggered){this.eventRateLimitCache[e].rateLimitExceededEventTriggered=!0,this.eventRateLimitCache[e].blockedForSession=!0;let g=E({eventName:e},t||{});this.triggerTrackEvent(K.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,g,r,a,s)}return}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:p,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,t,r,a,s)}else t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.draftEvents.push({type:"track",data:{eventName:e,properties:t,mergeDefaultProperties:r,userId:a,clientUserId:s}})}catch(p){nt.catch("Error in AnalyticsService trackEvent: ",p)}})}triggerTrackEvent(c){return Q(this,arguments,function*(e,t={},r=!0,a,s){try{r&&(t||(t={}),t=E(E({},t),this.defaultProperties));let p;if(t?.annotationId){let f=t.annotationId;if(!p&&this.commentService){let I=this.commentService.getAnnotationById(f);I?.metadata&&(p=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId);let T=this.commentService.getMultiThreadAnnotationById(f);T?.metadata&&(p=T.metadata),T?.targetElementId&&(t.targetElementId=T.targetElementId)}if(!p&&this.recorderAnnotationService){let I=this.recorderAnnotationService.getAnnotationById(f);I?.metadata&&(p=I.metadata)}if(!p&&this.reactionService){let I=this.reactionService.getAnnotationById(f);I?.metadata&&(p=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId)}if(!p&&this.areaService){let I=this.areaService.getAnnotationById(f);I?.metadata&&(p=I.metadata)}}if(p&&typeof p=="object"&&(t=E(E({},t),p)),t&&typeof t=="object"&&(t=D(E({},t),{userId:this.userId||a,clientUserId:this.user?.userId||s}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),t?.sessionTabId||(t.sessionTabId=this.domService?.getTabId()),this.liveStateSyncEvents.includes(e))){let f=this.liveStateService?.getSemStats();f&&!t?.semStats&&(t.semStats=f)}let g={userId:this.userId||a,clientUserId:this.user?.userId||s,event:e,properties:t,sf:this.sf,context:this.getContext(),eventTimestamp:t?.eventTimestamp};return this.setAnalytics("track",g)}catch(p){nt.catch("Error in AnalyticsService triggerTrackEvent: ",p)}})}setAnalytics(e,t){return Q(this,null,function*(){try{return navigator.onLine?Ki(this.functions,Zi({url:Dn.cloudFunction.sa,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({type:e,data:t}).catch(a=>{nt.warn("Error in AnalyticsService setAnalytics promise: ",e,a)}):void 0}catch(r){nt.catch("Error in AnalyticsService setAnalytics: ",r)}})}trackAuthenticatedEvent(e,t={},r=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,t,r):((!t||typeof t!="object")&&(t={}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.authService?.getUser$()?.pipe(Fe(a=>!!a),ot(1))?.subscribe(()=>{this.trackEvent(e,t,r)})))}catch(a){nt.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},t=Mi();return e.os={name:t?.deviceInfo?.osName,version:t?.deviceInfo?.osVersion},e.page={path:t?.path,title:t?.title,url:t?.url},e.screen={height:t?.deviceInfo?.screenHeight,width:t?.deviceInfo?.screenWidth},e.app={name:t?.deviceInfo?.browserName,version:t?.deviceInfo?.browserVersion},e.device={type:t?.deviceInfo?.deviceType},e.timezone=Ule(),e.userAgent=t?.deviceInfo?.userAgent,e}catch(e){nt.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(t){return new(t||o)(ee(Io))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var y=(()=>{let o=class o{get debugMode(){return Dle()}get debugAuthMode(){try{return!!sessionStorage.getItem("debugAuthMode")}catch{return!1}}get debugPerfMode(){return wle()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new ve(!0),this.log("%c[WB] Creating SERVICE LoggingService","color: blue;")}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.catch("Error in LoggingService enableLogs: ",e)}}disableLogs(){try{if(this.logsEnabled$.value===!1)return;this.logsEnabled$.next(!1)}catch(e){this.catch("Error in LoggingService disableLogs: ",e)}}debugAuth(e,...t){try{this.debugAuthMode&&console.log(e,...t)}catch(r){this.catch("Error in LoggingService debugAuth: ",r)}}log(e,...t){this.debugMode&&console.log(e,...t)}logPerf(e,...t){this.debugPerfMode&&console.log(e,...t)}warn(e,...t){this.debugMode&&console.warn(e,...t)}error(e,...t){this.debugMode&&console.error(e,...t)}debug(e,...t){this.debugMode&&console.debug(e,...t)}info(e,...t){this.debugMode&&console.info(e,...t)}catch(e,t,r,a=!1){try{let s=t?.message;this.logsEnabled$.value&&(s?.toLowerCase()?.includes("permission denied")||s?.toLowerCase()?.includes("permission_denied")||(t!==void 0?console.warn("Velt: ",e,t):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(K.Events.Core.SDK_ERROR,E({sourceMethod:e,message:(t?.message?t?.message:t)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},r||{}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var nce=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ice={};var gp,tz;(function(){var i;function o(be,Se){function Ae(){}Ae.prototype=Se.prototype,be.D=Se.prototype,be.prototype=new Ae,be.prototype.constructor=be,be.C=function(Ce,fe,we){for(var Ne=Array(arguments.length-2),to=2;to<arguments.length;to++)Ne[to-2]=arguments[to];return Se.prototype[fe].apply(Ce,Ne)}}function n(){this.blockSize=-1}function e(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}o(e,n),e.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function t(be,Se,Ae){Ae||(Ae=0);var Ce=Array(16);if(typeof Se=="string")for(var fe=0;16>fe;++fe)Ce[fe]=Se.charCodeAt(Ae++)|Se.charCodeAt(Ae++)<<8|Se.charCodeAt(Ae++)<<16|Se.charCodeAt(Ae++)<<24;else for(fe=0;16>fe;++fe)Ce[fe]=Se[Ae++]|Se[Ae++]<<8|Se[Ae++]<<16|Se[Ae++]<<24;Se=be.g[0],Ae=be.g[1],fe=be.g[2];var we=be.g[3],Ne=Se+(we^Ae&(fe^we))+Ce[0]+3614090360&4294967295;Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[1]+3905402710&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[2]+606105819&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[3]+3250441966&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[4]+4118548399&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[5]+1200080426&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[6]+2821735955&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[7]+4249261313&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[8]+1770035416&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[9]+2336552879&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[10]+4294925233&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[11]+2304563134&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(we^Ae&(fe^we))+Ce[12]+1804603682&4294967295,Se=Ae+(Ne<<7&4294967295|Ne>>>25),Ne=we+(fe^Se&(Ae^fe))+Ce[13]+4254626195&4294967295,we=Se+(Ne<<12&4294967295|Ne>>>20),Ne=fe+(Ae^we&(Se^Ae))+Ce[14]+2792965006&4294967295,fe=we+(Ne<<17&4294967295|Ne>>>15),Ne=Ae+(Se^fe&(we^Se))+Ce[15]+1236535329&4294967295,Ae=fe+(Ne<<22&4294967295|Ne>>>10),Ne=Se+(fe^we&(Ae^fe))+Ce[1]+4129170786&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[6]+3225465664&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[11]+643717713&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[0]+3921069994&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[5]+3593408605&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[10]+38016083&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[15]+3634488961&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[4]+3889429448&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[9]+568446438&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[14]+3275163606&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[3]+4107603335&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[8]+1163531501&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(fe^we&(Ae^fe))+Ce[13]+2850285829&4294967295,Se=Ae+(Ne<<5&4294967295|Ne>>>27),Ne=we+(Ae^fe&(Se^Ae))+Ce[2]+4243563512&4294967295,we=Se+(Ne<<9&4294967295|Ne>>>23),Ne=fe+(Se^Ae&(we^Se))+Ce[7]+1735328473&4294967295,fe=we+(Ne<<14&4294967295|Ne>>>18),Ne=Ae+(we^Se&(fe^we))+Ce[12]+2368359562&4294967295,Ae=fe+(Ne<<20&4294967295|Ne>>>12),Ne=Se+(Ae^fe^we)+Ce[5]+4294588738&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[8]+2272392833&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[11]+1839030562&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[14]+4259657740&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[1]+2763975236&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[4]+1272893353&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[7]+4139469664&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[10]+3200236656&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[13]+681279174&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[0]+3936430074&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[3]+3572445317&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[6]+76029189&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(Ae^fe^we)+Ce[9]+3654602809&4294967295,Se=Ae+(Ne<<4&4294967295|Ne>>>28),Ne=we+(Se^Ae^fe)+Ce[12]+3873151461&4294967295,we=Se+(Ne<<11&4294967295|Ne>>>21),Ne=fe+(we^Se^Ae)+Ce[15]+530742520&4294967295,fe=we+(Ne<<16&4294967295|Ne>>>16),Ne=Ae+(fe^we^Se)+Ce[2]+3299628645&4294967295,Ae=fe+(Ne<<23&4294967295|Ne>>>9),Ne=Se+(fe^(Ae|~we))+Ce[0]+4096336452&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[7]+1126891415&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[14]+2878612391&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[5]+4237533241&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[12]+1700485571&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[3]+2399980690&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[10]+4293915773&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[1]+2240044497&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[8]+1873313359&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[15]+4264355552&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[6]+2734768916&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[13]+1309151649&4294967295,Ae=fe+(Ne<<21&4294967295|Ne>>>11),Ne=Se+(fe^(Ae|~we))+Ce[4]+4149444226&4294967295,Se=Ae+(Ne<<6&4294967295|Ne>>>26),Ne=we+(Ae^(Se|~fe))+Ce[11]+3174756917&4294967295,we=Se+(Ne<<10&4294967295|Ne>>>22),Ne=fe+(Se^(we|~Ae))+Ce[2]+718787259&4294967295,fe=we+(Ne<<15&4294967295|Ne>>>17),Ne=Ae+(we^(fe|~Se))+Ce[9]+3951481745&4294967295,be.g[0]=be.g[0]+Se&4294967295,be.g[1]=be.g[1]+(fe+(Ne<<21&4294967295|Ne>>>11))&4294967295,be.g[2]=be.g[2]+fe&4294967295,be.g[3]=be.g[3]+we&4294967295}e.prototype.u=function(be,Se){Se===void 0&&(Se=be.length);for(var Ae=Se-this.blockSize,Ce=this.B,fe=this.h,we=0;we<Se;){if(fe==0)for(;we<=Ae;)t(this,be,we),we+=this.blockSize;if(typeof be=="string"){for(;we<Se;)if(Ce[fe++]=be.charCodeAt(we++),fe==this.blockSize){t(this,Ce),fe=0;break}}else for(;we<Se;)if(Ce[fe++]=be[we++],fe==this.blockSize){t(this,Ce),fe=0;break}}this.h=fe,this.o+=Se},e.prototype.v=function(){var be=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);be[0]=128;for(var Se=1;Se<be.length-8;++Se)be[Se]=0;var Ae=8*this.o;for(Se=be.length-8;Se<be.length;++Se)be[Se]=Ae&255,Ae/=256;for(this.u(be),be=Array(16),Se=Ae=0;4>Se;++Se)for(var Ce=0;32>Ce;Ce+=8)be[Ae++]=this.g[Se]>>>Ce&255;return be};function r(be,Se){var Ae=s;return Object.prototype.hasOwnProperty.call(Ae,be)?Ae[be]:Ae[be]=Se(be)}function a(be,Se){this.h=Se;for(var Ae=[],Ce=!0,fe=be.length-1;0<=fe;fe--){var we=be[fe]|0;Ce&&we==Se||(Ae[fe]=we,Ce=!1)}this.g=Ae}var s={};function c(be){return-128<=be&&128>be?r(be,function(Se){return new a([Se|0],0>Se?-1:0)}):new a([be|0],0>be?-1:0)}function p(be){if(isNaN(be)||!isFinite(be))return f;if(0>be)return z(p(-be));for(var Se=[],Ae=1,Ce=0;be>=Ae;Ce++)Se[Ce]=be/Ae|0,Ae*=4294967296;return new a(Se,0)}function g(be,Se){if(be.length==0)throw Error("number format error: empty string");if(Se=Se||10,2>Se||36<Se)throw Error("radix out of range: "+Se);if(be.charAt(0)=="-")return z(g(be.substring(1),Se));if(0<=be.indexOf("-"))throw Error('number format error: interior "-" character');for(var Ae=p(Math.pow(Se,8)),Ce=f,fe=0;fe<be.length;fe+=8){var we=Math.min(8,be.length-fe),Ne=parseInt(be.substring(fe,fe+we),Se);8>we?(we=p(Math.pow(Se,we)),Ce=Ce.j(we).add(p(Ne))):(Ce=Ce.j(Ae),Ce=Ce.add(p(Ne)))}return Ce}var f=c(0),I=c(1),T=c(16777216);i=a.prototype,i.m=function(){if(G(this))return-z(this).m();for(var be=0,Se=1,Ae=0;Ae<this.g.length;Ae++){var Ce=this.i(Ae);be+=(0<=Ce?Ce:4294967296+Ce)*Se,Se*=4294967296}return be},i.toString=function(be){if(be=be||10,2>be||36<be)throw Error("radix out of range: "+be);if(N(this))return"0";if(G(this))return"-"+z(this).toString(be);for(var Se=p(Math.pow(be,6)),Ae=this,Ce="";;){var fe=Oe(Ae,Se).g;Ae=J(Ae,fe.j(Se));var we=((0<Ae.g.length?Ae.g[0]:Ae.h)>>>0).toString(be);if(Ae=fe,N(Ae))return we+Ce;for(;6>we.length;)we="0"+we;Ce=we+Ce}},i.i=function(be){return 0>be?0:be<this.g.length?this.g[be]:this.h};function N(be){if(be.h!=0)return!1;for(var Se=0;Se<be.g.length;Se++)if(be.g[Se]!=0)return!1;return!0}function G(be){return be.h==-1}i.l=function(be){return be=J(this,be),G(be)?-1:N(be)?0:1};function z(be){for(var Se=be.g.length,Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=~be.g[Ce];return new a(Ae,~be.h).add(I)}i.abs=function(){return G(this)?z(this):this},i.add=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0,fe=0;fe<=Se;fe++){var we=Ce+(this.i(fe)&65535)+(be.i(fe)&65535),Ne=(we>>>16)+(this.i(fe)>>>16)+(be.i(fe)>>>16);Ce=Ne>>>16,we&=65535,Ne&=65535,Ae[fe]=Ne<<16|we}return new a(Ae,Ae[Ae.length-1]&-2147483648?-1:0)};function J(be,Se){return be.add(z(Se))}i.j=function(be){if(N(this)||N(be))return f;if(G(this))return G(be)?z(this).j(z(be)):z(z(this).j(be));if(G(be))return z(this.j(z(be)));if(0>this.l(T)&&0>be.l(T))return p(this.m()*be.m());for(var Se=this.g.length+be.g.length,Ae=[],Ce=0;Ce<2*Se;Ce++)Ae[Ce]=0;for(Ce=0;Ce<this.g.length;Ce++)for(var fe=0;fe<be.g.length;fe++){var we=this.i(Ce)>>>16,Ne=this.i(Ce)&65535,to=be.i(fe)>>>16,St=be.i(fe)&65535;Ae[2*Ce+2*fe]+=Ne*St,ce(Ae,2*Ce+2*fe),Ae[2*Ce+2*fe+1]+=we*St,ce(Ae,2*Ce+2*fe+1),Ae[2*Ce+2*fe+1]+=Ne*to,ce(Ae,2*Ce+2*fe+1),Ae[2*Ce+2*fe+2]+=we*to,ce(Ae,2*Ce+2*fe+2)}for(Ce=0;Ce<Se;Ce++)Ae[Ce]=Ae[2*Ce+1]<<16|Ae[2*Ce];for(Ce=Se;Ce<2*Se;Ce++)Ae[Ce]=0;return new a(Ae,0)};function ce(be,Se){for(;(be[Se]&65535)!=be[Se];)be[Se+1]+=be[Se]>>>16,be[Se]&=65535,Se++}function ye(be,Se){this.g=be,this.h=Se}function Oe(be,Se){if(N(Se))throw Error("division by zero");if(N(be))return new ye(f,f);if(G(be))return Se=Oe(z(be),Se),new ye(z(Se.g),z(Se.h));if(G(Se))return Se=Oe(be,z(Se)),new ye(z(Se.g),Se.h);if(30<be.g.length){if(G(be)||G(Se))throw Error("slowDivide_ only works with positive integers.");for(var Ae=I,Ce=Se;0>=Ce.l(be);)Ae=$e(Ae),Ce=$e(Ce);var fe=Be(Ae,1),we=Be(Ce,1);for(Ce=Be(Ce,2),Ae=Be(Ae,2);!N(Ce);){var Ne=we.add(Ce);0>=Ne.l(be)&&(fe=fe.add(Ae),we=Ne),Ce=Be(Ce,1),Ae=Be(Ae,1)}return Se=J(be,fe.j(Se)),new ye(fe,Se)}for(fe=f;0<=be.l(Se);){for(Ae=Math.max(1,Math.floor(be.m()/Se.m())),Ce=Math.ceil(Math.log(Ae)/Math.LN2),Ce=48>=Ce?1:Math.pow(2,Ce-48),we=p(Ae),Ne=we.j(Se);G(Ne)||0<Ne.l(be);)Ae-=Ce,we=p(Ae),Ne=we.j(Se);N(we)&&(we=I),fe=fe.add(we),be=J(be,Ne)}return new ye(fe,be)}i.A=function(be){return Oe(this,be).h},i.and=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)&be.i(Ce);return new a(Ae,this.h&be.h)},i.or=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)|be.i(Ce);return new a(Ae,this.h|be.h)},i.xor=function(be){for(var Se=Math.max(this.g.length,be.g.length),Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=this.i(Ce)^be.i(Ce);return new a(Ae,this.h^be.h)};function $e(be){for(var Se=be.g.length+1,Ae=[],Ce=0;Ce<Se;Ce++)Ae[Ce]=be.i(Ce)<<1|be.i(Ce-1)>>>31;return new a(Ae,be.h)}function Be(be,Se){var Ae=Se>>5;Se%=32;for(var Ce=be.g.length-Ae,fe=[],we=0;we<Ce;we++)fe[we]=0<Se?be.i(we+Ae)>>>Se|be.i(we+Ae+1)<<32-Se:be.i(we+Ae);return new a(fe,be.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,tz=ice.Md5=e,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=p,a.fromString=g,gp=ice.Integer=a}).apply(typeof nce<"u"?nce:typeof self<"u"?self:typeof window<"u"?window:{});var Mk=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},up={};var nz,C7e,K0,iz,tI,kk,oz,rz,az;(function(){var i,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(j,ie,ge){return j==Array.prototype||j==Object.prototype||(j[ie]=ge.value),j};function n(j){j=[typeof globalThis=="object"&&globalThis,j,typeof window=="object"&&window,typeof self=="object"&&self,typeof Mk=="object"&&Mk];for(var ie=0;ie<j.length;++ie){var ge=j[ie];if(ge&&ge.Math==Math)return ge}throw Error("Cannot find global object")}var e=n(this);function t(j,ie){if(ie)e:{var ge=e;j=j.split(".");for(var Te=0;Te<j.length-1;Te++){var We=j[Te];if(!(We in ge))break e;ge=ge[We]}j=j[j.length-1],Te=ge[j],ie=ie(Te),ie!=Te&&ie!=null&&o(ge,j,{configurable:!0,writable:!0,value:ie})}}function r(j,ie){j instanceof String&&(j+="");var ge=0,Te=!1,We={next:function(){if(!Te&&ge<j.length){var st=ge++;return{value:ie(st,j[st]),done:!1}}return Te=!0,{done:!0,value:void 0}}};return We[Symbol.iterator]=function(){return We},We}t("Array.prototype.values",function(j){return j||function(){return r(this,function(ie,ge){return ge})}});var a=a||{},s=this||self;function c(j){var ie=typeof j;return ie=ie!="object"?ie:j?Array.isArray(j)?"array":ie:"null",ie=="array"||ie=="object"&&typeof j.length=="number"}function p(j){var ie=typeof j;return ie=="object"&&j!=null||ie=="function"}function g(j,ie,ge){return j.call.apply(j.bind,arguments)}function f(j,ie,ge){if(!j)throw Error();if(2<arguments.length){var Te=Array.prototype.slice.call(arguments,2);return function(){var We=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(We,Te),j.apply(ie,We)}}return function(){return j.apply(ie,arguments)}}function I(j,ie,ge){return I=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?g:f,I.apply(null,arguments)}function T(j,ie){var ge=Array.prototype.slice.call(arguments,1);return function(){var Te=ge.slice();return Te.push.apply(Te,arguments),j.apply(this,Te)}}function N(j,ie){function ge(){}ge.prototype=ie.prototype,j.aa=ie.prototype,j.prototype=new ge,j.prototype.constructor=j,j.Qb=function(Te,We,st){for(var Lt=Array(arguments.length-2),ho=2;ho<arguments.length;ho++)Lt[ho-2]=arguments[ho];return ie.prototype[We].apply(Te,Lt)}}function G(j){let ie=j.length;if(0<ie){let ge=Array(ie);for(let Te=0;Te<ie;Te++)ge[Te]=j[Te];return ge}return[]}function z(j,ie){for(let ge=1;ge<arguments.length;ge++){let Te=arguments[ge];if(c(Te)){let We=j.length||0,st=Te.length||0;j.length=We+st;for(let Lt=0;Lt<st;Lt++)j[We+Lt]=Te[Lt]}else j.push(Te)}}class J{constructor(ie,ge){this.i=ie,this.j=ge,this.h=0,this.g=null}get(){let ie;return 0<this.h?(this.h--,ie=this.g,this.g=ie.next,ie.next=null):ie=this.i(),ie}}function ce(j){return/^[\s\xa0]*$/.test(j)}function ye(){var j=s.navigator;return j&&(j=j.userAgent)?j:""}function Oe(j){return Oe[" "](j),j}Oe[" "]=function(){};var $e=ye().indexOf("Gecko")!=-1&&!(ye().toLowerCase().indexOf("webkit")!=-1&&ye().indexOf("Edge")==-1)&&!(ye().indexOf("Trident")!=-1||ye().indexOf("MSIE")!=-1)&&ye().indexOf("Edge")==-1;function Be(j,ie,ge){for(let Te in j)ie.call(ge,j[Te],Te,j)}function be(j,ie){for(let ge in j)ie.call(void 0,j[ge],ge,j)}function Se(j){let ie={};for(let ge in j)ie[ge]=j[ge];return ie}let Ae="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ce(j,ie){let ge,Te;for(let We=1;We<arguments.length;We++){Te=arguments[We];for(ge in Te)j[ge]=Te[ge];for(let st=0;st<Ae.length;st++)ge=Ae[st],Object.prototype.hasOwnProperty.call(Te,ge)&&(j[ge]=Te[ge])}}function fe(j){var ie=1;j=j.split(":");let ge=[];for(;0<ie&&j.length;)ge.push(j.shift()),ie--;return j.length&&ge.push(j.join(":")),ge}function we(j){s.setTimeout(()=>{throw j},0)}function Ne(){var j=qt;let ie=null;return j.g&&(ie=j.g,j.g=j.g.next,j.g||(j.h=null),ie.next=null),ie}class to{constructor(){this.h=this.g=null}add(ie,ge){let Te=St.get();Te.set(ie,ge),this.h?this.h.next=Te:this.g=Te,this.h=Te}}var St=new J(()=>new It,j=>j.reset());class It{constructor(){this.next=this.g=this.h=null}set(ie,ge){this.h=ie,this.g=ge,this.next=null}reset(){this.next=this.g=this.h=null}}let bt,Nt=!1,qt=new to,Ht=()=>{let j=s.Promise.resolve(void 0);bt=()=>{j.then(Zt)}};var Zt=()=>{for(var j;j=Ne();){try{j.h.call(j.g)}catch(ge){we(ge)}var ie=St;ie.j(j),100>ie.h&&(ie.h++,j.next=ie.g,ie.g=j)}Nt=!1};function bi(){this.s=this.s,this.C=this.C}bi.prototype.s=!1,bi.prototype.ma=function(){this.s||(this.s=!0,this.N())},bi.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Jt(j,ie){this.type=j,this.g=this.target=ie,this.defaultPrevented=!1}Jt.prototype.h=function(){this.defaultPrevented=!0};var Jn=(function(){if(!s.addEventListener||!Object.defineProperty)return!1;var j=!1,ie=Object.defineProperty({},"passive",{get:function(){j=!0}});try{let ge=()=>{};s.addEventListener("test",ge,ie),s.removeEventListener("test",ge,ie)}catch{}return j})();function Wi(j,ie){if(Jt.call(this,j?j.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,j){var ge=this.type=j.type,Te=j.changedTouches&&j.changedTouches.length?j.changedTouches[0]:null;if(this.target=j.target||j.srcElement,this.g=ie,ie=j.relatedTarget){if($e){e:{try{Oe(ie.nodeName);var We=!0;break e}catch{}We=!1}We||(ie=null)}}else ge=="mouseover"?ie=j.fromElement:ge=="mouseout"&&(ie=j.toElement);this.relatedTarget=ie,Te?(this.clientX=Te.clientX!==void 0?Te.clientX:Te.pageX,this.clientY=Te.clientY!==void 0?Te.clientY:Te.pageY,this.screenX=Te.screenX||0,this.screenY=Te.screenY||0):(this.clientX=j.clientX!==void 0?j.clientX:j.pageX,this.clientY=j.clientY!==void 0?j.clientY:j.pageY,this.screenX=j.screenX||0,this.screenY=j.screenY||0),this.button=j.button,this.key=j.key||"",this.ctrlKey=j.ctrlKey,this.altKey=j.altKey,this.shiftKey=j.shiftKey,this.metaKey=j.metaKey,this.pointerId=j.pointerId||0,this.pointerType=typeof j.pointerType=="string"?j.pointerType:Em[j.pointerType]||"",this.state=j.state,this.i=j,j.defaultPrevented&&Wi.aa.h.call(this)}}N(Wi,Jt);var Em={2:"touch",3:"pen",4:"mouse"};Wi.prototype.h=function(){Wi.aa.h.call(this);var j=this.i;j.preventDefault?j.preventDefault():j.returnValue=!1};var To="closure_listenable_"+(1e6*Math.random()|0),Ra=0;function ya(j,ie,ge,Te,We){this.listener=j,this.proxy=null,this.src=ie,this.type=ge,this.capture=!!Te,this.ha=We,this.key=++Ra,this.da=this.fa=!1}function nl(j){j.da=!0,j.listener=null,j.proxy=null,j.src=null,j.ha=null}function fc(j){this.src=j,this.g={},this.h=0}fc.prototype.add=function(j,ie,ge,Te,We){var st=j.toString();j=this.g[st],j||(j=this.g[st]=[],this.h++);var Lt=Cd(j,ie,Te,We);return-1<Lt?(ie=j[Lt],ge||(ie.fa=!1)):(ie=new ya(ie,this.src,st,!!Te,We),ie.fa=ge,j.push(ie)),ie};function Of(j,ie){var ge=ie.type;if(ge in j.g){var Te=j.g[ge],We=Array.prototype.indexOf.call(Te,ie,void 0),st;(st=0<=We)&&Array.prototype.splice.call(Te,We,1),st&&(nl(ie),j.g[ge].length==0&&(delete j.g[ge],j.h--))}}function Cd(j,ie,ge,Te){for(var We=0;We<j.length;++We){var st=j[We];if(!st.da&&st.listener==ie&&st.capture==!!ge&&st.ha==Te)return We}return-1}var Dp="closure_lm_"+(1e6*Math.random()|0),vc={};function Af(j,ie,ge,Te,We){if(Te&&Te.once)return Cu(j,ie,ge,Te,We);if(Array.isArray(ie)){for(var st=0;st<ie.length;st++)Af(j,ie[st],ge,Te,We);return null}return ge=_d(ge),j&&j[To]?j.K(ie,ge,p(Te)?!!Te.capture:!!Te,We):Pf(j,ie,ge,!1,Te,We)}function Pf(j,ie,ge,Te,We,st){if(!ie)throw Error("Invalid event type");var Lt=p(We)?!!We.capture:!!We,ho=yu(j);if(ho||(j[Dp]=ho=new fc(j)),ge=ho.add(ie,ge,Te,Lt,st),ge.proxy)return ge;if(Te=wp(),ge.proxy=Te,Te.src=j,Te.listener=ge,j.addEventListener)Jn||(We=Lt),We===void 0&&(We=!1),j.addEventListener(ie.toString(),Te,We);else if(j.attachEvent)j.attachEvent(H1(ie.toString()),Te);else if(j.addListener&&j.removeListener)j.addListener(Te);else throw Error("addEventListener and attachEvent are unavailable.");return ge}function wp(){function j(ge){return ie.call(j.src,j.listener,ge)}let ie=a8;return j}function Cu(j,ie,ge,Te,We){if(Array.isArray(ie)){for(var st=0;st<ie.length;st++)Cu(j,ie[st],ge,Te,We);return null}return ge=_d(ge),j&&j[To]?j.L(ie,ge,p(Te)?!!Te.capture:!!Te,We):Pf(j,ie,ge,!0,Te,We)}function _u(j,ie,ge,Te,We){if(Array.isArray(ie))for(var st=0;st<ie.length;st++)_u(j,ie[st],ge,Te,We);else Te=p(Te)?!!Te.capture:!!Te,ge=_d(ge),j&&j[To]?(j=j.i,ie=String(ie).toString(),ie in j.g&&(st=j.g[ie],ge=Cd(st,ge,Te,We),-1<ge&&(nl(st[ge]),Array.prototype.splice.call(st,ge,1),st.length==0&&(delete j.g[ie],j.h--)))):j&&(j=yu(j))&&(ie=j.g[ie.toString()],j=-1,ie&&(j=Cd(ie,ge,Te,We)),(ge=-1<j?ie[j]:null)&&Mf(ge))}function Mf(j){if(typeof j!="number"&&j&&!j.da){var ie=j.src;if(ie&&ie[To])Of(ie.i,j);else{var ge=j.type,Te=j.proxy;ie.removeEventListener?ie.removeEventListener(ge,Te,j.capture):ie.detachEvent?ie.detachEvent(H1(ge),Te):ie.addListener&&ie.removeListener&&ie.removeListener(Te),(ge=yu(ie))?(Of(ge,j),ge.h==0&&(ge.src=null,ie[Dp]=null)):nl(j)}}}function H1(j){return j in vc?vc[j]:vc[j]="on"+j}function a8(j,ie){if(j.da)j=!0;else{ie=new Wi(ie,this);var ge=j.listener,Te=j.ha||j.src;j.fa&&Mf(j),j=ge.call(Te,ie)}return j}function yu(j){return j=j[Dp],j instanceof fc?j:null}var xm="__closure_events_fn_"+(1e9*Math.random()>>>0);function _d(j){return typeof j=="function"?j:(j[xm]||(j[xm]=function(ie){return j.handleEvent(ie)}),j[xm])}function Ko(){bi.call(this),this.i=new fc(this),this.M=this,this.F=null}N(Ko,bi),Ko.prototype[To]=!0,Ko.prototype.removeEventListener=function(j,ie,ge,Te){_u(this,j,ie,ge,Te)};function ea(j,ie){var ge,Te=j.F;if(Te)for(ge=[];Te;Te=Te.F)ge.push(Te);if(j=j.M,Te=ie.type||ie,typeof ie=="string")ie=new Jt(ie,j);else if(ie instanceof Jt)ie.target=ie.target||j;else{var We=ie;ie=new Jt(Te,j),Ce(ie,We)}if(We=!0,ge)for(var st=ge.length-1;0<=st;st--){var Lt=ie.g=ge[st];We=Su(Lt,Te,!0,ie)&&We}if(Lt=ie.g=j,We=Su(Lt,Te,!0,ie)&&We,We=Su(Lt,Te,!1,ie)&&We,ge)for(st=0;st<ge.length;st++)Lt=ie.g=ge[st],We=Su(Lt,Te,!1,ie)&&We}Ko.prototype.N=function(){if(Ko.aa.N.call(this),this.i){var j=this.i,ie;for(ie in j.g){for(var ge=j.g[ie],Te=0;Te<ge.length;Te++)nl(ge[Te]);delete j.g[ie],j.h--}}this.F=null},Ko.prototype.K=function(j,ie,ge,Te){return this.i.add(String(j),ie,!1,ge,Te)},Ko.prototype.L=function(j,ie,ge,Te){return this.i.add(String(j),ie,!0,ge,Te)};function Su(j,ie,ge,Te){if(ie=j.i.g[String(ie)],!ie)return!0;ie=ie.concat();for(var We=!0,st=0;st<ie.length;++st){var Lt=ie[st];if(Lt&&!Lt.da&&Lt.capture==ge){var ho=Lt.listener,ba=Lt.ha||Lt.src;Lt.fa&&Of(j.i,Lt),We=ho.call(ba,Te)!==!1&&We}}return We&&!Te.defaultPrevented}function z1(j,ie,ge){if(typeof j=="function")ge&&(j=I(j,ge));else if(j&&typeof j.handleEvent=="function")j=I(j.handleEvent,j);else throw Error("Invalid listener argument");return 2147483647<Number(ie)?-1:s.setTimeout(j,ie||0)}function kf(j){j.g=z1(()=>{j.g=null,j.i&&(j.i=!1,kf(j))},j.l);let ie=j.h;j.h=null,j.m.apply(null,ie)}class DA extends bi{constructor(ie,ge){super(),this.m=ie,this.l=ge,this.h=null,this.i=!1,this.g=null}j(ie){this.h=arguments,this.g?this.i=!0:kf(this)}N(){super.N(),this.g&&(s.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function yd(j){bi.call(this),this.h=j,this.g={}}N(yd,bi);var bu=[];function Ml(j){Be(j.g,function(ie,ge){this.g.hasOwnProperty(ge)&&Mf(ie)},j),j.g={}}yd.prototype.N=function(){yd.aa.N.call(this),Ml(this)},yd.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Sd=s.JSON.stringify,G1=s.JSON.parse,W1=class{stringify(j){return s.JSON.stringify(j,void 0)}parse(j){return s.JSON.parse(j,void 0)}};function q1(){}q1.prototype.h=null;function Iu(j){return j.h||(j.h=j.i())}function Eu(){}var xu={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Tm(){Jt.call(this,"d")}N(Tm,Jt);function Y1(){Jt.call(this,"c")}N(Y1,Jt);var Dm={},pr=null;function Cc(){return pr=pr||new Ko}Dm.La="serverreachability";function wA(j){Jt.call(this,Dm.La,j)}N(wA,Jt);function Op(j){let ie=Cc();ea(ie,new wA(ie))}Dm.STAT_EVENT="statevent";function Rf(j,ie){Jt.call(this,Dm.STAT_EVENT,j),this.stat=ie}N(Rf,Jt);function ta(j){let ie=Cc();ea(ie,new Rf(ie,j))}Dm.Ma="timingevent";function K1(j,ie){Jt.call(this,Dm.Ma,j),this.size=ie}N(K1,Jt);function Tu(j,ie){if(typeof j!="function")throw Error("Fn must not be null and must be a function");return s.setTimeout(function(){j()},ie)}function Na(){this.g=!0}Na.prototype.xa=function(){this.g=!1};function wm(j,ie,ge,Te,We,st){j.info(function(){if(j.g)if(st)for(var Lt="",ho=st.split("&"),ba=0;ba<ho.length;ba++){var Ri=ho[ba].split("=");if(1<Ri.length){var Fa=Ri[0];Ri=Ri[1];var La=Fa.split("_");Lt=2<=La.length&&La[1]=="type"?Lt+(Fa+"="+Ri+"&"):Lt+(Fa+"=redacted&")}}else Lt=null;else Lt=st;return"XMLHTTP REQ ("+Te+") [attempt "+We+"]: "+ie+`
|
|
182
182
|
`+ge+`
|
|
183
183
|
`+Lt})}function OA(j,ie,ge,Te,We,st,Lt){j.info(function(){return"XMLHTTP RESP ("+Te+") [ attempt "+We+"]: "+ie+`
|
|
184
184
|
`+ge+`
|
|
@@ -204,7 +204,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
204
204
|
<img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
|
|
205
205
|
</a>
|
|
206
206
|
`}};var Gg=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new co}};var K9=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new co}};var PI=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var Wg=class{constructor(){this.pageInfo=new co}},MI=(function(i){return i.Start="start",i.End="end",i})(MI||{}),TC=(function(i){return i.Avatar="avatar",i.Label="label",i})(TC||{});var Z9=class{constructor(){this.sources=[],this.playerState=new kI}},kI=class{constructor(){this.volume=1}};var RI=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new co}};var Sp=class{constructor(){this.visibility="private"}};var X9=class{constructor(){this.reactions=[],this.type="reaction",this.pageInfo=new co,this.isReactionResolverUsed=!1}};var Q9=class{};var qs=(function(i){return i.EDITOR="editor",i.VIEWER="viewer",i})(qs||{}),Wo=(function(i){return i.DOES_NOT_EXIST="does_not_exist",i.PERMISSION_DENIED="permission_denied",i.SOMETHING_WENT_WRONG="something_went_wrong",i})(Wo||{});var Rt=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new ve(null),this.disableLogsConfig$=new ve({warnings:!0,suppressAll:!1}),this.apiKey$=new ve(""),this.baseFeatureAllowList=[],this.sf$=new ve(!1),this.sdkType$=new ve("core"),this.logsEnabled$=new ve(!0),this.safeEval$=new ve(!1),this.encryptionProvider$=new ve(null);try{this.analyticsService.setConfigService(this),this.sdkType$.subscribe(r=>{this.analyticsService.updateDefaultProperties({sdkType:r})},r=>{this.loggingService.catch("Error in ConfigService sdkType$: ",r)}),this.logsEnabled$.subscribe(r=>{r?this.loggingService.enableLogs():this.loggingService.disableLogs(),nt.logsEnabled=r},r=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",r)})}catch(r){this.loggingService.catch("Error in ConfigService constructor: ",r)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(Re)),this.baseFeatureAllowList=e.featureAllowList?.slice(),this.config$.next(e)}catch(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(r=>!e.includes(r)):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(vt(Kt))}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),se(!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),se("core")}}enableLogs(){try{if(this.logsEnabled$.value===!0)return;this.logsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableLogs: ",e)}}disableLogs(e){try{e&&this.disableLogsConfig$.next({warnings:e.warnings??!0,suppressAll:e.suppressAll??!1}),e?.warnings!==!1&&this.logsEnabled$.next(!1)}catch(t){this.loggingService.catch("Error in ConfigService disableLogs: ",t)}}getDisableLogsConfig(){return this.disableLogsConfig$.value}getDisableLogsConfig$(){return this.disableLogsConfig$.asObservable()}getApiProxyDomain(){try{return this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiProxyDomain: ",e);return}}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),se(!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),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var tpe=(()=>{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 ff;return this.setLocalStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new ff}}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 ff;return this.setSessionStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new ff}}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)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var cm=(()=>{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 Bo,t=this.localStorageService.getSessionStorageData();if(t.snippylyAvatar)e=t.snippylyAvatar;else{let r=this.generateUserAvatar();t.snippylyAvatar=r,this.localStorageService.setSessionStorageData(t)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new Bo}}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)(ee(tpe),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var ts=(()=>{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 tt),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in CoreActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new tt),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var{entries:dpe,setPrototypeOf:npe,isFrozen:ENe,getPrototypeOf:xNe,getOwnPropertyDescriptor:TNe}=Object,{freeze:_s,seal:sc,create:NW}=Object,{apply:FW,construct:LW}=typeof Reflect<"u"&&Reflect;_s||(_s=function(o){return o});sc||(sc=function(o){return o});FW||(FW=function(o,n){for(var e=arguments.length,t=new Array(e>2?e-2:0),r=2;r<e;r++)t[r-2]=arguments[r];return o.apply(n,t)});LW||(LW=function(o){for(var n=arguments.length,e=new Array(n>1?n-1:0),t=1;t<n;t++)e[t-1]=arguments[t];return new o(...e)});var J9=ys(Array.prototype.forEach),DNe=ys(Array.prototype.lastIndexOf),ipe=ys(Array.prototype.pop),FI=ys(Array.prototype.push),wNe=ys(Array.prototype.splice),tR=ys(String.prototype.toLowerCase),OW=ys(String.prototype.toString),AW=ys(String.prototype.match),LI=ys(String.prototype.replace),ONe=ys(String.prototype.indexOf),ANe=ys(String.prototype.trim),md=ys(Object.prototype.hasOwnProperty),Cs=ys(RegExp.prototype.test),BI=PNe(TypeError);function ys(i){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var n=arguments.length,e=new Array(n>1?n-1:0),t=1;t<n;t++)e[t-1]=arguments[t];return FW(i,o,e)}}function PNe(i){return function(){for(var o=arguments.length,n=new Array(o),e=0;e<o;e++)n[e]=arguments[e];return LW(i,n)}}function ui(i,o){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tR;npe&&npe(i,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let r=n(t);r!==t&&(ENe(o)||(o[e]=r),t=r)}i[t]=!0}return i}function MNe(i){for(let o=0;o<i.length;o++)md(i,o)||(i[o]=null);return i}function bp(i){let o=NW(null);for(let[n,e]of dpe(i))md(i,n)&&(Array.isArray(e)?o[n]=MNe(e):e&&typeof e=="object"&&e.constructor===Object?o[n]=bp(e):o[n]=e);return o}function VI(i,o){for(;i!==null;){let e=TNe(i,o);if(e){if(e.get)return ys(e.get);if(typeof e.value=="function")return ys(e.value)}i=xNe(i)}function n(){return null}return n}var ope=_s(["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"]),PW=_s(["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"]),MW=_s(["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"]),kNe=_s(["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"]),kW=_s(["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"]),RNe=_s(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rpe=_s(["#text"]),ape=_s(["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"]),RW=_s(["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"]),spe=_s(["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"]),eR=_s(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),NNe=sc(/\{\{[\w\W]*|[\w\W]*\}\}/gm),FNe=sc(/<%[\w\W]*|[\w\W]*%>/gm),LNe=sc(/\$\{[\w\W]*/gm),BNe=sc(/^data-[\-\w.\u00B7-\uFFFF]+$/),VNe=sc(/^aria-[\-\w]+$/),mpe=sc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),UNe=sc(/^(?:\w+script|data):/i),jNe=sc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ppe=sc(/^html$/i),$Ne=sc(/^[a-z][.\w]*(-[.\w]+)+$/i),lpe=Object.freeze({__proto__:null,ARIA_ATTR:VNe,ATTR_WHITESPACE:jNe,CUSTOM_ELEMENT:$Ne,DATA_ATTR:BNe,DOCTYPE_NAME:ppe,ERB_EXPR:FNe,IS_ALLOWED_URI:mpe,IS_SCRIPT_OR_DATA:UNe,MUSTACHE_EXPR:NNe,TMPLIT_EXPR:LNe}),UI={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},HNe=function(){return typeof window>"u"?null:window},zNe=function(o,n){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,t="data-tt-policy-suffix";n&&n.hasAttribute(t)&&(e=n.getAttribute(t));let r="dompurify"+(e?"#"+e:"");try{return o.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},cpe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function gpe(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:HNe(),o=ln=>gpe(ln);if(o.version="3.3.0",o.removed=[],!i||!i.document||i.document.nodeType!==UI.document||!i.Element)return o.isSupported=!1,o;let{document:n}=i,e=n,t=e.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:s,Element:c,NodeFilter:p,NamedNodeMap:g=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:f,DOMParser:I,trustedTypes:T}=i,N=c.prototype,G=VI(N,"cloneNode"),z=VI(N,"remove"),J=VI(N,"nextSibling"),ce=VI(N,"childNodes"),ye=VI(N,"parentNode");if(typeof a=="function"){let ln=n.createElement("template");ln.content&&ln.content.ownerDocument&&(n=ln.content.ownerDocument)}let Oe,$e="",{implementation:Be,createNodeIterator:be,createDocumentFragment:Se,getElementsByTagName:Ae}=n,{importNode:Ce}=e,fe=cpe();o.isSupported=typeof dpe=="function"&&typeof ye=="function"&&Be&&Be.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:we,ERB_EXPR:Ne,TMPLIT_EXPR:to,DATA_ATTR:St,ARIA_ATTR:It,IS_SCRIPT_OR_DATA:bt,ATTR_WHITESPACE:Nt,CUSTOM_ELEMENT:qt}=lpe,{IS_ALLOWED_URI:Ht}=lpe,Zt=null,bi=ui({},[...ope,...PW,...MW,...kW,...rpe]),Jt=null,Jn=ui({},[...ape,...RW,...spe,...eR]),Wi=Object.seal(NW(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}})),Em=null,To=null,Ra=Object.seal(NW(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ya=!0,nl=!0,fc=!1,Of=!0,Cd=!1,Dp=!0,vc=!1,Af=!1,Pf=!1,wp=!1,Cu=!1,_u=!1,Mf=!0,H1=!1,a8="user-content-",yu=!0,xm=!1,_d={},Ko=null,ea=ui({},["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"]),Su=null,z1=ui({},["audio","video","img","source","image","track"]),kf=null,DA=ui({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),yd="http://www.w3.org/1998/Math/MathML",bu="http://www.w3.org/2000/svg",Ml="http://www.w3.org/1999/xhtml",Sd=Ml,G1=!1,W1=null,q1=ui({},[yd,bu,Ml],OW),Iu=ui({},["mi","mo","mn","ms","mtext"]),Eu=ui({},["annotation-xml"]),xu=ui({},["title","style","font","a","script"]),Tm=null,Y1=["application/xhtml+xml","text/html"],Dm="text/html",pr=null,Cc=null,wA=n.createElement("form"),Op=function(Ve){return Ve instanceof RegExp||Ve instanceof Function},Rf=function(){let Ve=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Cc&&Cc===Ve)){if((!Ve||typeof Ve!="object")&&(Ve={}),Ve=bp(Ve),Tm=Y1.indexOf(Ve.PARSER_MEDIA_TYPE)===-1?Dm:Ve.PARSER_MEDIA_TYPE,pr=Tm==="application/xhtml+xml"?OW:tR,Zt=md(Ve,"ALLOWED_TAGS")?ui({},Ve.ALLOWED_TAGS,pr):bi,Jt=md(Ve,"ALLOWED_ATTR")?ui({},Ve.ALLOWED_ATTR,pr):Jn,W1=md(Ve,"ALLOWED_NAMESPACES")?ui({},Ve.ALLOWED_NAMESPACES,OW):q1,kf=md(Ve,"ADD_URI_SAFE_ATTR")?ui(bp(DA),Ve.ADD_URI_SAFE_ATTR,pr):DA,Su=md(Ve,"ADD_DATA_URI_TAGS")?ui(bp(z1),Ve.ADD_DATA_URI_TAGS,pr):z1,Ko=md(Ve,"FORBID_CONTENTS")?ui({},Ve.FORBID_CONTENTS,pr):ea,Em=md(Ve,"FORBID_TAGS")?ui({},Ve.FORBID_TAGS,pr):bp({}),To=md(Ve,"FORBID_ATTR")?ui({},Ve.FORBID_ATTR,pr):bp({}),_d=md(Ve,"USE_PROFILES")?Ve.USE_PROFILES:!1,ya=Ve.ALLOW_ARIA_ATTR!==!1,nl=Ve.ALLOW_DATA_ATTR!==!1,fc=Ve.ALLOW_UNKNOWN_PROTOCOLS||!1,Of=Ve.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Cd=Ve.SAFE_FOR_TEMPLATES||!1,Dp=Ve.SAFE_FOR_XML!==!1,vc=Ve.WHOLE_DOCUMENT||!1,wp=Ve.RETURN_DOM||!1,Cu=Ve.RETURN_DOM_FRAGMENT||!1,_u=Ve.RETURN_TRUSTED_TYPE||!1,Pf=Ve.FORCE_BODY||!1,Mf=Ve.SANITIZE_DOM!==!1,H1=Ve.SANITIZE_NAMED_PROPS||!1,yu=Ve.KEEP_CONTENT!==!1,xm=Ve.IN_PLACE||!1,Ht=Ve.ALLOWED_URI_REGEXP||mpe,Sd=Ve.NAMESPACE||Ml,Iu=Ve.MATHML_TEXT_INTEGRATION_POINTS||Iu,Eu=Ve.HTML_INTEGRATION_POINTS||Eu,Wi=Ve.CUSTOM_ELEMENT_HANDLING||{},Ve.CUSTOM_ELEMENT_HANDLING&&Op(Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Wi.tagNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&Op(Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Wi.attributeNameCheck=Ve.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ve.CUSTOM_ELEMENT_HANDLING&&typeof Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Wi.allowCustomizedBuiltInElements=Ve.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Cd&&(nl=!1),Cu&&(wp=!0),_d&&(Zt=ui({},rpe),Jt=[],_d.html===!0&&(ui(Zt,ope),ui(Jt,ape)),_d.svg===!0&&(ui(Zt,PW),ui(Jt,RW),ui(Jt,eR)),_d.svgFilters===!0&&(ui(Zt,MW),ui(Jt,RW),ui(Jt,eR)),_d.mathMl===!0&&(ui(Zt,kW),ui(Jt,spe),ui(Jt,eR))),Ve.ADD_TAGS&&(typeof Ve.ADD_TAGS=="function"?Ra.tagCheck=Ve.ADD_TAGS:(Zt===bi&&(Zt=bp(Zt)),ui(Zt,Ve.ADD_TAGS,pr))),Ve.ADD_ATTR&&(typeof Ve.ADD_ATTR=="function"?Ra.attributeCheck=Ve.ADD_ATTR:(Jt===Jn&&(Jt=bp(Jt)),ui(Jt,Ve.ADD_ATTR,pr))),Ve.ADD_URI_SAFE_ATTR&&ui(kf,Ve.ADD_URI_SAFE_ATTR,pr),Ve.FORBID_CONTENTS&&(Ko===ea&&(Ko=bp(Ko)),ui(Ko,Ve.FORBID_CONTENTS,pr)),yu&&(Zt["#text"]=!0),vc&&ui(Zt,["html","head","body"]),Zt.table&&(ui(Zt,["tbody"]),delete Em.tbody),Ve.TRUSTED_TYPES_POLICY){if(typeof Ve.TRUSTED_TYPES_POLICY.createHTML!="function")throw BI('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ve.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw BI('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Oe=Ve.TRUSTED_TYPES_POLICY,$e=Oe.createHTML("")}else Oe===void 0&&(Oe=zNe(T,t)),Oe!==null&&typeof $e=="string"&&($e=Oe.createHTML(""));_s&&_s(Ve),Cc=Ve}},ta=ui({},[...PW,...MW,...kNe]),K1=ui({},[...kW,...RNe]),Tu=function(Ve){let At=ye(Ve);(!At||!At.tagName)&&(At={namespaceURI:Sd,tagName:"template"});let Xt=tR(Ve.tagName),uo=tR(At.tagName);return W1[Ve.namespaceURI]?Ve.namespaceURI===bu?At.namespaceURI===Ml?Xt==="svg":At.namespaceURI===yd?Xt==="svg"&&(uo==="annotation-xml"||Iu[uo]):!!ta[Xt]:Ve.namespaceURI===yd?At.namespaceURI===Ml?Xt==="math":At.namespaceURI===bu?Xt==="math"&&Eu[uo]:!!K1[Xt]:Ve.namespaceURI===Ml?At.namespaceURI===bu&&!Eu[uo]||At.namespaceURI===yd&&!Iu[uo]?!1:!K1[Xt]&&(xu[Xt]||!ta[Xt]):!!(Tm==="application/xhtml+xml"&&W1[Ve.namespaceURI]):!1},Na=function(Ve){FI(o.removed,{element:Ve});try{ye(Ve).removeChild(Ve)}catch{z(Ve)}},wm=function(Ve,At){try{FI(o.removed,{attribute:At.getAttributeNode(Ve),from:At})}catch{FI(o.removed,{attribute:null,from:At})}if(At.removeAttribute(Ve),Ve==="is")if(wp||Cu)try{Na(At)}catch{}else try{At.setAttribute(Ve,"")}catch{}},OA=function(Ve){let At=null,Xt=null;if(Pf)Ve="<remove></remove>"+Ve;else{let ko=AW(Ve,/^[\r\n\t ]+/);Xt=ko&&ko[0]}Tm==="application/xhtml+xml"&&Sd===Ml&&(Ve='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ve+"</body></html>");let uo=Oe?Oe.createHTML(Ve):Ve;if(Sd===Ml)try{At=new I().parseFromString(uo,Tm)}catch{}if(!At||!At.documentElement){At=Be.createDocument(Sd,"template",null);try{At.documentElement.innerHTML=G1?$e:uo}catch{}}let na=At.body||At.documentElement;return Ve&&Xt&&na.insertBefore(n.createTextNode(Xt),na.childNodes[0]||null),Sd===Ml?Ae.call(At,vc?"html":"body")[0]:vc?At.documentElement:na},Om=function(Ve){return be.call(Ve.ownerDocument||Ve,Ve,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Z1=function(Ve){return Ve instanceof f&&(typeof Ve.nodeName!="string"||typeof Ve.textContent!="string"||typeof Ve.removeChild!="function"||!(Ve.attributes instanceof g)||typeof Ve.removeAttribute!="function"||typeof Ve.setAttribute!="function"||typeof Ve.namespaceURI!="string"||typeof Ve.insertBefore!="function"||typeof Ve.hasChildNodes!="function")},AA=function(Ve){return typeof s=="function"&&Ve instanceof s};function ws(ln,Ve,At){J9(ln,Xt=>{Xt.call(o,Ve,At,Cc)})}let X1=function(Ve){let At=null;if(ws(fe.beforeSanitizeElements,Ve,null),Z1(Ve))return Na(Ve),!0;let Xt=pr(Ve.nodeName);if(ws(fe.uponSanitizeElement,Ve,{tagName:Xt,allowedTags:Zt}),Dp&&Ve.hasChildNodes()&&!AA(Ve.firstElementChild)&&Cs(/<[/\w!]/g,Ve.innerHTML)&&Cs(/<[/\w!]/g,Ve.textContent)||Ve.nodeType===UI.progressingInstruction||Dp&&Ve.nodeType===UI.comment&&Cs(/<[/\w]/g,Ve.data))return Na(Ve),!0;if(!(Ra.tagCheck instanceof Function&&Ra.tagCheck(Xt))&&(!Zt[Xt]||Em[Xt])){if(!Em[Xt]&&Du(Xt)&&(Wi.tagNameCheck instanceof RegExp&&Cs(Wi.tagNameCheck,Xt)||Wi.tagNameCheck instanceof Function&&Wi.tagNameCheck(Xt)))return!1;if(yu&&!Ko[Xt]){let uo=ye(Ve)||Ve.parentNode,na=ce(Ve)||Ve.childNodes;if(na&&uo){let ko=na.length;for(let Sa=ko-1;Sa>=0;--Sa){let il=G(na[Sa],!0);il.__removalCount=(Ve.__removalCount||0)+1,uo.insertBefore(il,J(Ve))}}}return Na(Ve),!0}return Ve instanceof c&&!Tu(Ve)||(Xt==="noscript"||Xt==="noembed"||Xt==="noframes")&&Cs(/<\/no(script|embed|frames)/i,Ve.innerHTML)?(Na(Ve),!0):(Cd&&Ve.nodeType===UI.text&&(At=Ve.textContent,J9([we,Ne,to],uo=>{At=LI(At,uo," ")}),Ve.textContent!==At&&(FI(o.removed,{element:Ve.cloneNode()}),Ve.textContent=At)),ws(fe.afterSanitizeElements,Ve,null),!1)},Nf=function(Ve,At,Xt){if(Mf&&(At==="id"||At==="name")&&(Xt in n||Xt in wA))return!1;if(!(nl&&!To[At]&&Cs(St,At))){if(!(ya&&Cs(It,At))){if(!(Ra.attributeCheck instanceof Function&&Ra.attributeCheck(At,Ve))){if(!Jt[At]||To[At]){if(!(Du(Ve)&&(Wi.tagNameCheck instanceof RegExp&&Cs(Wi.tagNameCheck,Ve)||Wi.tagNameCheck instanceof Function&&Wi.tagNameCheck(Ve))&&(Wi.attributeNameCheck instanceof RegExp&&Cs(Wi.attributeNameCheck,At)||Wi.attributeNameCheck instanceof Function&&Wi.attributeNameCheck(At,Ve))||At==="is"&&Wi.allowCustomizedBuiltInElements&&(Wi.tagNameCheck instanceof RegExp&&Cs(Wi.tagNameCheck,Xt)||Wi.tagNameCheck instanceof Function&&Wi.tagNameCheck(Xt))))return!1}else if(!kf[At]){if(!Cs(Ht,LI(Xt,Nt,""))){if(!((At==="src"||At==="xlink:href"||At==="href")&&Ve!=="script"&&ONe(Xt,"data:")===0&&Su[Ve])){if(!(fc&&!Cs(bt,LI(Xt,Nt,"")))){if(Xt)return!1}}}}}}}return!0},Du=function(Ve){return Ve!=="annotation-xml"&&AW(Ve,qt)},_c=function(Ve){ws(fe.beforeSanitizeAttributes,Ve,null);let{attributes:At}=Ve;if(!At||Z1(Ve))return;let Xt={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Jt,forceKeepAttr:void 0},uo=At.length;for(;uo--;){let na=At[uo],{name:ko,namespaceURI:Sa,value:il}=na,kl=pr(ko),yc=il,gr=ko==="value"?yc:ANe(yc);if(Xt.attrName=kl,Xt.attrValue=gr,Xt.keepAttr=!0,Xt.forceKeepAttr=void 0,ws(fe.uponSanitizeAttribute,Ve,Xt),gr=Xt.attrValue,H1&&(kl==="id"||kl==="name")&&(wm(ko,Ve),gr=a8+gr),Dp&&Cs(/((--!?|])>)|<\/(style|title|textarea)/i,gr)){wm(ko,Ve);continue}if(kl==="attributename"&&AW(gr,"href")){wm(ko,Ve);continue}if(Xt.forceKeepAttr)continue;if(!Xt.keepAttr){wm(ko,Ve);continue}if(!Of&&Cs(/\/>/i,gr)){wm(ko,Ve);continue}Cd&&J9([we,Ne,to],Q1=>{gr=LI(gr,Q1," ")});let MA=pr(Ve.nodeName);if(!Nf(MA,kl,gr)){wm(ko,Ve);continue}if(Oe&&typeof T=="object"&&typeof T.getAttributeType=="function"&&!Sa)switch(T.getAttributeType(MA,kl)){case"TrustedHTML":{gr=Oe.createHTML(gr);break}case"TrustedScriptURL":{gr=Oe.createScriptURL(gr);break}}if(gr!==yc)try{Sa?Ve.setAttributeNS(Sa,ko,gr):Ve.setAttribute(ko,gr),Z1(Ve)?Na(Ve):ipe(o.removed)}catch{wm(ko,Ve)}}ws(fe.afterSanitizeAttributes,Ve,null)},PA=function ln(Ve){let At=null,Xt=Om(Ve);for(ws(fe.beforeSanitizeShadowDOM,Ve,null);At=Xt.nextNode();)ws(fe.uponSanitizeShadowNode,At,null),X1(At),_c(At),At.content instanceof r&&ln(At.content);ws(fe.afterSanitizeShadowDOM,Ve,null)};return o.sanitize=function(ln){let Ve=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},At=null,Xt=null,uo=null,na=null;if(G1=!ln,G1&&(ln="<!-->"),typeof ln!="string"&&!AA(ln))if(typeof ln.toString=="function"){if(ln=ln.toString(),typeof ln!="string")throw BI("dirty is not a string, aborting")}else throw BI("toString is not a function");if(!o.isSupported)return ln;if(Af||Rf(Ve),o.removed=[],typeof ln=="string"&&(xm=!1),xm){if(ln.nodeName){let il=pr(ln.nodeName);if(!Zt[il]||Em[il])throw BI("root node is forbidden and cannot be sanitized in-place")}}else if(ln instanceof s)At=OA("<!---->"),Xt=At.ownerDocument.importNode(ln,!0),Xt.nodeType===UI.element&&Xt.nodeName==="BODY"||Xt.nodeName==="HTML"?At=Xt:At.appendChild(Xt);else{if(!wp&&!Cd&&!vc&&ln.indexOf("<")===-1)return Oe&&_u?Oe.createHTML(ln):ln;if(At=OA(ln),!At)return wp?null:_u?$e:""}At&&Pf&&Na(At.firstChild);let ko=Om(xm?ln:At);for(;uo=ko.nextNode();)X1(uo),_c(uo),uo.content instanceof r&&PA(uo.content);if(xm)return ln;if(wp){if(Cu)for(na=Se.call(At.ownerDocument);At.firstChild;)na.appendChild(At.firstChild);else na=At;return(Jt.shadowroot||Jt.shadowrootmode)&&(na=Ce.call(e,na,!0)),na}let Sa=vc?At.outerHTML:At.innerHTML;return vc&&Zt["!doctype"]&&At.ownerDocument&&At.ownerDocument.doctype&&At.ownerDocument.doctype.name&&Cs(ppe,At.ownerDocument.doctype.name)&&(Sa="<!DOCTYPE "+At.ownerDocument.doctype.name+`>
|
|
207
|
-
`+Sa),Cd&&J9([we,Ne,to],il=>{Sa=LI(Sa,il," ")}),Oe&&_u?Oe.createHTML(Sa):Sa},o.setConfig=function(){let ln=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rf(ln),Af=!0},o.clearConfig=function(){Cc=null,Af=!1},o.isValidAttribute=function(ln,Ve,At){Cc||Rf({});let Xt=pr(ln),uo=pr(Ve);return Nf(Xt,uo,At)},o.addHook=function(ln,Ve){typeof Ve=="function"&&FI(fe[ln],Ve)},o.removeHook=function(ln,Ve){if(Ve!==void 0){let At=DNe(fe[ln],Ve);return At===-1?void 0:wNe(fe[ln],At,1)[0]}return ipe(fe[ln])},o.removeHooks=function(ln){fe[ln]=[]},o.removeAllHooks=function(){fe=cpe()},o}var jI=gpe();var upe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Le=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=r,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new tt,this.windowPointerMove$=new ve(null),this.windowPointerUp$=new ve(null),this.documentSelectionChange$=new ve(null),this.windowClick$=new ve(null),this.windowScroll$=new ve(null),this.windowResize$=new ve(null),this.windowKeyupBackspace$=new ve(null),this.windowKeyupDelete$=new ve(null),this.windowKeyupEsc$=new ve(null),this.windowPopState$=new ve(null),this.documentClick$=new ve(null),this.documentClickSubject$=new tt,this.documentFocus$=new ve(null),this.windowKeydownShift$=new ve(null),this.windowKeyupShift$=new ve(null),this.mutation$=new ve(null),this.childListMutation$=new ve(null),this.networkStatus$=new ve(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new ve({}),this.selectedAnnotationsLocationMap$=new ve({}),this.recordingInProgress$=new ve({}),this.deleteAnnotations$=new ve([]),this.pinHighlighterClass$=new ve(null),this.dialogOpenedInSidebar$=new ve(!1),this.textHighlighterClass$=new ve(null),this.commentPinHighlighter$=new ve(!1),this.deviceInfo$=new ve(new Yn),this.customCss$=new ve(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=s=>{try{let c=[];return s.forEach(p=>{if(!Gi(p))if(p instanceof HTMLElement){if(p.className.includes("cdk-overlay-container")||p.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(p.className.includes("cdk-overlay")){let g=!1;p.childNodes.forEach(f=>{Gi(f)&&(g=!0)}),g||c.push(p)}else c.push(p)}else c.push(p)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let s=this.calculateScreenSize();this.currentScreenSize$=new ve(s),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Ti(),tn(([c,p])=>{try{let g=p.filter(I=>!c.includes(I)),f=c.filter(I=>!p.includes(I));f.length&&f.map(T=>document.getElementById(T)).filter(T=>T).forEach(T=>{this.unlistenElementScroll&&this.unlistenElementScroll[T.id]&&this.unlistenElementScroll[T.id]()}),g.length&&g.map(T=>document.getElementById(T)).filter(T=>T).forEach(T=>{this.unlistenElementScroll[T.id]=this.renderer.listen(T,"scroll",N=>{let G=this.calculateScreenSize();this.currentScreenSize$.next(G)})})}catch(g){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",g)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?Ble("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):Vle("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(s){this.loggingService.catch("Error in DomService constructor: ",s)}}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(r=>typeof r=="string"?new RegExp(r):r).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 r=new Set(["id","class","style"]);return e.getAttributeNames().forEach(s=>{if(r.has(s)||s.includes("snippyly")||s.includes("velt"))return;let c=e.getAttribute(s);c&&c.length<=256&&(t[s]=c)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],s=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((p,g)=>{let f=s.findIndex(T=>p.startsWith(T)),I=s.findIndex(T=>g.startsWith(T));return(f===-1?99:f)-(I===-1?99:I)}).slice(0,4).forEach(p=>{let g=CSS.escape(t[p]);a.push(`[${p}="${g}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",s,c=0;for(;(s=r.nextNode())&&a.length<t;){let p=(s.textContent||"").replace(/\s+/g," ").trim();if(p&&(a+=(a?" ":"")+p),c++,c>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return Tle(e)}catch{return}}generateRobustXPath(e,t){try{let r=t?.maxDepth||10,a=t?.useAbsolutePath||!1,s=[],c=e,p=0;for(;c&&c!==document.documentElement&&p<r;){let T=this.buildRobustXPathSegment(c);if(T&&(s.unshift(T),this.isStrongAnchorSegment(T)))break;c=c.parentElement,p++}if(s.length===0)return;let f=(a?"/":"//")+s.join("/");return s.some(T=>T.includes("[@")||T.includes("[contains(@class"))?f:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),r=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let I of r){let T=e.getAttribute(I);if(T)return`${t}[@${I}=${this.escapeXPathValue(T)}]`}let a=Array.from(e.attributes).filter(I=>I.name.startsWith("data-")&&!I.name.includes("snippyly")&&!I.name.includes("velt")&&I.value.length<100).sort((I,T)=>I.value.length-T.value.length);if(a.length>0){let I=a[0];return`${t}[@${I.name}=${this.escapeXPathValue(I.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let c=e.getAttribute("aria-label");if(c&&c.length<50)return`${t}[@aria-label=${this.escapeXPathValue(c)}]`;let p=e.getAttribute("name");if(p)return`${t}[@name=${this.escapeXPathValue(p)}]`;let g=e.getAttribute("type");if(g)return`${t}[@type=${this.escapeXPathValue(g)}]`;let f=Array.from(e.classList||[]).filter(I=>I.length>0&&I.length<40&&!I.includes("yui")&&!I.includes("velt")&&!I.includes("snippyly")&&!this.excludeClassList.includes(I)).slice(0,2);if(f.length>0){let I=f.map(T=>`contains(@class, ${this.escapeXPathValue(T)})`).join(" and ");return`${t}[${I}]`}if(e.parentElement){let I=Array.from(e.parentElement.children).filter(T=>T.tagName===e.tagName);if(I.length>1){let T=I.indexOf(e)+1;return`${t}[${T}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(["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(s=>`'${s}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(c=>`'${c}'`).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}}generateAnchorRecord(e,t){try{let r=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Di(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),r&&a){let s=this.generateAnchorRecordForElement(a,t);s&&(r.parent=s)}return r}catch(r){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",r),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let r=e,a=r.tagName?.toUpperCase();if(!a)return null;let s=r.id&&!this.isLikelyDynamicId(r.id)?r.id:void 0,c=this.getStableAttributes(r),p=this.buildStableElementSelector(r,c),g=this.getVisibleText(r),f=this.hashText(g||""),I=this.generateRobustXPath(r),T=this.getXPath(r),N=this.getXPath(r,!0),G=this.getXPath(r,!0,!0);return{version:"1.0",id:s,tagName:a,elementSelector:p,robustXPath:I||void 0,xPath:T||void 0,fXPath:N||void 0,cfXPath:G||void 0,contentHash:f?{value:f,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(r){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",r),null}}resolveAnchorRecord(e){try{let t=[],r=null,a=(f,I,T=0)=>{let N=[],G=T;if(N.push({method:I,score:T}),e.tagName&&f.tagName?.toUpperCase()===e.tagName&&(G+=10,N.push({method:"tagName-match",score:10})),e.contentHash?.value){let z=this.getVisibleText(f);this.hashText(z)===e.contentHash.value&&(G+=30,N.push({method:"contentHash-match",score:30}))}t.push({el:f,score:G,by:I,scoreBreakdown:N})};if(e.id){let f=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(f.length===1)return{element:f[0],matchedBy:"id",score:90};f.length>1&&f.forEach(I=>a(I,"id-duplicate",70))}if(e.elementSelector){let f=document.querySelectorAll(e.elementSelector);if(f.length===1)return{element:f[0],matchedBy:"element-selector",score:80};f.forEach(I=>a(I,"element-selector-duplicate",60))}if(e.robustXPath){let f=this.getElementFromRobustXPath(e.robustXPath);f&&a(f,"robustXPath",50)}e?.parent&&(r=this.resolveAnchorRecord(e.parent),r.element&&r.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(I=>a(I,"parent+tag",40)));let s=(f,I,T)=>{if(!f)return;let N=this.getElementFromXPath(f);N&&a(N,I||"xpath",T||30)};if(s(e.xPath,"xPath",30),s(e.cfXPath,"cfXPath",30),s(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let I=T=>{let N=0;for(let G=0;G<T.length&&N<400;G++){let z=T[G];if(N++,!this.isElementVisible(z))continue;let J=this.getVisibleText(z),ce=this.hashText(J);ce&&ce===e.contentHash?.value&&a(z,"contentHash",15)}};if(r?.element&&r?.element instanceof Element){let T=r?.element?.querySelectorAll("*");I(T)}}if(!t.length)return{element:null};t.sort((f,I)=>I.score-f.score);let c=t[0].score,p=t.filter(f=>f.score===c);if(p.length>1){let f=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let I of f)if(I.path){let T=this.getElementFromXPath(I.path);if(T){let N=p.find(G=>G.el===T);if(N)return{element:N.el,matchedBy:`${N.by}+position`,score:N.score,scoreBreakdown:N.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(de(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.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=t.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let g=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(g!==null&&g!==""){let f=this.xpathCacheId.get(g);f!==void 0&&(this.xpathCacheId.delete(g),this.xpathCache.delete(f))}}}),Gi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...t.filter(a=>a.type==="attributes").filter(a=>!Gi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&Di(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{No(hi(window,"offline").pipe(de(()=>!1)),hi(window,"online").pipe(de(()=>!0)),new Ut(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 Yn),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 hi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Rl}}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),r=e.target;if(t?.includes("name()='svg'")){let f=this.getXPath(t);f&&(r=f.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),g=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:g,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,r=!1,a=!0,s,c=!0,p){try{let g=e,f=g?.touches?.length?g.touches[0]?.clientX:g?.clientX,I=g?.touches?.length?g.touches[0]?.clientY:g?.clientY;p&&(f=p.clientX,I=p.clientY);let T=this.getBackgroundElement(f,I,t,r);if(T&&s&&typeof s=="function"&&(T=s(T)),T){let N=this.getXPath(T),G=this.getXPath(T,!0),z=T.getBoundingClientRect(),J=f-z.x,ce=I-z.y,ye=J*100/(z.width||1),Oe=ce*100/(z.height||1),$e={xpath:N,fXpath:G,leftPercentage:ye,topPercentage:Oe};if(a){let Be=this.getXPath(T,!0,!0);$e.cfXpath=Be}if(c){let Be=this.generateAnchorRecord(T);Be&&($e.anchor=Be)}return $e}else return null}catch(g){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",g),null}}getBackgroundElement(e,t,r=!0,a=!1){try{let s=document.elementsFromPoint(e,t),c=[];s.forEach(g=>{Gi(g)?c=[]:Di(g)&&c.push(g)}),a&&(c=c.filter(g=>this.isElementVisibleOnScreen(g)));let p=0;return r||c?.forEach((g,f)=>{g.tagName.toLowerCase()==="svg"&&(p=f)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,t){try{let r=document.elementsFromPoint(e,t),a=[];return r.forEach(s=>{Gi(s)&&Di(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(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,r=Math.min(t,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,t,r){if(e){if(!r&&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"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",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,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,t),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(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,r=!1,a){try{let s=this.calculateXPath(e,t,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((g,f)=>{g.includes("svg")&&(p=!0),p&&(c[f]="svg:"+g)}),s=c.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!t)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,t,r,a)+"/"+e.tagName.toLowerCase(),g=Array.from(e.parentNode?.children||[]).filter(f=>f.nodeType===1&&f.tagName===e.tagName?f.className?.split(" ")?.filter(T=>T?.includes("snippyly")||T?.includes("velt")||["show-pin-cursor"].includes(T))[0]===c:!1);if(g.length>1){let f=g.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${f}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}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 r=this.getXPath(e,!1,!1,t);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=on();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let r=this.resolveAnchorRecord(e.anchor);r?.element&&(t=r.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 r=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);r?.element&&(t=r.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 r=new PI;return r.screenWidth=Math.max(...t),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new PI}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(I=>{I.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(I=>{I.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(I=>{I?.parentNode?.insertBefore(document.createTextNode(I?.textContent),I),I.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),g;for(;g=p.nextNode();)g?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.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 r=t.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)t.textContent+=r.textContent,r.remove(),r=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 r=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=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 r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(f=>f.classList.contains("velt-annotation-draft-checked")?(f.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(f,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(f,"velt-comment-dialog-shake"),f.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||f.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(f,"velt-annotation-draft-checked")},100),f.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(f=>f),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let f=[];Object.keys(p).forEach(I=>{if(p[I]?.type==="tag"){let T=p[I];T?.to?.length||s.includes(I)||f.push(T)}else p[I]?.comments?.length||s.includes(I)||f.push(p[I])}),this.deleteAnnotations$.next(f),this.deleteAnnotations$.next([])}let g={};Object.keys(p).forEach(f=>{if(s.includes(f)&&(g[f]=p[f]),t)switch(t){case"comment":["comment","videoPin"].includes(p[f]?.type)||(g[f]=p[f]);break;default:p[f]?.type!==t&&(g[f]=p[f]);break}}),Object.keys(g).forEach(f=>{let I=g[f]?.multiThreadAnnotationId;I&&!g[I]&&(g[I]={annotationId:I,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(g)&&this.selectedAnnotationsMap$.next(g),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(D(E({},this.recordingInProgress$.value),{[e]:t}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(r[a]=t[a]);break;default:t[a].type===e&&(r[a]=t[a]);break}}),r}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(de(t=>{if(e){let r={};return Object.keys(t).forEach(a=>{t[a].type===e&&(r[a]=t[a])}),r}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(de(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,r,a=!1,s){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),p=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,p[e.annotationId]=t,s=e?.multiThreadAnnotationId||s,s&&(c[s]={annotationId:s,type:"multiThread"},p[s]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(p).forEach(g=>{c[g]||delete p[g]}),this.selectedAnnotationsLocationMap$.next(p)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}setSelectedAnnotationLocation(e,t){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==t&&(r[e]=t,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(r=>{t[r.annotationId]&&(t[r.annotationId]=r)}),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),se([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===t){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let g=p.getBoundingClientRect(),f=a.getBoundingClientRect();r.offsetLeft+=f.left-g.left,r.offsetTop+=f.top-g.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return t>0||r>0||a<window.innerHeight&&s>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,r=window.getComputedStyle(t);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ut(e=>{let t=hi(document,"mousedown").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=hi(document,"mousemove").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=hi(document,"mouseup").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=t.pipe(he(p=>r.pipe(Ti(),de(([g,f])=>({startPoint:p,prevPoint:g,curPoint:f})),fo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,t){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y),c=Math.min(e.x,t.x),p=Math.min(e.y,t.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let t={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);if(c){t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let p=this.generateAnchorRecord(c);p&&(t.commonAncestorContainerAnchor=p)}}return t.text=e.toString(),t.occurrence=Qh(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,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&t++,r=r.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 r=e?.closest("picture");return r?r?.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:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(t?.length)for(let s=0;s<t.length;s++){let c=document.getElementsByClassName(t[s]);for(let p=0;p<c.length;p++){let g=c[p];g&&g instanceof HTMLElement&&a.push(g)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let g=c[p];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 r=0;r<t.length;r++){let a=document.getElementById(t[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementsByClassName(t[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.querySelectorAll(t[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,t,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(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),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.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 r=t.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var t=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(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;"),jI.sanitize(e,upe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return jI.sanitize(e,upe)}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 Yn;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),se(new Yn)}}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=on(),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 Yn}}isMobileDevice(){try{return new Yn().getDeviceType()===sr.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Yn().getDeviceType()===sr.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Yn().getDeviceType()===sr.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(r=>{t.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(r.nodeValue))}),t}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),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(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Yn().getDeviceType()===sr.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Zo),ee(y),ee(ml))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ue=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.afAuth=e,this.configService=t,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=g,this.user$=new ve(null),this.userOptions$=new ve(null),this.userContacts$=new ve(null),this.userOrganization$=new ve(null),this.providedUser=new Bo,this.firebaseConfig$=new ve(null),this.advancedQueries$=new ve(null),this.planDetails$=new ve(null),this.signOutPreviousUser$=new ve(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{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(f=>{this.config=f}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=ei(this.afAuth).pipe(no(this.afAuth.currentUser),Ti(),he(([f,I])=>this.domService.onNetworkStatusChange$().pipe(Fe(T=>T),ot(1),de(()=>({previousUser:f,currentUser:I}))))).subscribe(T=>Q(this,[T],function*({previousUser:f,currentUser:I}){if(!I&&f){let N=f?.stsTokenManager?.expirationTime,G=new Date().getTime(),z=N-G;G>N&&(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&f?.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:z,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:z,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"))))}}),f=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",f)}),this.getUser$().pipe(vt(Kt)).subscribe(f=>{let I=Qr(f);this.coreActionsService.triggerAction(Un.USER_UPDATE,I),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:Un.USER_UPDATE,payload:{user:I}})})}catch(f){this.loggingService.catch("Error in AuthService constructor: ",f)}}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 B9),this.configService.initConfig(t),t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||ei(this.afAuth).pipe(ot(1)).subscribe(r=>Q(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ap(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?D(E({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(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)}}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)}}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;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let r=yield ez(()=>window.Velt.identify(e.user,E(E({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}),e.retryConfig||{retryCount:0,retryDelay:0});return r&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(Un.ERROR).pipe(Fe(a=>a.code==="token_expired"),ot(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let s=this.docService?.getDocumentIds()?.map(T=>({id:T.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,p=[],g=this.docService?.getLocation();g&&p.push(g.location);let f=this.docService?.getLocations();f&&Object.values(f).forEach(T=>{p.push(T.location)}),(yield ez(()=>Q(this,null,function*(){try{let T=yield e.generateToken?.();return T?window.Velt.identify(e.user,E(E({},e.options||{}),T&&{authToken:T}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:s,options:c,source:"internal"}),yield this.docService?.setLocations({locations:p,source:"internal",options:{appendLocation:!g}}))}}))),r}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return Q(this,null,function*(){try{if(e){let t=yield bl(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 j0(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}updateUserWithColorAndTextColor(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),r=yield this.getUserFromStorage(t);return!r||Object.keys(r).length===0?(delete t?.color,delete t?.textColor,t):(r?.color&&(t.color=r?.color),r?.textColor&&(t.textColor=r?.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);this.loggingService.debugAuth("updateUserIfRequired currentUser",JSON.parse(JSON.stringify(t))),this.loggingService.debugAuth("updateUserIfRequired user",JSON.parse(JSON.stringify(e)));let r={};if(e.color&&e.color!==t?.color&&(r.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(r.textColor=e.textColor),this.loggingService.debugAuth("updateUserIfRequired fieldsToUpdate",JSON.parse(JSON.stringify(r))),Object.keys(r).length>0&&e.organizationId){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));ad({data:{type:"addUserInfoToOrganization",metadata:{organizationId:e.clientOrganizationId},user:D(E({},r),{userId:e.userId})},getSdkProxy:a,userId:e?.userId??""})}}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,r,a,s){return Q(this,null,function*(){try{if(this.loggingService.logPerf(`[PERF] identify() called at ${performance.now().toFixed(2)}ms`),this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=z0(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield ei(this.afAuth).pipe(ot(1)).toPromise().catch(g=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let g=yield ap(c,!0).catch(T=>null);if(!g)return;let{user:f,firebaseConfig:I}=g.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==f?.groupId||e?.organizationId!==f?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,I)||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");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let T=yield ap(c,!0).catch(J=>null);if(!T)return;let{firebaseConfig:N,user:G,advancedQueries:z}=T.claims;yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(N),this.setAdvancedQueries(z),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a,e),p=!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:s})}}if(p){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:s},!0,e.userSnippylyId,e.userId);let g=Ki(this.functions,Zi({url:Dn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),f=ga(),I=performance.now();this.loggingService.logPerf(`[PERF] validateClient() started at ${I.toFixed(2)}ms`);let T=(yield g({apiKey:this.apiKey,user:e,version:f,authToken:t?.authToken}))?.data;if(this.loggingService.logPerf(`[PERF] validateClient() completed in ${(performance.now()-I).toFixed(2)}ms`),T.error){if(this.analyticsService.trackEvent(K.Events.Core.SDK_VALIDATE_CLIENT_FAILED,D(E({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:T.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},T),{source:s}),!0,e.userSnippylyId,e.userId),T.error&&typeof T.error=="string")if(T.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let N={code:"token_expired",message:"Token expired",error:T?.error,source:T?.source};this.coreActionsService.triggerAction(Un.ERROR,N)}else{let N={code:"too_many_retries",message:"Token expired. Too many retries.",error:T?.error,source:T?.source};this.coreActionsService.triggerAction(Un.ERROR,N),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:s},!0,e.userSnippylyId,e.userId)}else{let N=T;this.coreActionsService.triggerAction(Un.ERROR,N)}throw T}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:s},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),T.firebaseConfig){this.setFirebaseConfig(T.firebaseConfig),yield this.signInWithCustomToken(e,T.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let N=yield ap(this.afAuth.currentUser,!0).catch(J=>null);if(!N)return;let{user:G,advancedQueries:z}=N.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!G?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=ga();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=ga();if(e){let t=e.split("."),r=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),s=parseInt(t[2]||"0");if(r>=4&&a>=5)return r===4&&a===5&&s===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(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(r=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:E(E({},Dn.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 gn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(de(()=>this.getAdvancedQueriesEnabled()),zn(()=>se(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),ei(this.afAuth).pipe(he(e=>e?this.user$.asObservable():se(null)),vt(Kt))}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=E(E({},this.providedUser),e),t){let r=E(E({},t),e);this.updateUserInternally(r)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return nie(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:r,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:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.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,r){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new Bo;a.userSnippylyId=e.uid,a.type="signedIn",r&&(a=E(E({},a),r)),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 r=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0});a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=E(E({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=r?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=r?.initial||this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return 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();try{if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let r=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:Mo.ORGANIZATION,source:Ir.IDENTIFY,organizationId:e.clientOrganizationId}}],a=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.IDENTIFY,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:r}}),yield this.userPermissionService?.onResourceAccessRequired({requests:r,uniqueId:a,userId:e.userId,methodName:Ir.IDENTIFY,fromCache:!1})}}catch(r){this.loggingService.catch("Error in updateUserInternally: ",r)}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)),r=D(E({},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 Ki(this.functions,Zi({url:Dn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:ga(),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(Fe(e=>!!e),de(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}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(he(e=>e?this.userOrganization$.asObservable().pipe(de(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),yield 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 ei(this.afAuth).pipe(ot(1)).toPromise().catch(r=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(t)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.user$.next(null),yield nm(1e3),iie(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return eo(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 Qr(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Rn(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)(ee(Ai),ee(Rt),ee(cm),ee(ts),ee(Le),ee(Io),ee(et),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var dm=class{constructor({apiKey:o,documentId:n,organizationId:e,folderId:t,veltFolderId:r,clientDocumentId:a,clientOrganizationId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.folderId=t,this.veltFolderId=r,this.clientDocumentId=a,this.clientOrganizationId=s,a&&(this.documentId=br(a)),s&&(this.organizationId=Qa(s)),t&&(this.folderId=t,this.veltFolderId=Ui(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 nR=class{constructor({apiKey:o,documentId:n,organizationId:e,clientDocumentId:t,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.veltFolderId=s,t&&(this.documentId=br(t)),r&&(this.organizationId=Qa(r)),a&&(this.folderId=a,this.veltFolderId=Ui(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.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.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var iR=class{};var bn=(()=>{let o=class o{constructor(e,t){this.authService=e,this.loggingService=t,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(dM(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ys=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.commentAnnotationById$=new ve({}),this.fieldsToRemove=[],this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return s(),c({});let f={},I=[...new Set(e.commentAnnotationIds||[])],T=D(E({},e),{commentAnnotationIds:I});Q(this,null,function*(){try{if(I.length>0||e.documentIds?.length||e.folderId){let G=rd(()=>g?.get(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(z=>r?{}:(s(),z&&z.statusCode!==200?(this.loggingService.catch(z?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):z?.data)).catch(z=>{throw s(),z});try{f=(yield G)||{},this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:I});let z={};Object.entries(f).forEach(([J,ce])=>{let ye=this.commentAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ce)&&(z[J]=ce):z[J]=ce}),Object.keys(z).length>0&&this.commentAnnotationById$.next(E(E({},this.commentAnnotationById$.getValue()),z)),c(z)}catch(z){r||p(z),c(f)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",t),{}}})}saveCommentAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let t=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=E(E({},r),e.commentAnnotation);let a=yield rd(()=>t?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(t){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=E({},a);delete s?.[e],this.commentAnnotationById$._value=s;let c=yield rd(()=>r?.delete({commentAnnotationId:e.toString(),metadata:t,event:Oa.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(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}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(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)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var mm=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.reactionAnnotationById$=new ve({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return s(),c({});let f={},I=[...new Set(e.reactionAnnotationIds||[])],T=D(E({},e),{reactionAnnotationIds:I});Q(this,null,function*(){try{if(I.length>0||e.documentIds?.length||e.folderId){let G=rd(()=>g?.get(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(z=>r?{}:(s(),z&&z.statusCode!==200?(this.loggingService.catch(z?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):z?.data)).catch(z=>{throw s(),z});try{f=(yield G)||{},this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:I});let z={};Object.entries(f).forEach(([J,ce])=>{let ye=this.reactionAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ce)&&(z[J]=ce):z[J]=ce}),Object.keys(z).length>0&&this.reactionAnnotationById$.next(E(E({},this.reactionAnnotationById$.getValue()),z)),c(z)}catch(z){r||p(z),c(f)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",t),{}}})}saveReactionAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let t=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=E(E({},r),e);let a={reactionAnnotation:e,event:Oa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield rd(()=>t?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(t){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=E({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let c=yield rd(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:t,event:Oa.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(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)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var rt=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.analyticsService=e,this.authService=t,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=g,this.coreActionsService=f,this.functions=I,this.documentPaths$=new ve(null),this.docContext$=new ve(null),this.documentIds$=new ve([]),this.organizationConfig$=new ve(null),this.firestorePaths$=new ve(null),this.location$=new ve(null),this.excludedLocationIds$=new ve([]),this.organizationMetadata$=new ve(null),this.documentMetadata$=new ve(null),this.locationMetadata$=new ve(null),this.customerMetadata$=new ve(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new ve({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new tt,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,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(jo(this.DEBOUNCE_TIME)).subscribe({next:T=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(T.documentId,T.clientOrganizationId,T.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:T=>{this.loggingService.catch("Error in setDocumentId subscription:",T),this.queueSize--}}),this.databaseService.getDb().pipe(Fe(T=>!!T),ot(1)).subscribe(T=>{T&&(this.db=T)}),this.configService.getApiKey$().subscribe(T=>{if(this.apiKey=T,this.apiKey){if(!this.isCustomDocId){let N=xk(window.location.href);this.currentUrl=N}this.analyticsService.updateDefaultProperties({apiKey:T})}}),this.authService.getUser$().subscribe(T=>Q(this,null,function*(){if(T&&(this.analyticsService.updateDefaultProperties({organizationId:T?.organizationId,clientOrganizationId:T?.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&&T?.organizationId&&this.documentPaths$.value?.organizationId!==T?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(N=>({id:N.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),T?.organizationId&&T?.clientOrganizationId)){let N={organizationId:T?.organizationId,clientOrganizationId:T?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:T?.organizationId,clientOrganizationId:T?.clientOrganizationId}),yield this.updateOrganizationMetadata(N)}})),this.documentPaths$.subscribe(T=>{let N={documentId:T?.documentId,clientDocumentId:T?.clientDocumentId,folderId:T?.folderId,allDocuments:T?.allDocuments,veltFolderId:T?.veltFolderId};T?.organizationId&&(N.organizationId=T.organizationId,N.clientOrganizationId=T.clientOrganizationId),this.analyticsService.updateDefaultProperties(N),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(T=>{this.analyticsService.updateDefaultProperties({clientLocation:T?.location,locationId:T?.locationId})}),this.organizationMetadata$.subscribe(T=>{this.authService.setUserOrganization(T?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Fe(T=>!!T),ot(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(T){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",T)}},T=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",T)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(T){this.loggingService.catch("Error in DocService constructor:",T)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,organizationId:this.documentPaths$.value?.clientOrganizationId}: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.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)}}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=xk(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=xk(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(s){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:r,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(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocument",source:a,payload:{documentId:e,documentMetadata:t,options:r}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:E({organizationId:t?.organizationId},r??{}),source:a})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(e,t={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,s=this.documentIds$.value.map(g=>g.clientDocumentId),c=GH(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(g=>s.includes(g.id))||!gi(c,t)||r!==a}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let r=[];return e.forEach(a=>{let s=a.id,c=`${Rn(s)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r}catch(r){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",r),[]}}setDocuments(s){return Q(this,arguments,function*({documents:e,options:t,source:r="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocuments",source:r,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:r,skipPermissionValidation:a})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(r){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:"setRootDocument",source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},s=this.documentIds$.value.map(c=>c.clientDocumentId);if(!s.includes(e.id)){let c=[...s.map(g=>({id:g})),{id:e.id}],p=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(p)}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()}getProcessedDocContext(){return Xle(this.getDocContext())}filterRelevantDocuments(a){return Q(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:r=!1}){try{let s=this.authService.getUser();return!s||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,s),yield this.handlePermissionProvider(e,t,s),t=yield this.filterDocumentsByPermissions(e,t,s,r),t=t.slice(0,50)),t}catch(s){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",s),t}})}fetchDocumentsFromFolder(e,t,r){return Q(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield ad({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??r?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:r?.userId??""}))?.data?.data?.forEach(c=>{t.find(p=>p.clientDocumentId===c.id)||t.push({documentId:br(c.id),clientDocumentId:c.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,r){try{let a=[];return e.organizationId&&e.organizationId!==r.clientOrganizationId&&a.push({userId:r.userId,resource:{id:e.organizationId,type:Mo.ORGANIZATION,source:Ir.SET_DOCUMENTS,organizationId:e.organizationId}}),e.folderId&&a.push({userId:r.userId,resource:{id:e.folderId,type:Mo.FOLDER,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??""}}),t&&t.forEach(s=>{a.push({userId:r.userId,resource:{id:s.clientDocumentId,type:Mo.DOCUMENT,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??""}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&Jle({input:e?.context}).forEach(c=>{let p=JSON.stringify(c.access);a.push({userId:r.userId,resource:{id:p,type:Mo.CONTEXT,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??"",context:c}})}),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 r=e.data.filter(a=>a.type===Mo.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(r?.length){let a=t.filter(c=>r.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),s=ece({input:a});s?.access&&this.setDocContext(s)}}catch(r){this.loggingService.catch("Error in processAccessibleContexts:",r)}}handlePermissionProvider(e,t,r){return Q(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{let a=this.buildPermissionRequests(e,t,r),s=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.SET_DOCUMENTS,uniqueId:s,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}});let c=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:s,methodName:Ir.SET_DOCUMENTS,fromCache:!1});this.processAccessibleContexts(c,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,r,a=!1){return Q(this,null,function*(){if(a)return t;let s=this.currentValidationToken,c=[...t];return s&&this.validatePermissionsInBackground(e,t,r,s),c})}validatePermissionsInBackground(e,t,r,a){this.userPermissionService?.getUserPermissions({organizationId:e?.organizationId??r?.clientOrganizationId,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let c=[];Object.entries(s?.[r.userId]?.documents??{}).forEach(([p,g])=>{g?.errorCode===Wo.PERMISSION_DENIED&&c.push(p)}),c.length>0&&this.handleDeniedDocumentAccess(c,r,a)}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,r){try{if(this.currentValidationToken!==r)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(Un.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 s=this.documentIds$.value||[],c=s.filter(p=>!e.includes(p.clientDocumentId));c.length!==s.length&&(c.length>0?this.setDocuments({documents:c.map(p=>({id:p.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(Un.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(r){return Q(this,arguments,function*({organizationId:e,user:t}){try{let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield ad({data:{type:"addUserInfoToOrganization",metadata:{organizationId:e},user:t},getSdkProxy:a,userId:t?.userId??""})}catch(a){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",a)}})}setDocumentsImpl(s){return Q(this,arguments,function*({documents:e,options:t,source:r,skipPermissionValidation:a=!1}){try{let c=t?.organizationId??this.documentPaths$.value?.clientOrganizationId;if(!this.shouldSetDocumentsAgain(e,GH(D(E({},t),{organizationId:c})))){r==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let p=on();this.currentValidationToken=p;let g=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(g?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let f=this.authService.getUser();if(!f){this.draftDocuments=e,this.draftOptions=t;return}if(this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1}),this.addUserInfoToOrganization({organizationId:t?.organizationId??f?.clientOrganizationId??"",user:f}),g=yield this.filterRelevantDocuments({options:t,documentIds:g,skipPermissionValidation:a}),this.documentIds$.next(g),g?.length){let I=g[0]?.clientDocumentId;t?.rootDocumentId&&g.find(T=>T.clientDocumentId===t?.rootDocumentId)&&(I=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:I,clientOrganizationId:t?.organizationId,options:t})}return}catch(c){this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocumentId",source:r,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:r})}catch(s){this.loggingService.catch("Error in setDocumentId:",s);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:r}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let s=Date.now(),c=s-this.lastSetDocumentIdCallTime,p=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||c>this.DEBOUNCE_TIME&&p>this.DEBOUNCE_TIME){yield this.setDocumentIdImpl(e,t,r),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:r??void 0});return}catch(s){this.loggingService.catch("Error in debounceSetDocuments:",s)}})}setDocumentIdImpl(e,t,r){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 s=this.currentDocumentId;if(this.apiKey){let c=`${Rn(e)}`,p=r?.folderId,g=r?.folderId?Ui(r?.folderId):void 0,f=r?.locationId,I=r?.allDocuments,T=a?.organizationId?t?Et(t):a?.organizationId:void 0;if(yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(N=>N.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(N=>N.clientDocumentId),organizationId:t??a?.clientOrganizationId??""})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==T){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let N=new j9,G=new iR;N.clientDocumentId=e,G.clientDocumentId=e,N.folderId=p,G.folderId=p,N.locationId=f,G.locationId=f,N.allDocuments=I,G.allDocuments=I,N.veltFolderId=g,G.veltFolderId=g,N.documentId=c,G.documentId=c,T&&(N.organizationId=T,N.clientOrganizationId=t??a?.clientOrganizationId,G.organizationId=T,G.clientOrganizationId=t??a?.clientOrganizationId);let z=`${this.apiKey}`,J=`apiKey/${this.apiKey}`;T&&(z=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${N.organizationId}`,J=`${J}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${N.organizationId}`),G.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,G.document=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,N.presence=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,N.cursor=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,N.comment=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,G.comment=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,N.multiThread=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,G.multiThread=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,N.tag=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,N.area=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,G.area=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AREA}`,N.arrow=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,N.selection=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,N.audioHuddle=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,N.huddle=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,N.recorder=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,G.recorder=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,N.flock=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,N.syncVideoPlayer=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,N.liveState=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,N.liveStateSingleEditorMode=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,N.reaction=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,G.reaction=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,N.crdt=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,G.crdt=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,N.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,N.views=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,G.notificationViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,G.documentViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,G.locationViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,N.notifications=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,N.metadata=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,N.users=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,N.documentIam=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.groupContacts=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,N.globalContacts=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,N.logins=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,N.userFeedback=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,N.userReportBugs=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,N.userContactUs=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,T&&(N.organizationMetadata=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,N.organizationIam=`${z}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.organizationGroups=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,N.organizationNotifications=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(N.organizationNotificationsWithDocumentId=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,N.heartbeatByDocument=`${z}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),N.organizationNotificationsLastNotificationTimestamp=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,N.organizationNotificationsUsers=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,N.heartbeat=`${z}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),G.organizationUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,G.users=`${J}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,G.documentUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,G.notificationDocs=`${J}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,G.notificationUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,!this.documentPaths$.value&&this.loggingService.logPerf(`[PERF] documentPaths$ FIRST SET at ${performance.now().toFixed(2)}ms`),this.documentPaths$.next(N),this.firestorePaths$.next(G),N?.clientOrganizationId&&N?.organizationId&&!(N?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&N?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:N?.organizationId,clientOrganizationId:N?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),s&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:e}}),this.analyticsService.trackEvent(K.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,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(Un.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:"unsetDocumentId",source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocumentId: ",r)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.userPermissionService?.revokeAccessOnDocumentUnset(),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.clientDocumentMetadata=void 0,this.clientDocumentMetadataMap={},this.locations$.next({}),this.documentIds$.next([]),this.coreActionsService.triggerAction(Un.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(r){this.loggingService.catch("Error in unsetDocumentImpl: ",r)}}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(Un.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:"unsetDocuments"}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocuments: ",r)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,r]of this.preDocumentIdChangeFunctions)try{yield r(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(r=>{r&&!r?.errorCode&&this.organizationMetadata$.next(D(E({},this.organizationMetadata$.value),{[t]:r}))}).catch(r=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",r)})}}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,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,s=[],c={organizationId:t?.clientOrganizationId,folderId:a},p=[],g=20;for(let I=0;I<e.length;I+=g)p.push(e.slice(I,I+g));p.forEach(I=>{let T=JSON.parse(JSON.stringify(c));T.documentIds=I.map(N=>N.clientDocumentId),s.push(this.fetchDocuments(T))});let f={};s.length>0&&(yield Promise.all(s).then(I=>{I?.forEach(T=>{T?.forEach(N=>{N?.metadata?.documentId&&(f[N.metadata.documentId]=N.metadata)})}),this.setAllDocumentMetadata(E(E({},this.documentMetadata$.value),f))}).catch(I=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",I)}))}else r?.[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,r=e?.folderId,a=e?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a},p=[],g=20;for(let I=0;I<t.length;I+=g)p.push(t.slice(I,I+g));p.forEach(I=>{let T=JSON.parse(JSON.stringify(c));T.documentIds=I.map(N=>N.clientDocumentId),s.push(this.fetchLocations(T))});let f=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(I=>{I?.forEach(T=>{T?.forEach(N=>{N?.metadata?.documentId&&(f[N.metadata.documentId]=D(E({},f?.[N.metadata.documentId]??{}),{[N.location.id]:N}))})}),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}).catch(I=>{this.loggingService.catch("Error in fetchLocationMetadata: ",I)})}}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(zn(t=>se(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(de(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`${Rn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${Et(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(r){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(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:"setLocation",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:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"setLocations",source:r,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(s){this.loggingService.catch("Error in setLocations: ",s)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(r=>{if(r&&typeof r=="object"){let a=!0;r?.version&&(!r?.version?.id||!r?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${r?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(r)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(r){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(Un.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:"setRootLocation",source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(s=>s.location).filter(s=>String(s.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=D(E(E({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=E(E({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),s=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(f=>f.location.id)].filter(f=>f!==void 0);let p;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(p=a.find(f=>f.id===t?.rootLocationId),!p)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(p){let f=er(p),I=Rn(JSON.stringify(f));f.id&&s.push({locationId:I,location:f}),this.location$.next({locationId:I,location:f})}}else{p||(p=a[0]);let f=er(p),I=Rn(JSON.stringify(f));f.id&&s.push({locationId:I,location:f}),this.location$.next({locationId:I,location:f})}let g=[];return a.slice(t?.appendLocation?0:1).forEach(f=>{if(f.id!==this.location$.value?.location.id){let I=E({},f),T=this.locations$.value;f?.id&&Object.keys(T).forEach(J=>{let ce=T[J];ce.location?.id===f.id&&(I=E(E({},ce.location),f),delete T?.[J])});let N=this.genarateLocationId(I),G={locationId:N,location:I};I.id&&s.push({locationId:N,location:I}),g.push(G);let z=D(E({},T),{[N]:G});this.locations$.next(z)}}),this.updateDocumentLocationMetadata(s),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:"setLocations",payload:{locations:a,options:t}}),this.analyticsService.trackEvent(K.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),g}catch(r){this.loggingService.catch("Error in setLocationImpl: ",r);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(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"addLocation",source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(r){this.loggingService.catch("Error in DocService addLocation:",r);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(Un.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:"removeLocation",payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}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(Un.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:"removeLocations",source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(r){this.loggingService.catch("Error in removeLocations: ",r)}}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(r=>{let a=this.genarateLocationId(r);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==r.id))),this.removeCustomLocation(r)}):(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(r){this.loggingService.catch("Error in removeLocation: ",r)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:"unsetLocationIds",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(r=>{this.getLocation()?.location.id===r&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==r))),this.removeCustomLocationId(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:"removeLocationsSuccess",source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in unsetLocationIds: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(e){return Q(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,r=this.documentPaths$.value;if(this.db&&t&&r?.documentId){if(this.organizationMetadata$.value?.[t])return;let s=new Q9;s.apiKey=this.configService?.getApiKey()??"",s.organizationId=t,s.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:t,documentId:r?.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 r={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield ad({methodName:"createFolder",data:{type:"createFolder",metadata:r},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 r=t.map(a=>Q(this,null,function*(){let s=new U9;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=E(E({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=E(E({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=Mi();let c=e?.folderId,p=e?.veltFolderId;s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let g=!0,f=this.documentMetadata$.value?.[a.documentId];if(c&&p){let I=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));I?.clientDocumentId&&!I?.errorCode?I?.folderId&&(I?.folderId!==c||I?.veltFolderId!==p)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),g=!1):I?.folderId===c?(c&&(s.folderId=c),p&&(s.veltFolderId=p)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),g=!1):(c&&(s.folderId=c),p&&(s.veltFolderId=p))}if(f){let I={};Object.entries(s).forEach(([T,N])=>{I[T]=N}),gi(I,f)&&(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(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(r),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 r=this.getDocumentIds();r.find(a=>a.documentId===t.documentId)||r.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});s?.errorCode&&(s={});let c=[];for(let p of e){let g=new G9;g.locationId=p?.locationId,g.veltLocationId=jH(p?.location?.id??""),g.location=p?.location,g.pageInfo=Mi(),g?.pageInfo?.deviceInfo&&delete g?.pageInfo?.deviceInfo;let f=D(E({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:D(E({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[p?.locationId]:g})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(f)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let I=this.locationMetadata$.value;if(I||(I={}),p?.location?.id){let T=I?.[a.documentId],N=T?.[p?.location?.id??""];I&&(T||(I[a.documentId]={}),N||(I[a.documentId][p?.location?.id??""]={}),I[a.documentId][p?.location?.id??""]=D(E({},N),{location:p?.location})),Object.keys(I||{}).length>0&&this.locationMetadata$.next(I)}}yield Promise.allSettled(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Rn(JSON.stringify(er(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(E({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let r=this.locations$.value;Object.entries(r).forEach(([a,s])=>{s.location.id===e&&(delete r[a],this.locations$.next(E({},r)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==e)))})}catch(r){this.loggingService.catch("Error in DocService removeCustomLocationId:",r)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(t=s.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}]`),r=[];t.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(E({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),se({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let t=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),t){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);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(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}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(de(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),vt(Kt))}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(de(e=>e||{}),vt(Kt))}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={},r=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(r&&a)Object.values(e).forEach(s=>{s?.documentId&&s?.veltFolderId===r&&(t[s.documentId]=s)});else{let s=this.documentIds$.value;if(s?.length)s.forEach(c=>{let p=e?.[c.documentId];p&&(t[c.documentId]=p)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(de(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),vt(Kt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let r=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));r[e]=t,this.documentMetadata$.next(r)}catch(r){this.loggingService.catch("Error in DocService setDocumentMetadata:",r)}}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(de(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(de(e=>e||{}),vt(Kt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(vt(Kt))}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(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=t||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,g=c?.veltFolderId;return E(E({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),g?{veltFolderId:g}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,t){try{let r,a;t?.element?r=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(r=t.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,t),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),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 r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=Ui(e?.folderId);r.push(ht("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(ht("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(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 r=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=Ui(e?.folderId);r.push(ht("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(ht("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(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:r,documents:a,folderId:s}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Qa(r);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let p=[],g=this.documentMetadata$.value??{};for(let f of a)if(f?.documentId){f.organizationId=c,f.clientOrganizationId=r,f.clientDocumentId=f.documentId;let I=br(f.documentId);f.documentId=I,f.apiKey=this.configService.getApiKey()??void 0,(s||this.documentPaths$.value?.folderId)&&(f.folderId=s||this.documentPaths$.value?.folderId,f.veltFolderId=Ui(s||this.documentPaths$.value?.folderId||""));let T=()=>{if(s&&this.documentPaths$.value?.folderId&&s!==this.documentPaths$.value?.folderId)return;let G=g?.[I];G?g[I]=E(E({},G),f):g[I]=f},N=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:I,organizationId:c,field:"metadata"}});if(N?.errorCode&&(N={}),N&&N.apiKey&&N.folderId&&s&&N.folderId!=f.folderId){this.loggingService.catch(`Error in updateDocuments: document ${f.clientDocumentId} already exists with different folderId: ${N.folderId}`);continue}if(N&&N.apiKey&&!N.folderId&&f.folderId){this.loggingService.catch(`Error in updateDocuments: document ${f.clientDocumentId} already exists, move this document to folder with REST API`);continue}T(),f&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:f?.documentId??""})&&p.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(f)),properties:{organizationId:c,documentId:I}}))}yield Promise.all(p),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:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(f=>f.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=s.map(f=>br(f)),p=[],g=this.locationMetadata$.value;g||(g={}),c.forEach(f=>{a.forEach(I=>{let T=this.location$.value;if(I?.id===T?.location?.id&&this.location$.next({locationId:T?.locationId,location:I}),I?.id){delete I?.metadata;let N=jH(I.id),G=g?.[f],z=G?.[I.id];g&&(G||(g[f]={}),z||(g[f][I.id]={}),g[f][I.id]=D(E({},z),{location:I})),I&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:I})),properties:{organizationId:Qa(r),documentId:f,id:N}}))}})}),yield Promise.all(p),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 r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let c=Ui(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ht("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(he(e=>e?this.documentPaths$.pipe(he(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(de(r=>r?.data?.docIamConfig??r?.data),vt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?Ei.RESTRICTED:Ei.PUBLIC:e&&e.documentAccessType?e.documentAccessType:Ei.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),Ei.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(r?.errorCode)return;switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case Ei.PUBLIC:r.features.all.restricted=!1;break;case Ei.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId: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(E(E({},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)(ee(et),ee(Ue),ee(bn),ee(Le),ee(Rt),ee(y),ee(Ys),ee(mm),ee(ts),ee(Io))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Fn=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.authService=t,this.docService=r,this.loggingService=a,this.resolveOrganizationUsers=new ve(!0),this.resolveFolderUsers=new ve(!0),this.resolveDocumentUsers=new ve(!0),this.unresolvedUsers=new ve([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Tn,this.userDataProvider$=new ve(null),this.userById$=new ve({}),this.userByIdCalled$=new ve({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Fe(s=>!!s),he(()=>this.getUnresolvedUsers$().pipe(Fe(s=>s.length>0),jo(300),ot(20),he(s=>{let c=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:c,isCollection:!0,useQuery:!0,firestoreQuery:[_i(ht("user.userId","in",s.slice(0,20)))]}}).pipe(de(p=>p?.data),tn(p=>{if(p&&typeof p=="object"){delete p.undefined,delete p.null;let g=Object.values(p??{});this.setUserByIds(g.map(I=>I.user));let f=s.filter(I=>!g.some(T=>T.user.userId===I));f.length!==s.length&&this.setUnresolvedUsers(f)}})):se([])})))).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)}}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(r){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",r),!1}}resolveUsers(c){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:r,organizationId:a,skipUserCheck:s=!1}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let p=!1;if(r&&(p=this.isResolverForFeatureDisabled(r)),p)return{};{let g={},f=[],I={};if(e?.forEach(T=>{let N=this.getUserById(T);N?g[T]=N:this.userByIdCalled$.getValue()[T]?t&&f.push(T):(f.push(T),this.userByIdCalled$.next(D(E({},this.userByIdCalled$.getValue()),{[T]:!0})))}),f.length>0){let T={};try{let N,G=new Promise((z,J)=>{N=setTimeout(()=>{J(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});T=yield Promise.race([this.getUsersFromDB({userIds:f,organizationId:a,skipUserCheck:s}).finally(()=>{clearTimeout(N)}),G]),this.analyticsService.trackEvent(K.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:f})}catch(N){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",N,{userIds:f})}finally{f?.forEach(N=>{if(!T[N]){let G=new Set([...this.getUnresolvedUsers(),N]);this.unresolvedUsers.next(Array.from(G)),T[N]={userId:N,name:`User ${N}`}}})}Object.entries(T).forEach(([N,G])=>{G&&(g[N]=T?.[N],I[N]=T?.[N])})}return Object.keys(I).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(I)),this.userById$.next(E(E({},this.userById$.getValue()),I))),g}}catch(p){return this.loggingService.catch("Error in UsersService resolveUsers:",p),{}}})}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:r=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let s=this.userDataProvider$.getValue();if(s)return s.get(e);if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:r}))??[],p={};return c.forEach(g=>{g.forEach(f=>{f?.user?.userId&&(p[f.user.userId]=f.user)})}),p}catch(s){return this.loggingService.catch("Error in UsersService getUsersFromDB:",s),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){try{if(!e?.length)return[];let s=[];for(let g=0;g<e.length;g+=30)s.push(e.slice(g,g+30));let c=s.map((g,f)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ht("user.userId","in",g)],skipUserCheck:r}}))||[]}catch(I){return this.loggingService.catch(`Error in batch ${f+1}:`,I),[]}}));return yield Promise.all(c)}catch(s){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",s),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:r}){try{if(!e?.length||!r?.length)return[];let s=[];for(let G=0;G<e.length;G+=30)s.push(e.slice(G,G+30));let c=[];for(let G=0;G<r.length;G+=30)c.push(r.slice(G,G+30));let p=[],g=0,f=(G,z)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_i(ht("userId","in",G),ht("veltResourceId","in",z))]}}))??[])||[]}catch(J){return this.loggingService.catch(`Error in batch ${g+1}:`,J),[]}});for(let G of s)for(let z of c)p.push(f(G,z)),g++;return(yield Promise.all(p)).flat().filter((G,z,J)=>z===J.findIndex(ce=>ce.userId===G.userId&&ce.resourceId===G.resourceId))}catch(s){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",s),[]}})}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(vt(Kt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}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(r=>{t[r.userId]=E(E({},t?.[r.userId]??{}),r)}),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;"),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)}}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)(ee(et),ee(Ue),ee(rt),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var hpe=(()=>{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 r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var fpe=(()=>{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 r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var qg=class{static getFirestoreProdDbName(o,n){return n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(n){return nt.error("Error in isTestingDb:",n),!1}}};var Yg=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new ve(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let t=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield rd(()=>t?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(t){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",t);return}})}deleteAttachment(r){return Q(this,arguments,function*({attachmentId:e,metadata:t}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield rd(()=>a?.delete({attachmentId:e,metadata:t,event:Oa.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",t)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Kg=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.coreActionsService=g,this.notificationActionTypeMap={[$t.NEWLY_ADDED]:Oa.COMMENT_ANNOTATION_ADD,[$t.ADDED]:Oa.COMMENT_ADD,[$t.UPDATED]:Oa.COMMENT_UPDATE,[$t.DELETED]:Oa.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 r of e){if(r?.from?.userId&&t.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&t.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&t.add(s?.userId)}if(r?.assignedTo?.userId&&t.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.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 s=this.usersService.getUserById(a?.userId);if(s)return E(E({},a),s)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(t?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(id(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(s=new RegExp(id(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(s,a.text),t.commentHtml=t.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}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?.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),r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(s=>{let c=t?.comments?.[s?.commentId];if(c){s.commentHtml=c?.commentHtml,s.commentText=c?.commentText;let p=c?.attachments;r&&p&&s.attachments?.forEach(g=>{let f=g?.attachmentId;p?.[f]&&(g.name=p?.[f]?.name,g.url=p?.[f]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(s=>{t?.[s]&&(e[s]=t[s])})),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 r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=t?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return r?!gi(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!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 r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new dd;if(Object.assign(a,e),a.isCommentResolverUsed=t,r){let s=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));a.attachments=s}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}stripCommentAnnotationData({data:e,actionType:t,commentId:r}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),c;t&&(c=this.notificationActionTypeMap?.[t]);let p={},g=null,f=!1;if(e&&e.annotationId){let T=e.annotationId;p[T]=E(E(E(E({annotationId:T,metadata:Y0(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(G=>{e?.[G]&&(p[T][G]=e[G],delete e[G])}),e.comments?.forEach(G=>{if(G.commentId){let z;a&&(z={},G.attachments?.forEach(J=>{z[J.attachmentId]={attachmentId:J.attachmentId,name:J.name,url:J.url}})),p[T].comments[G.commentId]=E(E(E(E(E(E({commentId:G.commentId},G?.commentHtml&&{commentHtml:G?.commentHtml}),G?.commentText&&{commentText:G?.commentText}),z&&{attachments:z}),G?.from&&{from:G?.from}),G?.to&&{to:G?.to}),G?.taggedUserContacts&&{taggedUserContacts:G?.taggedUserContacts})}}),f=this.isCommentsDataChanged(p[T],T);let N=new Go;Object.assign(N,e),N.comments=e.comments?.map(G=>this.stripCommentsFromAnnotationData({comment:G}))||[],g=N}let I=g?.comments?.find(T=>T.commentId===r);return I?.isDraft&&(c=g?.comments?.length&&g?.comments?.length>0?Oa.COMMENT_ADD:Oa.COMMENT_ANNOTATION_ADD),{strippedData:f&&(t||I?.isDraft)?p:null,originalData:g,eventType:c}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?.userId?D(E({},r),{contact:{userId:r.contact.userId}}):r));let t=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];t.forEach(r=>{if(r?.text&&r?.contact?.userId){let a=new RegExp(id(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),t.forEach(r=>{r?.text&&r?.contact?.userId&&(r.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 r=Object.values(e?.annotationData?.subscribedUsers||{}).map(s=>s.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&r.length){let s=e?.metadata?.clientDocumentId,c=[];r.forEach(f=>{if(c.push({userId:f,resource:{id:s,type:Mo.DOCUMENT,source:Ir.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??""}}),e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()){let I=JSON.stringify(e?.annotationData?.context?.access);c.push({userId:f,resource:{id:I,type:Mo.CONTEXT,source:Ir.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:e?.annotationData?.context?.access}}})}});let p=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.SET_NOTIFICATIONS,uniqueId:p,timestamp:new Date().getTime(),source:"internal",payload:{requests:c}});let g=yield this.userPermissionService?.onResourceAccessRequired({requests:c,uniqueId:p,methodName:Ir.SET_NOTIFICATIONS});g?.success&&g?.data?.length&&g.data.forEach(f=>{f.hasAccess||a.push(f.userId)})}return a}catch(r){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",r),[]}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let p=yk(this.authService.getFirebaseConfig()?.firebaseOptions),g=Ki(this.functions,Zi({url:Dn.cloudFunction?.[p]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let G=r?.targetAnnotationData?.commentId;if(G){let z=e?.comments?.find(J=>J?.commentId===G);z&&(r.targetAnnotationData=z)}try{let z=this.stripCommentAnnotationData({data:r.annotationData,actionType:r?.actionType??$t.NEWLY_ADDED});z?.originalData&&(r.annotationData=this.formatCommentData(z.originalData)),r?.targetAnnotationData&&(r.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:r.targetAnnotationData})))}catch(z){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",z)}}let f=qg.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),I=yield this.getDeniedForYouUsers({extraData:r}),T={path:t??"",data:e??{},dbId:f??"",notificationData:r||void 0,notificationURL:Dn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:ga(),deniedForYouUsers:I,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),metadata:s},N=yield bl(T,this.authService.getUser()?.userId??"");yield g({veltData:N})}catch(p){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",p)}})}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn),ee(Ue),ee(Io),ee(Rt),ee(Ys),ee(Yg),ee(ts))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vpe=(()=>{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 r of e)r?.user?.userId&&t.add(r?.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 r=t;e?.user&&typeof e.user=="object"&&(r=E(E({},r),e.user)),e=D(E({},e),{user:r})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Cpe=(()=>{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 r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var aR=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=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 r of e)r?.from?.userId&&t.add(r?.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),r=yield this.usersService.resolveUsers({userIds:t});for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var sR=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}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 r of e)r?.updatedBy?.userId&&t.add(r?.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}});return t.length?(yield this.usersService.resolveUsers({userIds:t}),this.mergeSingleEditorLiveStateDataWithUser(e)):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 r=this.usersService.getUserById(t?.updatedBy?.userId);r&&(t.updatedBy=r)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Spe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var wC=(()=>{let o=class o{constructor(e,t,r){this.authService=e,this.loggingService=t,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId),r?.transcription?.from?.userId&&t.add(r?.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?D(E({},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(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield bl(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var lR=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let r of e){let{notification:a}=r;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 s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)t.add(c)}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),r=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[r]?.commentText,s=t?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(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 r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=t?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let r=this.usersService.getUserById(t?.actionUser?.userId);r&&(t.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(t.displayHeadlineMessageTemplateData.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(t.displayHeadlineMessageTemplateData.recipientUser=r)}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(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&t.push(r.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 r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield bl(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(t){return new(t||o)(ee(Kg),ee(wC),ee(y),ee(Fn),ee(Ue),ee(Ys))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ipe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Epe=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.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:r}){try{let s=yk(this.authService.getFirebaseConfig()?.firebaseOptions),c=Ki(this.functions,Zi({url:Dn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),p=qg.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=this.authService.getUser()?.userId??"",f={path:t??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:ga()},I=yield bl(f,g);yield c({veltData:I})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}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 r=this.usersService.getUserById(t?.from?.userId);r&&(t.from=r)}}}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 r=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return r?!gi(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let t={};if(e&&e.annotationId){let r=e.annotationId;if(t[r]=E({annotationId:r,metadata:Y0(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[r],r))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)(ee(y),ee(Fn),ee(Ue),ee(Io),ee(Rt),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var xpe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let r of e)r?.user?.userId&&t.add(r.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Tpe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r.from.userId),r?.to?.length)for(let a of r.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 r=this.usersService.getUserById(t?.userId);r&&(t=r)}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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pm=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I,T,N,G,z,J,ce,ye,Oe,$e){this.areaUtilsService=e,this.arrowUtilsService=t,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=g,this.multiThreadUtilsService=f,this.notificationUtilsService=I,this.presenceUtilsService=T,this.reactionUtilsService=N,this.recorderUtilsService=G,this.selectionUtilsService=z,this.tagUtilsService=J,this.usersService=ce,this.docService=ye,this.commentAnnotationsResolverService=Oe,this.reactionAnnotationsResolverService=$e}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",r),null}}getFirestorePath({feature:e,properties:t,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=t;c||(c=r?.organizationId);let g=new nR({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});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"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"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"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"allDocNotifications":return t?.documentId&&g?.docNotification?`${g?.docNotification}`: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(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"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:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=t;p||(p=r?.organizationId);let g=new dm({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});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!s&&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!s&&t?.documentId&&t?.id&&g?.comment?`${g?.comment}${t?.id}`:void 0;case"allMultiThreads":return!s&&t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return!s&&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"multiThread":return!s&&t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&t?.id&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!s&&t?.documentId&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocuments":return!s&&g?.docs&&t?.documentId?`${g?.docs}/${t?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&t?.documentId&&g?.area?`${g?.area}`:void 0;case"area":return!s&&t?.id&&g?.area?`${g?.area}${t?.id}`:void 0;case"folder":return!s&&t?.folderId&&g?.folder?`${g?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!s&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!s&&t?.documentId&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!s&&t?.documentId&&g?.documentIam?`${g?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&g?.organizationIam?`${g?.organizationIam}users/`:void 0;case"reaction":return!s&&t?.id&&g?.reaction?`${g?.reaction}${t?.id}`:void 0;case"allReactions":return!s&&t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return!s&&t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}${t?.id}`:void 0;case"allRecorders":return!s&&t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"organizationMetadata":return!s&&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!s&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentIam":return!s&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocumentViews":return!s&&t?.documentId&&g?.views?`${g?.views}documentViews/`:void 0;case"documentViews":return!s&&t?.documentId&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!s&&t?.documentId&&g?.views?`${g?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&t?.id&&t?.user&&g?.views?`${g?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!s&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!s&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!s&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/location`:void 0;case"location":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!s&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!s&&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(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(c){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}):this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let g=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...g],p=p.filter(f=>!this.commentAnnotationsResolverService.getCommentAnnotationById(f))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let g=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...g],p=p.filter(f=>!this.commentAnnotationsResolverService.getCommentAnnotationById(f))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return t}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),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((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature: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((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data: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((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):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((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):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((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):t;default:return t}return t}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(de(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(de(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(de(()=>{let r=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(de(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,r),se(e)}}handleDataStripping({feature:e,data:t,actionType:r,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:r,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);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:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return s?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,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:t}};case"documentUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"documentDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"documentMetadataViews":return s?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return s?t:{metadata:t};case"locationUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"locationDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"locationViews":return s?t:{location:t};case"docNotificationViews":return s?t:{views:t.views};case"userNotificationViews":return s?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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(s){return Q(this,arguments,function*({feature:e,data:t,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(r??{}).includes(t.doc.id);if(r?.[t.doc.id]){let a=t.doc.data(),s=r?.[t.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){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)?D(E({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return Q(this,arguments,function*({feature:e,data:t,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let f={comment:"allComments",reaction:"allReactions"}[e];if(!f)return null;let I=t?.metadata?.documentId,T=t?.metadata?.veltFolderId;return Object.keys(r).filter(N=>N.includes(f)&&(!I||N.includes(I)||T&&N.includes(T))).forEach(N=>{let G=r[N]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[N]?.subject&&r[N].subject.next({data:G?.data,operation:c})):r[N]?.subject?.next({data:D(E({},G?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(g){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",g),null}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s})}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",p),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}rtdbDefaultTransactionCallback(e,t){try{let r=E({},e||{});return Object.entries(t).forEach(([a,s])=>{s==null?delete r[a]:r[a]=s}),r}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",r),e}}};o.\u0275fac=function(t){return new(t||o)(ee(hpe),ee(fpe),ee(Kg),ee(vpe),ee(Cpe),ee(aR),ee(sR),ee(y),ee(Spe),ee(lR),ee(Ipe),ee(Epe),ee(wC),ee(xpe),ee(Tpe),ee(Fn),ee(rt),ee(Ys),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Dpe=(()=>{let o=class o{constructor(e,t,r){this.configService=e,this.authService=t,this.loggingService=r,this.firestore$=new ve(null);try{gn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Fe(([a,s])=>!!a&&!!s),ot(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(A9(qg.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||A9("DocumentIdDb");if(e){let t=wI(e,"generateDocumentId");return yC(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(ee(Rt),ee(Ue),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.authService=e,this.commonDbUtilsService=t,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=g,this.commentAnnotationsResolverService=f,this.reactionAnnotationsResolverService=I,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(T=>{if(T){this.db=T;let N=Pi(T,".info/serverTimeOffset");this.offsetListener=bg(N,G=>{let z=G.val();this.offset=z})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(T=>{T&&(this.firestore=T)}))}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 r=Pi(this.db,e);return _l(r).update(t)}return Promise.resolve()}catch(r){return this.loggingService.catch("Error in setupOnDisconnect:",r),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){gn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([t,r])=>!!t),ot(1),tn(([t,r])=>{e({db:t,firestore:r})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,r,a,s,c){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(f=>Q(this,[f],function*({db:p,firestore:g}){let I;t?.skipFirestore||(I=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let T=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let N,G;try{T&&(N=Pi(p,`${T}`))}catch{this.loggingService.catch("Error in dbRef")}try{I?.includes("/organizations")&&g&&I&&(G=yC(g,`${I}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield r({dbRef:N,firestoreRef:G,data:a,firestorePath:I}),c&&c({firestoreAvailable:!!g})}catch(N){this.loggingService.catch(`Error in ${e} operation: `,N),s&&s(N)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){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.performDatabaseOperation(e,r,g=>Q(this,null,function*(){if(g.dbRef){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Lh(g.dbRef,()=>JSON.parse(JSON.stringify(f))):yield m0(g.dbRef,JSON.parse(JSON.stringify(f)))}try{if(g.firestoreRef&&g.data&&!r?.skipFirestore){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset()});typeof f=="object"&&(f=JSON.parse(JSON.stringify(f)));let{strippedData:I,originalData:T,eventType:N}=this.commonDbUtilsService.handleDataStripping({feature:e,data:f,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??r?.targetCommentId});if(e==="comment"){let G=null;I&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:I,eventType:N,commentId:c?.targetAnnotationData?.commentId})),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:T,firestorePath:g.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let G=null;I&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(I)),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:T,firestorePath:g.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield Qme(this.firestore,G=>Q(this,null,function*(){G.set(g.firestoreRef,f)}))):yield wW(g.firestoreRef,f)}}catch(f){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,f)}}),t,s,a))}catch(g){this.loggingService.catch(`Error in setData for ${e}`,g)}})}updateData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){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.performDatabaseOperation(e,r,g=>Q(this,null,function*(){if(g.dbRef&&!r?.skipRtdb){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Lh(g.dbRef,I=>{let T;return r?.rtdbTransactionCallback?T=r.rtdbTransactionCallback(I,f):T=this.commonDbUtilsService.rtdbDefaultTransactionCallback(I,f),JSON.parse(JSON.stringify(T))}):yield fM(g.dbRef,JSON.parse(JSON.stringify(f)))}try{if(g.firestoreRef&&g.data&&!r?.skipFirestore){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset()});typeof f=="object"&&(f=JSON.parse(JSON.stringify(f)));let{strippedData:I,originalData:T,eventType:N}=this.commonDbUtilsService.handleDataStripping({feature:e,data:f,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(e==="comment"){let G=null;I&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:I,eventType:N,commentId:c?.targetAnnotationData?.commentId})),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:T,firestorePath:g.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let G=null;I&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(I)),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:T,firestorePath:g.firestorePath??""}))}else yield wW(g.firestoreRef,f,{merge:!0})}}catch(f){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,f)}}),t,s,a))}catch(g){this.loggingService.catch(`Error in updateData for ${e}`,g)}})}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.performDatabaseOperation(e,t,c=>Q(this,null,function*(){c.dbRef&&(yield hM(c.dbRef));try{if(c.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield qme(c.firestoreRef)}catch(p){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=on()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),on()||"noDocumentId"}}queryData(r){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 r=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=wI(this.firestore,r);t?.useCollectionGroup&&(a=xW(this.firestore,r));let s=t?.firestoreQuery??[],c=DW(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let p=yield Kme(c).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,g),null));return p?p.data().count:0}catch(p){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,p),0}else try{let p=yield Xme(c).catch(f=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,f),null));if(!p)return[];let g=p.docs.map(f=>f.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:g})}catch(f){return this.loggingService.catch(`Error in modifyData for ${e}`,f),g}}catch(p){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,p),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Pi(this.db,r),s=t?.rtdbQuery??[],c=Jj(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let p=yield Xj(c).catch(f=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,f),null));if(!p)return[];let g=p.val();return g?t?.skipObjectValues?g:Object.values(g??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){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 s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield Zme(yC(this.firestore,s)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return t?.field?p?.[t.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield Xj(Pi(this.db,s)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return t?.field?p?.[t.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let r=this.shouldUseFirestore();t?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(t)}`;return gn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Fe(s=>!!s))]).pipe(Fe(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),he(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let f=this.handleFirestoreListener(e,t,c).subscribe(I=>{this.observablesCache[a]?.subject?.next(I)},I=>this.observablesCache[a]?.subject?.error(I));this.firestoreSubscriptions[a]=f}return new Ut(g=>{let f=this.observablesCache[a]?.subject?.subscribe(I=>g.next(I),I=>g.error(I),()=>g.complete());return this.observablesCache[a].count+=1,()=>{f?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let f=this.handleRealtimeDbListener(e,t,s).subscribe(I=>{this.observablesCache[a]?.subject?.next(I)},I=>this.observablesCache[a]?.subject?.error(I));this.rtdbSubscriptions[a]=f}return new Ut(g=>{let f=this.observablesCache[a]?.subject?.subscribe(I=>g.next(I),I=>g.error(I),()=>g.complete());return this.observablesCache[a].count+=1,()=>{f?.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 se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Lu(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,r){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()}),s=`${e}-${JSON.stringify(t)}`;return a?new Ut(c=>{let p=t.isCollection?this.setupCollectionListener(r,a,e,c,t):this.setupDocumentListener(r,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(he(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),he(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):se(c)),he(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):se(c)),vt(Kt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,t,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=wI(e,t);if(s?.useCollectionGroup&&(p=xW(e,t)),s?.useQuery&&s?.firestoreQuery){let I=s?.firestoreQuery??[];p=DW(p,...I)}let g=!0,f=[];return r==="allComments"&&this.loggingService.logPerf(`[PERF] allComments listener started at ${performance.now().toFixed(2)}ms`),TW(p,I=>{try{let T=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),N=null,G=!1;I?.docChanges()?.length?I.docChanges().forEach(z=>{["allComments","allReactions"].includes(r)&&!g&&z.type!=="removed"&&f.push(z.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:z,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(T,this.handleCollectionChange(z,T)),z.type==="removed"&&(N||(N={type:z.type,ids:[]}),N.ids.push(z.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&f?.length&&(this.commonDbUtilsService.resolveAnnotations({data:f,feature:r}),f=[]),r==="allComments"&&g&&Object.keys(T).length>0&&this.loggingService.logPerf(`[PERF] allComments first snapshot received at ${performance.now().toFixed(2)}ms, entries count: ${Object.keys(T).length}`),this.commonDbUtilsService.modifyAndSetData({feature:r,data:T,subscriber:a,operation:N})),g=!1}catch(T){this.handleListenerError(T,r,a)}},I=>this.handleListenerError(I,r,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,r,a,s){let c=yC(e,t);return TW(c,p=>{try{let g=p.data()||{};s?.field&&(g=g?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:g,subscriber:a,operation:null})}catch(g){this.handleListenerError(g,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,t,r){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,r){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}`),se({});let s=Pi(r,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];s=Jj(s,...c)}return this.objectValFromChildEvents(s,e).pipe(zn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),se({}))),de(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((g,[f,I])=>(g[f]=this.commonDbUtilsService.addMetadata(I,t),g),{}):this.commonDbUtilsService.addMetadata(c,t))),he(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),he(c=>this.usersService.getUserById$().pipe(de(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}objectValFromChildEvents(e,t){return new Ut(r=>{let a={},s=!1,c=null,p=z=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,z),r.error(z)}catch{}},g=z=>{try{if(!gi(z,c)){let J=JSON.parse(JSON.stringify(z));c=J,r.next(J)}}catch{}},f=z=>{try{z.key&&(a[z.key]=z.val(),s&&g(E({},a)))}catch{}},I=z=>{try{z.key&&(a[z.key]=z.val(),s&&g(E({},a)))}catch{}},T=z=>{try{z.key&&(delete a[z.key],s&&g(E({},a)))}catch{}},N=z=>{try{if(!s){let J=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=J,r.next(J),s=!0}}catch{}};lre(e,f,p),cre(e,I,p),dre(e,T,p);let G=bg(e,N,p,{onlyOnce:!0});return()=>{try{G&&typeof G=="function"&&G(),uM(e,"child_added",f),uM(e,"child_changed",I),uM(e,"child_removed",T)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(pm),ee(y),ee(Dpe),ee(bn),ee(Rt),ee(rt),ee(Fn),ee(Ys),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var yi=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.analyticsService=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=g,this.db=hs(),this.internalUserContacts$=new ve([]),this.userGlobalContact$=new ve(!1),this.userGroupContact$=new ve(null),this.users$=new ve([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new ve({}),this.userOrganizationContacts$=new ve([]),this.userFolderContacts$=new ve([]),this.userDocumentContacts$=new ve([]),this.userOrganizationGroups$=new ve([]),this.onContactSelectedSubject$=new tt,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([zi.ALL]),this.customUserContacts$=new ve(null),this.customUserContactsConfig$=new ve({merge:!1}),this.currentOrganizationUserIAM$=new ve(null),this.userContacts$=new ve([]),this.userSnippylyIdContacts$=new ve(null),this.usersByOrganizationId$=new ve({}),this.temporaryUserIds$=new ve([]),this.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(he(f=>this.docService.getDocumentPaths$().pipe(tn(I=>{this.documentPaths=I}),de(()=>f)))).subscribe(f=>Q(this,null,function*(){if(this.user=f,f&&this.documentPaths)if(!f?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(f),this.setLoggedInUser(f),yield this.moveGlobalContactUserFromEmailToUserIdPath(f),this.updateUserInGlobalContactsIfAvailable(f),f?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(f?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let I=this.userPermissionService?.getCurrentUserPermissions(),T=this.documentPaths.folderId,N=!0;T&&I?.[f?.userId]?.folders?.[T]?.errorCode===Wo.PERMISSION_DENIED&&(N=!1),this.getOrganizationContactsFromDb$(),N&&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}),f=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",f)}),this.databaseService.getDb().pipe(Fe(f=>!!f),ot(1)).subscribe(f=>{f&&(this.db=f)},f=>{this.loggingService.catch("Error in ContactService constructor getDb: ",f)}),this.getOrganizationGroups$().subscribe(f=>{this.authService.setOrganizationUserGroups(f)}),gn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([f,I,T])=>{I?T?.merge?this.userContacts$.next([...f||[],...I||[]]):this.userContacts$.next(I||[]):this.userContacts$.next(f||[])}),this.getUserContacts$().subscribe(f=>{try{f?.forEach(I=>{let T=I?.userSnippylyId||z0(this.configService.getApiKey(),I.userId);T&&this.userSnippylyIdContacts$.next(D(E({},this.userSnippylyIdContacts$.value),{[T]:I}))})}catch{}})}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=[]}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:Et(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:Et(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:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(D(E({},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:Et(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Et(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(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:Et(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{if(!this.userPermissionService?.getIsContextEnabled())return;let t=this.getUserAccessFields();e.forEach(r=>{t[r.user.userId]=r.accessFields||[]}),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 r=new Bo;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}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:Et(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(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 r,a=t?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Et(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}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(r=>Q(this,null,function*(){let a=t[r];a?.email&&a?.userId&&Et(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Et(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(ot(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===Ei.PUBLIC)r=!0;else if(a===Ei.RESTRICTED){let s=Et(this.user?.userId);if(t?.users?.[s]&&(r=!0),this.user?.email){let c=Et(this.user?.email);t?.users?.[c]&&(r=!0)}}if(r){let s=new Sp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,t){try{let r=t?.filter(a=>a?.visibility==="group");r?.length&&r.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:Et(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:Et(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}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(r=>{r?.userId?(!r?.email||!t[r.email])&&(t[r.userId]=r):r?.email&&(!r?.userId||!t[r.userId])&&(t[r.email]=r)}),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:r,veltFolderId:a}=e||{};return t&&r?gn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(de(([s,c,p,g,f,I,T,N])=>{let G={},z=!1;I&&!I?.merge&&(z=!0);let J=Be=>T.some(be=>Be.includes(be)),ce=J([zi.ALL,zi.ORGANIZATION])?Object.keys(s?.[t]||{}):[],ye=a?J([zi.ALL,zi.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],Oe=J([zi.ALL,zi.DOCUMENT])?Object.keys(p?.[t]?.[r]||{}):[];if([...ce,...ye||[],...Oe,...N].forEach(Be=>{let be=g?.[Be];be&&(G[Be]=be)}),f){let{merge:Be,options:be}=I||{},{organizationId:Se,documentId:Ae,folderId:Ce}=be||{},fe=Ce?Ui(Ce):void 0;(!Se||Se===t)&&(!Ae||Ae===r)&&(!fe||fe===a)&&(Be||(G={}),f.forEach(we=>{we?.userId&&(G[we.userId]=we)}))}return Object.values(G??{})})):this.userContacts$.asObservable().pipe(de(s=>s))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),se([])}}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(Fe(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(Fe(t=>!!t),tn(t=>{this.documentPaths=t}),de(()=>e))),he(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(de(r=>r?.data),tn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(de(r=>r?.data),tn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Et(e?.userId)}}).pipe(de(r=>r?.data),tn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),No(...t).pipe(fo(this.authService.getUser$().pipe(Fe(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(vt(Kt))}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(he(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(de(t=>t?.data),tn(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],se()):se():se())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(he(e=>e?.organizationId?this.userById$.pipe(de(t=>{let r={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(de(t=>{let r={};return t.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(de(t=>t.find(r=>r.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(de(t=>t.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Fe(t=>!!t),de(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let r=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ht("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(r?.length){let a=yield this.usersService.resolveUsers({userIds:r.map(s=>s?.userId)});if(a){let s={};Object.entries(a).forEach(([p,g])=>{s[p]=g}),this.userById$.next(E(E({},this.userById$.value),s));let c=new Set([...this.temporaryUserIds$.value,...Object.keys(s)]);this.temporaryUserIds$.next(Array.from(c))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>this.usersService.getResolveOrganizationUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),t?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0,useQuery:!0,firestoreQuery:[_i(R9(ht("organizationIds","array-contains-any",[r]),ht("viewerOrganizationIds","array-contains-any",[r]))),Xi("id")]}}).pipe(de(a=>a?.data),de(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserAccessFields(s),this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):se():se()}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>this.usersService.getResolveFolderUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return se();if(!this.commonDbService.shouldUseFirestore())return se();if(!this.documentPaths?.veltFolderId)return se();let a=se([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[_i(R9(ht("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ht("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),Xi("id")]}}).pipe(de(s=>s?.data)),a.pipe(de(s=>{if(s){typeof s=="object"&&(s?.undefined&&delete s.undefined,s?.null&&delete s.null);let c=Object.values(s??{});this.setUserAccessFields(c),this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(Fe(r=>!!r),tn(r=>{this.documentPaths=r}),de(()=>t))),he(t=>this.usersService.getResolveDocumentUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(he(r=>{let a=r?.length>0?r.map(g=>g.documentId):[this.documentPaths?.documentId??""];if(a.some(g=>!g)||!this.documentPaths)return se();let s=se([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let p=[];for(let g=0;g<a.length;g+=U.LISTENER_BATCH_SIZE)p.push(a.slice(g,g+U.LISTENER_BATCH_SIZE));return s=gn(p.map(g=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:D(E({},c),{firestoreQuery:[_i(R9(ht("documentIds","array-contains-any",g),ht("viewerDocumentIds","array-contains-any",g))),Xi("id")]})}).pipe(xr()))).pipe(de(g=>Xr(g)?.data)),s.pipe(de(g=>{if(g){typeof g=="object"&&(g?.undefined&&delete g.undefined,g?.null&&delete g.null);let f=Object.values(g??{});this.setUserAccessFields(f),this.setUserDocumentContacts(f)}else this.setUserDocumentContacts([])}))})):se():se())),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),this.usersService.setUserByIds(a),t){let s={};s[t]={};let c={};e.forEach(p=>{s[t][p.user.userId]=p,c[p.user.userId]=p.user}),this.userById$.next(E(E({},this.userById$.value),c)),this.usersByOrganizationId$.next(D(E({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{let t=e?.map(s=>s?.user);this.userFolderContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.folderIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(E(E({},this.userById$.value),a)),this.usersByOrganizationIdAndFolderId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",t)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{let t=e?.map(s=>s?.user);this.userDocumentContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.documentIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(E(E({},this.userById$.value),a)),this.usersByOrganizationIdAndDocumentId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",t)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(zi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let t=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(t)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>{if(this.setUserOrganizationGroups([]),!t)return se();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(de(a=>a?.data),de(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(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),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case Ei.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:r,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(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.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:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.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(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=D(E({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(he(e=>e?gn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(de(([t,r,a,s,c])=>{let p={};p.organizationUsers=t?.map(f=>this.convertToClientUser(f)),p.folderUsers=r?.map(f=>this.convertToClientUser(f)),p.documentUsers=a?.map(f=>this.convertToClientUser(f)),p.updatedContactList=c?.map(f=>this.convertToClientUser(f));let g=[];return s?.forEach(f=>{let I=this.convertToClientUserGroup(f,p.organizationUsers||[]);I&&g.push(I)}),p.userGroups=g,p}),vt(Kt)):se(null)),zn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,t){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(s=>{if(s?.userId){let c=Et(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(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)(ee(et),ee(Ue),ee(Rt),ee(bn),ee(rt),ee(y),ee(pn),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var wpe=i=>{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 jI.sanitize(i,o)}catch(o){return nt.catch("Error in File utils sanitizeSvg: ",o),""}},Ope=i=>{try{return i.name.split(".").slice(0,-1).join(".")}catch(o){nt.catch("Error in File utils getFileName: ",o);return}},UW=i=>{try{return/(?:\.([^.]+))?$/.exec(i?.name)[1]}catch(o){nt.catch("Error in File utils getFileExtension: ",o);return}},Ape=(i,o)=>{try{let n=i.slice(0,-1,i.type);return new File([n],o+"."+UW(i),{type:i.type})}catch(n){nt.catch("Error in File utils updateFile: ",n);return}},Ppe=i=>new Promise((o,n)=>{let e=new FileReader;e.readAsDataURL(i),e.onload=()=>{o(e.result)},e.onerror=t=>{n(t)}}),jW={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 Zg=(()=>{let o=class o{constructor(e,t,r,a){this.authService=e,this.configService=t,this.loggingService=r,this.attachmentResolverService=a,this.storage=bb();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=bb(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:t}){try{let r=new SC;r.name=t.name;let a=Ape(t,`${r.attachmentId}_${Ope(t)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=t.size,r.type=UW(t),r?.type&&(r.mimeType=jW[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return Q(this,null,function*(){if(e.type===jW.svg)try{let t=yield e.text(),r=wpe(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(s){return Q(this,arguments,function*({attachment:e,file:t,resolve:r,reject:a}){try{let c=Ib(this.storage,e.bucketPath),p=x$(c,t,{cacheControl:"public,max-age=3600"});p.on("state_changed",g=>{let f=g.bytesTransferred/g.totalBytes*100},g=>{a(g)},()=>{E$(p.snapshot.ref).then(g=>{e.url=g,r(e)})})}catch(c){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",c),a(c)}})}uploadToResolver(c){return Q(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:a,reject:s}){try{r.attachmentId=t.attachmentId;let p={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},g=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Oa.ATTACHMENT_ADD});g&&g.data?.url?(t.url=g.data?.url,a(t)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>Q(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let p=yield this.sanitizeSvgFile(t),g=this.createAttachment({path:e,file:p});if(!g)throw new Error("Attachment not created");r?this.uploadToResolver({file:p,attachment:g,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:g,file:p,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}}))}uploadChunk(e,t,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,p=Ib(this.storage,c),g=x$(p,t,{cacheControl:"public,max-age=3600"});g.on("state_changed",f=>{let I=f.bytesTransferred/f.totalBytes*100},f=>{s(f)},()=>{E$(g.snapshot.ref).then(f=>{a(f)}).catch(f=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,f),s(f)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let r=t.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},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:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=Ib(this.storage,e.bucketPath);I$(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((t,r)=>{let a=Ib(this.storage,e);I$(a).then(()=>{t(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(Rt),ee(y),ee(Yg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var In=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=g,this.documentIAM$=new ve(null),this.workspaceIAM$=new ve(null),this.roles$=new ve([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Fe(f=>!!f),ot(1)).subscribe(f=>{f&&(this.getUser(),this.getDocumentPaths())},f=>{this.loggingService.catch("Error in CommentService getDb subscription: ",f)}),this.getRole$().pipe(ot(1)).subscribe(f=>{this.authService?.getUser()&&!f&&this.analyticsService.trackEvent(K.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(f=>{f?.accessType&&this.contactService.setDocumentAccessType(f.accessType)})}catch(f){this.loggingService.catch("Error in IamService constructor: ",f)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Fe(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Fe(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new V9;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(zn(e=>se(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(de(e=>!!e),vt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(de(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(de(e=>e?.features),he(e=>this.getRole$().pipe(de(t=>(t===so.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(he(()=>this.documentIAM$.pipe(Fe(t=>!!t),he(()=>this.workspaceIAM$.pipe(de(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(he(()=>this.configService.getSF$()),he(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),he(()=>this.configService.getSF()?this.documentIAM$.pipe(Fe(e=>!!e),vt(Kt)):se(null)),he(()=>this.workspaceIAM$.pipe(vt(Kt))),de(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return so.ADMIN;if(!e)return this.user?.isAdmin?so.ADMIN:so.COMMENTER;let t=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?Ei.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||Ei.PUBLIC:null){case Ei.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||so.COMMENTER;break;case Ei.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.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(de(e=>e===so.ADMIN),vt())}isUserAdmin(){try{return this.getRole()===so.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[Et(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[Et(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Et(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[Et(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ue),ee(yi),ee(bn),ee(rt),ee(Rt),ee(y),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ss=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.authService=e,this.docService=t,this.loggingService=r,this.commonDbService=a,this.usersService=s,this.commentUtilsService=c,this.coreActionsService=p,this.functions=g,this.configService=f,this.contactService=I,this.currentUserPermissions$=new ve(null),this.permissionsCache$=new ve(null),this.permissionProvider$=new ve(null);try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(T){this.loggingService.catch("Error in UserPermissionService constructor:",T)}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled())return!0;let r=this.contactService.getUserAccessFieldsByUserId(e);return r?t.every(a=>r.includes(a)):!0}catch(r){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",r),!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:Wo.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:Wo.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(r){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:Wo.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:Wo.DOES_NOT_EXIST,error:!0};let s=this.docService.getDocumentMetadata(e)??{};return this.docService.setDocumentMetadata(e,E(E({},s),a?.metadata??{})),{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(r){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:Wo.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:Wo.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{let t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return{};let r=yield this.validateResources(t),[a,s]=yield this.fetchUserPermissionsFromDB(t),c=this.buildPermissionsResponse(t,r,a,s);return!e&&Object.keys(c).length>0&&this.setCurrentUserPermissions(c),c}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),r=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:r.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId,organizationId:e?.organizationId??t?.clientOrganizationId?Qa(e?.organizationId??t?.clientOrganizationId??""):void 0}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a,clientOrganizationId:s}=e,c=[],p=[];a&&(c.push(this.organizationDetails(a)),p.push({id:s??"",type:"organization"})),t.forEach(f=>{c.push(this.folderDetails({folderId:Ui(f),organizationId:a??""})),p.push({id:f,type:"folder"})}),r.forEach(f=>{c.push(this.documentDetails({documentId:br(f),organizationId:a??""})),p.push({id:f,type:"document"})});let g=yield Promise.allSettled(c);return this.processValidationResults(g,p)})}processValidationResults(e,t){let r=[],a=[],s,c=e.map((p,g)=>({result:p,metadata:t[g]})).filter(({result:p})=>p.status==="rejected"||p.status==="fulfilled"&&p.value.error);for(let{result:p,metadata:g}of c){let f=p.status==="fulfilled"?p.value.errorCode??Wo.SOMETHING_WENT_WRONG:Wo.SOMETHING_WENT_WRONG,I={id:g.id,errorCode:f};switch(g.type){case"organization":if(s=I,f===Wo.DOES_NOT_EXIST)throw new Error(`Organization with id '${g.id}' does not exist`);break;case"folder":r.push(I);break;case"document":a.push(I);break}}return{failedFolderIds:r,failedDocumentIds:a,failedOrganizationId:s}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a}=e,s=[this.authService.getUser()?.userId??""],c=[...t.map(f=>Ui(f)),...r.map(f=>br(f)),a??""],[p,g]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:s,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:s,organizationId:a,resourceIds:c})]);return[p.status==="fulfilled"?p.value:[],g.status==="fulfilled"?g.value:[]]})}buildPermissionsResponse(e,t,r,a){let{folderIds:s,documentIds:c,clientOrganizationId:p,organizationId:g}=e,{failedFolderIds:f,failedDocumentIds:I,failedOrganizationId:T}=t,N={};return this.processRegularUserPermissions(N,r,s,c,p??"",g??"",f,I,T),this.processTemporaryUserPermissions(N,a),N}processRegularUserPermissions(e,t,r,a,s,c,p,g,f){for(let I of t)for(let T of I)T?.user?.userId&&(e[T.user.userId]=D(E({},r.length&&{folders:this.buildFolderPermissions(r,T,p)}),{documents:this.buildDocumentPermissions(a,T,g),organization:{[s]:this.buildOrganizationPermission(c,T,f)}}))}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case Wo.DOES_NOT_EXIST:return`${t} does not exist`;case Wo.PERMISSION_DENIED:return`User does not have access to ${t}`;case Wo.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(r){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",r),"Something went wrong"}}buildFolderPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"folder"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerFolderIds?.includes(Ui(s))?qs.VIEWER:qs.EDITOR},a},{})}buildDocumentPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"document"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerDocumentIds?.includes(br(s))?qs.VIEWER:qs.EDITOR},a},{})}buildOrganizationPermission(e,t,r){return r?{error:this.getErrorMessage(r.errorCode,"organization"),errorCode:r.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?qs.VIEWER:qs.EDITOR}}processTemporaryUserPermissions(e,t){for(let r of t)if(r?.userId)switch(this.ensureUserPermissionStructure(e,r.userId),r.type){case"folder":this.addTemporaryFolderPermission(e,r);break;case"document":this.addTemporaryDocumentPermission(e,r);break;case"organization":this.addTemporaryOrganizationPermission(e,r);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].folders||(e[r].folders={}),e[r].folders[a]||(e[r].folders[a]={accessRole:s??qs.EDITOR,expiresAt:c})}addTemporaryDocumentPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].documents||(e[r].documents={}),e[r].documents[a]={accessRole:s??qs.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].organization||(e[r].organization={}),e[r].organization[a]={accessRole:s??qs.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:r}){try{let a=!0,s=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return s&&(e&&typeof e=="string"&&s?.[c]?.organization?.[e]&&(s?.[c]?.organization?.[e]?.accessRole===qs.VIEWER||s?.[c]?.organization?.[e]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&s?.[c]?.folders?.[t]&&(s?.[c]?.folders?.[t]?.accessRole===qs.VIEWER||s?.[c]?.folders?.[t]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1),r&&typeof r=="string"&&s?.[c]?.documents?.[r]&&(s?.[c]?.documents?.[r]?.accessRole===qs.VIEWER||s?.[c]?.documents?.[r]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(vt(Kt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),r=this.authService.getUser()?.userId??"";if(t?.[r]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[r]?.organization?.[a]){let s=Qa(a);t[r].organization&&(t[r].organization[s]=t[r].organization[a],delete t[r].organization[a])}t?.[r]?.folders&&(t[r].folders=Object.fromEntries(Object.entries(t?.[r]?.folders??{}).map(([s,c])=>[Ui(s),c]))),t?.[r]?.documents&&(t[r].documents=Object.fromEntries(Object.entries(t?.[r]?.documents??{}).map(([s,c])=>[br(s),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(de(e=>this.refactorPermissionsWithServerIds(e)),vt(Kt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;"),this.currentUserPermissions$.next(e)}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===IC.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return Q(this,null,function*(){try{if(this.isRevokeAccessOnUserLogoutEnabled){let e=[],t=this.authService.getUser()?.userId??"";(this.getPermissionsCache()??[]).forEach(a=>{a.userId===t&&a.hasAccess&&(a.type===Mo.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&e.push(D(E({},a),{hasAccess:!1})):e.push(D(E({},a),{hasAccess:!1})))}),e.length>0&&(this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:on(),methodName:"revokeAccessOnUserLogout",source:"internal",payload:{requests:e}}),this.setPermissionsCache([]),yield this.revokeAccess({requests:e,userId:this.authService.getUser()?.userId??""}))}}catch(e){this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",e)}})}revokeAccessOnDocumentUnset(){return Q(this,null,function*(){try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let e=[],t=this.docService.getDocumentIds(),r=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.docService.getDocumentPaths()?.folderId??"",s=this.authService.getUser()?.userId??"",c=this.getPermissionsCache()??[];t.forEach(g=>{c.find(f=>f.resourceId===g.clientDocumentId&&f.type===Mo.DOCUMENT&&f.organizationId===r&&f.userId===s)&&(e.push({userId:s,resourceId:g.clientDocumentId,organizationId:r,type:Mo.DOCUMENT,hasAccess:!1}),c=c.filter(f=>!(f.resourceId===g.clientDocumentId&&f.type===Mo.DOCUMENT&&f.organizationId===r&&f.userId===s)))}),a&&c.find(g=>g.resourceId===a&&g.type===Mo.FOLDER&&g.organizationId===r&&g.userId===s)&&(e.push({userId:s,resourceId:a,organizationId:r,type:Mo.FOLDER,hasAccess:!1}),c=c.filter(g=>!(g.resourceId===a&&g.type===Mo.FOLDER&&g.organizationId===r&&g.userId===s))),r&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&c.find(g=>g.resourceId===r&&g.type===Mo.ORGANIZATION&&g.organizationId===r&&g.userId===s)&&(e.push({userId:s,resourceId:r,organizationId:r,type:Mo.ORGANIZATION,hasAccess:!1}),c=c.filter(g=>!(g.resourceId===r&&g.type===Mo.ORGANIZATION&&g.organizationId===r&&g.userId===s)));let p=on();this.setPermissionsCache(c),e.length>0&&(this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:"revokeAccessOnDocumentUnset",source:"internal",payload:{requests:e}}),yield this.revokeAccess({requests:e,userId:s}))}}catch(e){this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",e)}})}getAccess(r){return Q(this,arguments,function*({requests:e,userId:t}){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ad({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(r){return Q(this,arguments,function*({requests:e,userId:t}){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ad({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}onResourceAccessRequired(c){return Q(this,arguments,function*({requests:e,uniqueId:t,methodName:r,userId:a,fromCache:s=!0}){try{if(!e?.length)return;let p=[],g=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&s&&(e.forEach(f=>{let I=g?.find(T=>T.resourceId===f.resource.id&&T.type===f.resource.type&&T.userId===f.userId&&T.organizationId===f.resource.organizationId);I&&p.push(I)}),p.length>0&&(e=e.filter(f=>!p.find(I=>I.resourceId===f.resource.id&&I.type===f.resource.type&&I.userId===f.userId&&I.organizationId===f.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:r,source:"internal",payload:{requests:e,fromCache:s}});let f=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:r,source:"internal",payload:{result:f}}),f?.success&&f?.data?.length&&(this.setPermissionsCache([...g,...f.data]),f.data=[...p,...f.data]),f}else if(p.length>0)return this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:r,source:"internal",uniqueId:t,payload:{results:p}}),{data:p,success:!0,statusCode:200};return}catch(p){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",p),this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:r,source:"internal",uniqueId:t,payload:{error:p,requests:e,fromCache:s}});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 s=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(s,a)});let r=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(r)}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)(ee(Ue),ee(rt),ee(y),ee(pn),ee(Fn),ee(Kg),ee(ts),ee(Io),ee(Rt),ee(yi))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I,T,N,G,z,J,ce,ye,Oe){this.afAuth=e,this.analyticsService=t,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=g,this.databaseService=f,this.docService=I,this.domService=T,this.iamService=N,this.loggingService=G,this.notificationUtilsService=z,this.usersService=J,this.functions=ce,this.userPermissionService=ye,this.coreActionsService=Oe,this.db=hs(),this.notificationsDb=hs(void 0,Dn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new ve([]),this.rawNotificationsByIdMap$=new ve(new Map),this.processedNotifications$=new ve([]),this.userNotificationsFromServer$=new ve([]),this.readNotificationsOnForYouTab$=new ve(!1),this.currentDocumentOnly$=new ve(!1),this.notificationViews$=new ve({}),this.notificationsByIdMap$=new ve(new Map),this.historyPanelVisible$=new ve(!1),this.notificationsForYou$=new ve(null),this.notificationsByDocumentIdMap$=new ve(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new ve(null),this.maxNotificationDays$=new ve(15),this.tabConfig$=new ve({people:{enable:!1}}),this.settingsConfig$=new ve(null),this.muteAllNotifications$=new ve(!1),this.enableSettings$=new ve(!1),this.selfNotifications$=new ve(!1),this.settingsInitialConfig$=new ve([{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.notificationsPanelVisible$=new ve(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Fe($e=>!!$e),ot(1)).subscribe($e=>{$e&&(this.db=$e,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},$e=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",$e)}),this.authService.getUser$().subscribe($e=>{$e?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Be=>{this.notificationsByDocumentIdSubscription[Be]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe($e=>{if($e){let Be=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys($e||{}).forEach(be=>{let Se=Be?.[be]?.notifications;Se?.length&&Se.forEach(Ae=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Ae},$e)?.notification})}),this.notificationsByDocumentIdMap$.next(Be)}})}catch($e){this.loggingService.catch("Error in NotificationService constructor: ",$e)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{t[r]=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=Et(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:t}});if(r?.notificationsConfig)this.setDBConfigDataToInitialConfig(r?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let a={};this.settingsInitialConfig$.getValue().forEach(c=>{if(c.enable){let p=c?.values?.find(g=>g.id===c.default);a[c.id]=p||c?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(a).forEach(c=>{s[c]=a[c].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=Et(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Fe(t=>t===!0),he(()=>this.docService.getDocumentPaths$().pipe(Fe(t=>!!t),he(t=>Do(this.getInitialConfigFromDB(t)).pipe(he(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t?.documentId,userId:e}}).pipe(de(r=>{r?.data?.notificationsConfig&&!gi(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer([]),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(he(()=>this.getCurrentDocumentOnly$().pipe(he(e=>e?this.docService.getDocumentPaths$().pipe(de(t=>{})):se(void 0)))),tn(()=>{this.notificationsByDocumentIdMap$.next(null)}),he(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Ti(),de(([e,t])=>{let r=e?.map(g=>g.documentId),a=t?.map(g=>g.documentId),s=r?.filter(g=>!a?.includes(g)),c=a?.map(g=>({documentId:g,timestamp:t?.find(f=>f.documentId===g)?.timestamp})).filter(g=>!r?.includes(g.documentId)),p=a?.map(g=>{let f=t?.find(I=>I.documentId===g)?.timestamp;return{documentId:g,timestamp:f}}).filter(g=>{let f=e?.find(I=>I.documentId===g.documentId)?.timestamp;return f&&g.timestamp&&f!==g.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(g=>{this.removeNotificationsForDocumentId(g)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})))).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(he(t=>this.docService.getOrganizationConfig$().pipe(de(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||t?.organizationId;return s&&c&&(a=new dm({apiKey:s,organizationId:c})),{user:t,documentPaths:a}}))),he(t=>{let{user:r,documentPaths:a}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return se(null);if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime(),g=[_i(ht("timestamp",">=",p),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ht("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];return this.getCurrentDocumentOnly()||(g.push(Xi("timestamp","desc")),g.push(k9(e))),this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:g}}).pipe(de(f=>f?.data),de(f=>{let I=[];return Object.keys(f||{}).forEach(T=>{let N=this.commonDbService.shouldUseFirestore()?f[T]?.timestamp??0:f[T],G=this.commonDbService.shouldUseFirestore()?f[T]?.deletedNotification??!1:!1;if(G&&G.id&&G?.timestamp===N){let z=G.id,J=f[T]?.metadata?.documentId,ce=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),ye=ce?.[J]??{documentMetadata:null,notifications:[]},Oe=ye.notifications??[],$e=Oe?.findIndex(Be=>Be.id===z);$e!==-1&&(Oe.splice($e,1),this.notificationsByDocumentIdMap$.next(D(E({},ce),{[J]:D(E({},ye),{notifications:Oe})})))}I.push({documentId:T,timestamp:N})}),I}),zn(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),se([]))))}return se(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),se([])}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let r=Ki(this.functions,Zi({url:Dn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let s=this.getStartAtTimestamp(),c={};if(e.forEach(Oe=>{if(Oe?.documentId){let $e=this.getAllowedDocumentMetadataByDocumentId(Oe.documentId);$e&&(c[Oe.documentId]=$e)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let Oe=[];if(e.forEach(Ae=>{this.docService.getDocumentMetadata(Ae.documentId)||Oe.push(Ae.documentId)}),Oe.length){let Ae=this.authService.getUser(),Ce=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let fe=yield ad({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Ae?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:Oe},getSdkProxy:Ce,userId:Ae?.userId??""});if(fe?.data?.length){let we={};fe?.data.forEach(Ne=>{Ne?.documentId&&(we[Ne.documentId]=Ne)}),this.docService.setAllDocumentMetadata(E(E({},this.docService.getAllDocumentMetadataMap()),we))}}catch(fe){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",fe)}}let $e=[],Be=[];e.forEach(Ae=>{let Ce=this.docService.getDocumentMetadata(Ae.documentId);Ce?.clientDocumentId?$e.push({userId:this.authService.getUser()?.userId??"",resource:{id:Ce.clientDocumentId,type:Mo.DOCUMENT,source:Ir.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):Be.push(Ae.documentId)}),Be.length&&(e=e.filter(Ae=>!Be.includes(Ae.documentId)));let be=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:be,methodName:Ir.GET_NOTIFICATIONS,source:"internal",payload:{requests:$e}});let Se=yield this.userPermissionService?.onResourceAccessRequired({requests:$e,uniqueId:be,methodName:Ir.GET_NOTIFICATIONS});Se?.success&&Se?.data?.length?Se.data.forEach(Ae=>{!Ae.hasAccess&&Ae.resourceId&&(e=e.filter(Ce=>Ce.documentId!==br(Ae.resourceId)))}):e=[]}catch(Oe){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",Oe),e=[]}if(!e.length)return[];let p=this.userPermissionService?.getPermissionsCache()?.filter(Oe=>Oe.type===Mo.CONTEXT),g={organizationId:a,documentIds:e.filter(Oe=>!!Oe.documentId&&!!Oe.timestamp).map(Oe=>({documentId:Oe.documentId,timestamp:Oe.timestamp??0})),timestamp:s,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:p,retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},f=yield this.notificationUtilsService.handleNotificationEncryption({data:g}),I=yield r({veltData:f}),T=I?.data?.data?.veltData||{},N=I?.data?.data?.veltAdditionalData||{},G="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),z=yield j0(T,G),{userNotifications:J=[],userNotificationIdsInDocNotifications:ce=[],permissionResults:ye=[]}=yield j0(N,G);if(this.userPermissionService?.getIsContextEnabled()){let Oe=[...this.userPermissionService?.getPermissionsCache()??[],...ye??[]];this.userPermissionService?.setPermissionsCache(Oe)}if(z&&typeof z=="object"){let Oe=this.usersService.userDataProviderAvailable(),$e=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Be=[],be=[];Object.keys(z).forEach((Se,Ae)=>{let Ce=z[Se].documentMetadata;if(Ce){let we=this.allowedDocumentMetadataMap$.value||{};(!we?.[Se]||!gi(we?.[Se],Ce))&&this.allowedDocumentMetadataMap$.next(D(E({},we),{[Se]:Ce}))}let fe=z[Se].notifications||[];fe.forEach(we=>{ce.includes(we.notificationId)&&!J.find(Ne=>Ne.notificationId===we.notificationId)&&J.push(JSON.parse(JSON.stringify(we))),we.notification=this.getClientNotificationObject(we)}),this.setNotificationForDocumentIdInCache(Se,Ce,fe),Oe&&(Be.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:fe,shouldAwait:!0,forceResolve:!0})),Be.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:J,shouldAwait:!0,forceResolve:!0}))),$e&&(be.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:fe,shouldCommentAnnotationsResolverAwait:!0})),be.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:J,shouldCommentAnnotationsResolverAwait:!0})))}),this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer(),...J]),Oe&&Promise.all(Be).then(()=>{Object.keys(z).forEach(Se=>{let Ae=z?.[Se]?.documentMetadata||{},Ce=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:z?.[Se]?.notifications||[]});Ce.forEach(fe=>{fe.notification=this.getClientNotificationObject(fe)}),this.setNotificationForDocumentIdInCache(Se,Ae,Ce)})}),$e&&Promise.all(be).then(()=>{Object.keys(z).forEach(Se=>{let Ae=z?.[Se]?.documentMetadata||{},Ce=z?.[Se]?.notifications?.reduce((fe,we)=>(fe[we.notificationId]=we,fe),{});Ce=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Ce}),Ce=Object.values(Ce??{}),Ce.forEach(fe=>{fe.notification=this.getClientNotificationObject(fe)}),this.setNotificationForDocumentIdInCache(Se,Ae,Ce)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t.filter((r,a,s)=>a===s.findIndex(c=>c.notificationId===r.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),g=p?.[e]?.notifications||[],f=this.docService.getLocationMetadatas(),I=r?.map(G=>{let z=G?.notification;return z?(z.metadata&&(z.metadata.documentName=t?.documentName||z.metadata.documentName,z.metadata.organizationMetadata=c||z.metadata.organizationMetadata,z.metadata.documentMetadata=t||z.metadata.documentMetadata),f&&(z=this.notificationUtilsService.mergeLocationWithNotification({notification:z},f)?.notification),z):null})?.filter(G=>!!G)||[],T=new Map(g.map(G=>[G.id,G]));I.forEach(G=>{T.set(G.id,G)});let N=Array.from(T.values()).sort((G,z)=>(z.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(D(E({},p),{[e]:{notifications:N,documentMetadata:t}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}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(he(e=>se(e).pipe(de(t=>{let r=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable();if(r||a){let c=t?.reduce((p,g)=>(p[g.notificationId]=g,p),{});r&&(c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:c||[]})),a&&(c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:c||[]})),t=Object.values(c??{})}return t.forEach(c=>{c.notification=this.getClientNotificationObject(c)}),t.sort((c,p)=>p.timestamp-c.timestamp),t.map(c=>c.notification).filter(c=>!!c)}),he(t=>{let r={data:t?.reduce((a,s)=>(a[s.id]={notification:s},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:r,feature:"allUserNotifications"}).pipe(de(a=>Object.values(a?.data||{}).map(s=>s?.notification)))}))),he(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(de(()=>e))}),he(e=>this.allowedDocumentMetadataMap$.pipe(de(()=>e))),de(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=s||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([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=Rn(e)),t&&typeof t=="object"){let s=er(t);r=Rn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Fe(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(de(c=>(s.featureAllowed=c,s))):se(s)),he(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),se([])):se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(de(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Fe(t=>!!t),de(t=>D(E({},e),{config:t})),he(t=>this.authService.getUser$().pipe(de(r=>D(E({},t),{user:r})))),he(t=>eo(t.config,t.user,Re.NOTIFICATION)?se(D(E({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(D(E({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Fe(t=>!!t),he(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=Pi(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return gM(a).pipe(zn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),de(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(f=>{let I=s?.raw[f];I?.id&&c.push(I)}),c.forEach(f=>{f.id&&p.set(f.id,f)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let g=[];s?.processed&&Object.keys(s?.processed||{}).forEach(f=>{let I=s?.processed[f];I?.id&&g.push(I)}),this.processedNotifications$.next(g),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),r;e?.email&&(r=Et(e?.email));let a;e?.userId&&(a=Et(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let g=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(g=!0);let f={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:g,notificationSourceData:p.notificationSourceData},I=this.getRawNotificationById(f.id);if(I?.metadata&&(f.metadata={apiKey:I.metadata.apiKey,organizationId:I.metadata.organizationId,clientOrganizationId:I.metadata.clientOrganizationId,documentId:I.metadata.documentId,clientDocumentId:I.metadata.clientDocumentId,location:I?.location,locationId:I?.locationId}),f?.notificationSource==="comment"&&f?.targetAnnotationId){let T=this.commentService?.getAnnotationById(f.targetAnnotationId);T||I?.annotationData&&(T=I.annotationData),T&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(T))}s.set(p.id,f)}}),s.forEach((p,g)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[g]?.views?.[e?.userSnippylyId],s.set(g,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let g=null;c?.email&&(g=Et(c?.email));let f=null;c?.userId&&(f=Et(c?.userId));let I=!1,T=!0;(g&&p.notifyUsers?.[g]||f&&p.notifyUsersByUserId?.[f])&&(I=!0),f&&a?.[f]&&(T=!1);let N={id:p.id};if(s?N=D(E(E({},N),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:I,isUnread:T}):N={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:I,isUnread:T,metadata:r},N?.notificationSource==="comment"&&N?.targetAnnotationId){let G=this.commentService?.getAnnotationById(N.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||t?.annotationData&&(G=t.annotationData),G&&(N.notificationSourceData=this.commentService?.getCommentAnnotationForClient(G))}return t?.targetAnnotationData?.isCommentResolverUsed&&(N.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),N}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(de(e=>e?Object.keys(e??{}).map(t=>{let r=e[t].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,r)=>r.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(de(e=>{let t=null;return e?(t=[],e.forEach(r=>{r.notifications.forEach(a=>{t?.push(a)})}),t?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,r=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(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=t?.documentId?new dm({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),g=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(g))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{let t=Pi(this.notificationsDb),r=this.processNotificationData(e);iM(t,JSON.parse(JSON.stringify(r)))}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(he(t=>t?t.organizationId?this.getAllNotifications$().pipe(he(r=>this.notificationsForYou$.pipe(de(a=>{if(r||a){let s=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(r||[]).forEach(c=>{c.id&&s.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!s.has(c.id)&&s.set(c.id,c)}),Array.from(s.values()).sort((c,p)=>(p.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(de(r=>Array.from(r.values())),de(r=>r.sort((a,s)=>s.timestamp-a.timestamp)),Bu()):se(null)),vt(Kt))}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 r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,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]:p);return this.domService.sanitizeHtml(c)}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(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);t=t?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${r.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,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(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 c=0;c<e.length;c+=50){let g=e.slice(c,c+50).filter(T=>T?.id),f=g.map(T=>this.setNotificationAsRead({notification:T,userNotifications:JSON.parse(JSON.stringify(t))})),I=yield Promise.all(f);g.forEach((T,N)=>{let G=I[N];if(!G.some(J=>J.notificationId===T.id))t=t.filter(J=>J.notificationId!==T.id);else{let J=t.find(ye=>ye.notificationId===T.id),ce=G.find(ye=>ye.notificationId===T.id);J&&ce?.views&&(J.views=ce.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(c=>{let p=c.metadata?.documentId;if(p&&a?.[p]){let g=a?.[p]?.notifications||[],f=g.find(I=>I.id===c.id);f&&(f.isUnread=!1),a[p].notifications=g}}),this.notificationsByDocumentIdMap$.next(a),!gi(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(ot(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(de(e=>e?.filter(r=>r?.isUnread)?.length??null),he(e=>this.getNotifications$().pipe(de(t=>{let r=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(r){return Q(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let s=Et(a?.userId),{metadata:c}=e;if(c){let{apiKey:p,organizationId:g,documentId:f}=c;if(p&&g&&f&&s){let I=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:g,documentId:f,apiKey:p}});I?.notificationId&&(I?.views?.[s]||(I.views||(I.views={}),I.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:g,documentId:f,apiKey:p},data:I})));let T=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:s,documentId:f,organizationId:g}});if(T?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:s,documentId:f,organizationId:g}}),t=t.filter(N=>N.notificationId!==e.id);else if(!T?.views?.[s]){T.views||(T.views={}),T.views[s]={timestamp:Date.now()};let N=t.find(G=>G.notificationId===e.id);N&&(N.views=T.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:s,documentId:f,organizationId:g},data:T})}}}}}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(ot(1)).subscribe(t=>{if(t){let r=t.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}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)}}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(r=>{["email","inbox"].includes(r.id)&&(t=!r.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=Et(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:t,clientUserId:this.authService.getUser()?.userId};t&&r?.documentId&&this.getEnableSettings()&&this.enableSettings$.value&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:t},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}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)(ee(Ai),ee(et),ee(Ue),ee(Rt),ee(pn),ee(pm),ee(Kg),ee(Ys),ee(bn),ee(rt),ee(Le),ee(In),ee(y),ee(lR),ee(Fn),ee(Io),ee(Ss),ee(ts))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Uo=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(U.CommentAnnotationStatusMap),this._customPriorityMap=new ve(U.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(U.CommentCategoryMap);try{let t=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(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(r=>{t[r.id]=r,r.type||(r.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(r=>{t[r.id]=r}),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(r=>{t[r.id]=r}),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(([r,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(([r,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(([r,a])=>a.type==="ongoing");if(t)return t.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),r=t.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=t.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=t.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[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)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pd=(()=>{let o=class o{constructor(e,t,r){this.domService=e,this.loggingService=t,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(t=>{let r=e[t];if(r.svg)this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
207
|
+
`+Sa),Cd&&J9([we,Ne,to],il=>{Sa=LI(Sa,il," ")}),Oe&&_u?Oe.createHTML(Sa):Sa},o.setConfig=function(){let ln=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rf(ln),Af=!0},o.clearConfig=function(){Cc=null,Af=!1},o.isValidAttribute=function(ln,Ve,At){Cc||Rf({});let Xt=pr(ln),uo=pr(Ve);return Nf(Xt,uo,At)},o.addHook=function(ln,Ve){typeof Ve=="function"&&FI(fe[ln],Ve)},o.removeHook=function(ln,Ve){if(Ve!==void 0){let At=DNe(fe[ln],Ve);return At===-1?void 0:wNe(fe[ln],At,1)[0]}return ipe(fe[ln])},o.removeHooks=function(ln){fe[ln]=[]},o.removeAllHooks=function(){fe=cpe()},o}var jI=gpe();var upe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Le=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=r,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new ve(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new ve([]),this.mousedown=!1,this.windowMouseDown$=new tt,this.windowPointerMove$=new ve(null),this.windowPointerUp$=new ve(null),this.documentSelectionChange$=new ve(null),this.windowClick$=new ve(null),this.windowScroll$=new ve(null),this.windowResize$=new ve(null),this.windowKeyupBackspace$=new ve(null),this.windowKeyupDelete$=new ve(null),this.windowKeyupEsc$=new ve(null),this.windowPopState$=new ve(null),this.documentClick$=new ve(null),this.documentClickSubject$=new tt,this.documentFocus$=new ve(null),this.windowKeydownShift$=new ve(null),this.windowKeyupShift$=new ve(null),this.mutation$=new ve(null),this.childListMutation$=new ve(null),this.networkStatus$=new ve(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new ve({}),this.selectedAnnotationsLocationMap$=new ve({}),this.recordingInProgress$=new ve({}),this.deleteAnnotations$=new ve([]),this.pinHighlighterClass$=new ve(null),this.dialogOpenedInSidebar$=new ve(!1),this.textHighlighterClass$=new ve(null),this.commentPinHighlighter$=new ve(!1),this.deviceInfo$=new ve(new Yn),this.customCss$=new ve(null),this.mutationObserver=null,this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=s=>{try{let c=[];return s.forEach(p=>{if(!Gi(p))if(p instanceof HTMLElement){if(p.className.includes("cdk-overlay-container")||p.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(p.className.includes("cdk-overlay")){let g=!1;p.childNodes.forEach(f=>{Gi(f)&&(g=!0)}),g||c.push(p)}else c.push(p)}else c.push(p)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let s=this.calculateScreenSize();this.currentScreenSize$=new ve(s),this.currentMousePosition$=new ve(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Ti(),tn(([c,p])=>{try{let g=p.filter(I=>!c.includes(I)),f=c.filter(I=>!p.includes(I));f.length&&f.map(T=>document.getElementById(T)).filter(T=>T).forEach(T=>{this.unlistenElementScroll&&this.unlistenElementScroll[T.id]&&this.unlistenElementScroll[T.id]()}),g.length&&g.map(T=>document.getElementById(T)).filter(T=>T).forEach(T=>{this.unlistenElementScroll[T.id]=this.renderer.listen(T,"scroll",N=>{let G=this.calculateScreenSize();this.currentScreenSize$.next(G)})})}catch(g){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",g)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?Ble("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):Vle("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}catch(s){this.loggingService.catch("Error in DomService constructor: ",s)}}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(r=>typeof r=="string"?new RegExp(r):r).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 r=new Set(["id","class","style"]);return e.getAttributeNames().forEach(s=>{if(r.has(s)||s.includes("snippyly")||s.includes("velt"))return;let c=e.getAttribute(s);c&&c.length<=256&&(t[s]=c)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],s=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((p,g)=>{let f=s.findIndex(T=>p.startsWith(T)),I=s.findIndex(T=>g.startsWith(T));return(f===-1?99:f)-(I===-1?99:I)}).slice(0,4).forEach(p=>{let g=CSS.escape(t[p]);a.push(`[${p}="${g}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",s,c=0;for(;(s=r.nextNode())&&a.length<t;){let p=(s.textContent||"").replace(/\s+/g," ").trim();if(p&&(a+=(a?" ":"")+p),c++,c>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return Tle(e)}catch{return}}generateRobustXPath(e,t){try{let r=t?.maxDepth||10,a=t?.useAbsolutePath||!1,s=[],c=e,p=0;for(;c&&c!==document.documentElement&&p<r;){let T=this.buildRobustXPathSegment(c);if(T&&(s.unshift(T),this.isStrongAnchorSegment(T)))break;c=c.parentElement,p++}if(s.length===0)return;let f=(a?"/":"//")+s.join("/");return s.some(T=>T.includes("[@")||T.includes("[contains(@class"))?f:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),r=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let I of r){let T=e.getAttribute(I);if(T)return`${t}[@${I}=${this.escapeXPathValue(T)}]`}let a=Array.from(e.attributes).filter(I=>I.name.startsWith("data-")&&!I.name.includes("snippyly")&&!I.name.includes("velt")&&I.value.length<100).sort((I,T)=>I.value.length-T.value.length);if(a.length>0){let I=a[0];return`${t}[@${I.name}=${this.escapeXPathValue(I.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let c=e.getAttribute("aria-label");if(c&&c.length<50)return`${t}[@aria-label=${this.escapeXPathValue(c)}]`;let p=e.getAttribute("name");if(p)return`${t}[@name=${this.escapeXPathValue(p)}]`;let g=e.getAttribute("type");if(g)return`${t}[@type=${this.escapeXPathValue(g)}]`;let f=Array.from(e.classList||[]).filter(I=>I.length>0&&I.length<40&&!I.includes("yui")&&!I.includes("velt")&&!I.includes("snippyly")&&!this.excludeClassList.includes(I)).slice(0,2);if(f.length>0){let I=f.map(T=>`contains(@class, ${this.escapeXPathValue(T)})`).join(" and ");return`${t}[${I}]`}if(e.parentElement){let I=Array.from(e.parentElement.children).filter(T=>T.tagName===e.tagName);if(I.length>1){let T=I.indexOf(e)+1;return`${t}[${T}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(["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(s=>`'${s}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(c=>`'${c}'`).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}}generateAnchorRecord(e,t){try{let r=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Di(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),r&&a){let s=this.generateAnchorRecordForElement(a,t);s&&(r.parent=s)}return r}catch(r){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",r),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let r=e,a=r.tagName?.toUpperCase();if(!a)return null;let s=r.id&&!this.isLikelyDynamicId(r.id)?r.id:void 0,c=this.getStableAttributes(r),p=this.buildStableElementSelector(r,c),g=this.getVisibleText(r),f=this.hashText(g||""),I=this.generateRobustXPath(r),T=this.getXPath(r),N=this.getXPath(r,!0),G=this.getXPath(r,!0,!0);return{version:"1.0",id:s,tagName:a,elementSelector:p,robustXPath:I||void 0,xPath:T||void 0,fXPath:N||void 0,cfXPath:G||void 0,contentHash:f?{value:f,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(r){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",r),null}}resolveAnchorRecord(e){try{let t=[],r=null,a=(f,I,T=0)=>{let N=[],G=T;if(N.push({method:I,score:T}),e.tagName&&f.tagName?.toUpperCase()===e.tagName&&(G+=10,N.push({method:"tagName-match",score:10})),e.contentHash?.value){let z=this.getVisibleText(f);this.hashText(z)===e.contentHash.value&&(G+=30,N.push({method:"contentHash-match",score:30}))}t.push({el:f,score:G,by:I,scoreBreakdown:N})};if(e.id){let f=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(f.length===1)return{element:f[0],matchedBy:"id",score:90};f.length>1&&f.forEach(I=>a(I,"id-duplicate",70))}if(e.elementSelector){let f=document.querySelectorAll(e.elementSelector);if(f.length===1)return{element:f[0],matchedBy:"element-selector",score:80};f.forEach(I=>a(I,"element-selector-duplicate",60))}if(e.robustXPath){let f=this.getElementFromRobustXPath(e.robustXPath);f&&a(f,"robustXPath",50)}e?.parent&&(r=this.resolveAnchorRecord(e.parent),r.element&&r.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(I=>a(I,"parent+tag",40)));let s=(f,I,T)=>{if(!f)return;let N=this.getElementFromXPath(f);N&&a(N,I||"xpath",T||30)};if(s(e.xPath,"xPath",30),s(e.cfXPath,"cfXPath",30),s(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let I=T=>{let N=0;for(let G=0;G<T.length&&N<400;G++){let z=T[G];if(N++,!this.isElementVisible(z))continue;let J=this.getVisibleText(z),ce=this.hashText(J);ce&&ce===e.contentHash?.value&&a(z,"contentHash",15)}};if(r?.element&&r?.element instanceof Element){let T=r?.element?.querySelectorAll("*");I(T)}}if(!t.length)return{element:null};t.sort((f,I)=>I.score-f.score);let c=t[0].score,p=t.filter(f=>f.score===c);if(p.length>1){let f=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let I of f)if(I.path){let T=this.getElementFromXPath(I.path);if(T){let N=p.find(G=>G.el===T);if(N)return{element:N.el,matchedBy:`${N.by}+position`,score:N.score,scoreBreakdown:N.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(de(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.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===U.VELT_IGNORE_CHANGE_DETECTION))return;let r=t.filter(a=>a.type==="childList").filter(a=>{let s=a.target;return a.removedNodes.forEach(c=>{let p=c;if(typeof p.getAttribute=="function"){let g=p.getAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(g!==null&&g!==""){let f=this.xpathCacheId.get(g);f!==void 0&&(this.xpathCacheId.delete(g),this.xpathCache.delete(f))}}}),Gi(s)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.childListMutation$.next(r),r.push(...t.filter(a=>a.type==="attributes").filter(a=>!Gi(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let s=a.target;return s?.classList?.contains("snippyly-sidebar-panel")?!1:s?!s.getAttribute(U.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),r=r.filter(a=>{let s=!0;return Object.keys(U.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(c=>{a.target?.closest(c)&&(s=!1)}),s}),r=r.filter(a=>a.target&&Di(a.target)),r.length&&this.mutation$.next(r)}catch(r){this.loggingService.catch("Error in DomService change detection: ",r)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{No(hi(window,"offline").pipe(de(()=>!1)),hi(window,"online").pipe(de(()=>!0)),new Ut(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 Yn),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 hi(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Rl}}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),r=e.target;if(t?.includes("name()='svg'")){let f=this.getXPath(t);f&&(r=f.iterateNext()||e.target)}let a=r.getBoundingClientRect(),s=e.clientX-a.x,c=e.clientY-a.y,p=s*100/(a.width||1),g=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:g,leftPercentage:p}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,r=!1,a=!0,s,c=!0,p){try{let g=e,f=g?.touches?.length?g.touches[0]?.clientX:g?.clientX,I=g?.touches?.length?g.touches[0]?.clientY:g?.clientY;p&&(f=p.clientX,I=p.clientY);let T=this.getBackgroundElement(f,I,t,r);if(T&&s&&typeof s=="function"&&(T=s(T)),T){let N=this.getXPath(T),G=this.getXPath(T,!0),z=T.getBoundingClientRect(),J=f-z.x,ce=I-z.y,ye=J*100/(z.width||1),Oe=ce*100/(z.height||1),$e={xpath:N,fXpath:G,leftPercentage:ye,topPercentage:Oe};if(a){let Be=this.getXPath(T,!0,!0);$e.cfXpath=Be}if(c){let Be=this.generateAnchorRecord(T);Be&&($e.anchor=Be)}return $e}else return null}catch(g){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",g),null}}getBackgroundElement(e,t,r=!0,a=!1){try{let s=document.elementsFromPoint(e,t),c=[];s.forEach(g=>{Gi(g)?c=[]:Di(g)&&c.push(g)}),a&&(c=c.filter(g=>this.isElementVisibleOnScreen(g)));let p=0;return r||c?.forEach((g,f)=>{g.tagName.toLowerCase()==="svg"&&(p=f)}),c[p]}catch(s){return this.loggingService.catch("Error in DomService getBackgroundElement: ",s),null}}getBackgroundVeltElement(e,t){try{let r=document.elementsFromPoint(e,t),a=[];return r.forEach(s=>{Gi(s)&&Di(s)&&a.push(s)}),a[0]}catch(r){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",r),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(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,r=Math.min(t,e.width/2),a=Math.abs(e.y),s=e.y-20;return a>50&&(s=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(r),this.loggingService.log(s),{topPositionX:r,topPositionY:s}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,t,r){if(e){if(!r&&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"),s=e.style.getPropertyPriority("cursor"),c=a?{defaultCursorValue:a,defaultCursorPriority:s}:"";e.setAttribute(U.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),e.style.setProperty("cursor",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,r,a=!1){try{e&&(this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(U.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(U.VELT_SELECTION_COLOR)&&e.style.setProperty(U.VELT_SELECTION_COLOR,t),r&&e.setAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME,r))}catch(s){this.loggingService.catch("Error in DomService highlightUserElement: ",s)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,U.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT),e.removeAttribute(U.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(U.VELT_SELECTION_COLOR),e.removeAttribute(U.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(U.VELT_SELECTION_COLOR))}catch(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,r=!1,a){try{let s=this.calculateXPath(e,t,r,a);if(s&&typeof s=="string"&&s.includes("/svg")){let c=s.split("/"),p=!1;c.forEach((g,f)=>{g.includes("svg")&&(p=!0),p&&(c[f]="svg:"+g)}),s=c.join("/")}return s}catch(s){this.loggingService.catch("Error in DomService getXPath:",s)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,r,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!t)return"//*[@id='"+e.id+"']";if(r&&e.className&&e.className.split){let c=e.className?.split(" ")?.filter(p=>!p?.includes("snippyly")&&!p?.includes("velt")&&!["show-pin-cursor"].includes(p))[0];if(c){let p=this.calculateXPath(e.parentNode,t,r,a)+"/"+e.tagName.toLowerCase(),g=Array.from(e.parentNode?.children||[]).filter(f=>f.nodeType===1&&f.tagName===e.tagName?f.className?.split(" ")?.filter(T=>T?.includes("snippyly")||T?.includes("velt")||["show-pin-cursor"].includes(T))[0]===c:!1);if(g.length>1){let f=g.indexOf(e)+1;p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${f}]`}else p+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return p}}let s=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,r)+"/"+e.tagName.toLowerCase()+(s.length>1?"["+([].indexOf.call(s,e)+1)+"]":"")}}catch(s){this.loggingService.catch("Error in DomService calculateXPath:",s)}}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 r=this.getXPath(e,!1,!1,t);if(r){let a=r?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let s=on();a.setAttribute(U.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,s),this.xpathCacheId.set(s,e)}return this.xpathCache.set(e,a),a}return null}catch(r){return this.loggingService.catch("Error in DomService getElementFromXPath:",r),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let r=this.resolveAnchorRecord(e.anchor);r?.element&&(t=r.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 r=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);r?.element&&(t=r.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 r=new PI;return r.screenWidth=Math.max(...t),r.screenHeight=Math.max(...e),r.screenScrollHeight=this.pageScrollHeight,r}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new PI}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let r=new DOMParser().parseFromString(e,"text/html");r.querySelectorAll("[data-snippyly-cache-id]").forEach(I=>{I.removeAttribute("data-snippyly-cache-id")}),r.querySelectorAll("[data-velt-cache-id]").forEach(I=>{I.removeAttribute("data-velt-cache-id")}),r.querySelectorAll(".comment-text-highlight").forEach(I=>{I?.parentNode?.insertBefore(document.createTextNode(I?.textContent),I),I.remove()});let p=document.createNodeIterator(r,NodeFilter.SHOW_COMMENT),g;for(;g=p.nextNode();)g?.remove();return this.mergeAdjacentTextNodes(r.body),this.sanitizeHtml(r.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 r=t.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;)t.textContent+=r.textContent,r.remove(),r=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 r=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(r,this.pageScrollHeight),this.nodeMap[r]=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 r=Array.from(document.querySelectorAll(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];r.push(...a),r=Array.from(new Set(r));let s=r.map(f=>f.classList.contains("velt-annotation-draft-checked")?(f.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(f,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(f,"velt-comment-dialog-shake"),f.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||f.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(f,"velt-annotation-draft-checked")},100),f.getAttribute(U.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(f=>f),c=Object.keys(this.getRecordingInProgress()||{});s=[...s,...c];let p=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let f=[];Object.keys(p).forEach(I=>{if(p[I]?.type==="tag"){let T=p[I];T?.to?.length||s.includes(I)||f.push(T)}else p[I]?.comments?.length||s.includes(I)||f.push(p[I])}),this.deleteAnnotations$.next(f),this.deleteAnnotations$.next([])}let g={};Object.keys(p).forEach(f=>{if(s.includes(f)&&(g[f]=p[f]),t)switch(t){case"comment":["comment","videoPin"].includes(p[f]?.type)||(g[f]=p[f]);break;default:p[f]?.type!==t&&(g[f]=p[f]);break}}),Object.keys(g).forEach(f=>{let I=g[f]?.multiThreadAnnotationId;I&&!g[I]&&(g[I]={annotationId:I,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(g)&&this.selectedAnnotationsMap$.next(g),this.setDialogOpenedInSidebar(!1)}catch(r){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",r)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(D(E({},this.recordingInProgress$.value),{[e]:t}));else{let r=this.recordingInProgress$.value;delete r[e],this.recordingInProgress$.next(r)}}catch(r){this.loggingService.catch("Error in DomService setRecordingInProgress: ",r)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[];return Array.from(document.querySelectorAll(`${U.TAGS.SNIPPYLY_COMMENT_DIALOG}`)).forEach(r=>{if(r?.shadowRoot){let a=r.shadowRoot.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);a&&e.push(a)}else{let a=r.querySelector(`${U.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(a?.shadowRoot){let s=a.shadowRoot?.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=r.querySelector(`[${U.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let r={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(r[a]=t[a]);break;default:t[a].type===e&&(r[a]=t[a]);break}}),r}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(de(t=>{if(e){let r={};return Object.keys(t).forEach(a=>{t[a].type===e&&(r[a]=t[a])}),r}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(de(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,r,a=!1,s){try{r==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),p=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,p[e.annotationId]=t,s=e?.multiThreadAnnotationId||s,s&&(c[s]={annotationId:s,type:"multiThread"},p[s]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(p).forEach(g=>{c[g]||delete p[g]}),this.selectedAnnotationsLocationMap$.next(p)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}setSelectedAnnotationLocation(e,t){try{let r=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));r?.[e]!==t&&(r[e]=t,this.selectedAnnotationsLocationMap$.next(r))}catch(r){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",r)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(r=>{t[r.annotationId]&&(t[r.annotationId]=r)}),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),se([])}}getHighestNode(){return this.loggingService.log("%c[WB] Calling FUNCTION: getHighestNode","color: green;"),this.highestNode}onWindowMouseDown$(){return this.windowMouseDown$.asObservable()}onWindowPointerMove$(){return this.windowPointerMove$.asObservable()}onWindowPointerMove(){return this.windowPointerMove$.value}onWindowPointerUp$(){return this.windowPointerUp$.asObservable()}onSelectionChange$(){return this.documentSelectionChange$.asObservable()}onWindowClick$(){return this.windowClick$.asObservable()}onWindowScroll$(){return this.windowScroll$.asObservable()}onWindowResize$(){return this.windowResize$.asObservable()}onWindowKeyupBackspace$(){return this.windowKeyupBackspace$.asObservable()}onWindowKeyupDelete$(){return this.windowKeyupDelete$.asObservable()}onWindowKeyupEsc$(){return this.windowKeyupEsc$.asObservable()}onWindowPopState$(){return this.windowPopState$.asObservable()}onDocumentClick$(){return this.documentClick$.asObservable()}getLastDocumentClick(){return this.documentClick$.value}onDocumentClickSubject$(){return this.documentClickSubject$.asObservable()}onDocumentFocus$(){return this.documentFocus$.asObservable()}onDomChange$(e){try{return this.mutationObserver||this.setMutationObserver(e),this.mutation$.asObservable()}catch(t){return this.loggingService.catch("Error in DomService onDomChange$: ",t),se([])}}getChildListMutation$(){return this.childListMutation$.asObservable()}onNetworkStatusChange$(){return this.networkStatus$.asObservable()}getNetworkStatus(){return this.networkStatus$.value}getElementOffset(e,t){try{let r={offsetTop:0,offsetLeft:0},a=e;if(a===t){let s=window.getComputedStyle(e);s.position==="static"&&s.transformStyle!="preserve-3d"&&s.transform=="none"&&(r.offsetLeft=e?.offsetLeft||0,r.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let p=a.parentElement;if(p){let g=p.getBoundingClientRect(),f=a.getBoundingClientRect();r.offsetLeft+=f.left-g.left,r.offsetTop+=f.top-g.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let p=window.getComputedStyle(a);p.position==="static"&&p.transformStyle!="preserve-3d"&&p.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0)}}else{let c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.transform=="none"&&(r.offsetLeft+=a?.offsetLeft||0,r.offsetTop+=a?.offsetTop||0):(r.offsetLeft+=a.offsetLeft,r.offsetTop+=a.offsetTop)}return r}catch(r){return this.loggingService.catch("Error in DomService getElementOffset: ",r),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:r,top:a,bottom:s}=e?.getBoundingClientRect();return t>0||r>0||a<window.innerHeight&&s>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,r=window.getComputedStyle(t);return!(r.display==="none"||r.visibility==="hidden"||parseFloat(r.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ut(e=>{let t=hi(document,"mousedown").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),r=hi(document,"mousemove").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),a=hi(document,"mouseup").pipe(de(p=>({type:p.type,x:p.clientX+window.scrollX,y:p.clientY+window.scrollY,event:p}))),c=t.pipe(he(p=>r.pipe(Ti(),de(([g,f])=>({startPoint:p,prevPoint:g,curPoint:f})),fo(a)))).subscribe(e);return()=>c.unsubscribe()})}drawRectangle(e,t){let r=document.querySelector(".rectangle");r||(r=document.createElement("div"),this.addClassToElement(r,"rectangle"),r.setAttribute(U.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),r.setAttribute(U.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(r));let a=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y),c=Math.min(e.x,t.x),p=Math.min(e.y,t.y);return r.style.width=`${a}px`,r.style.height=`${s}px`,r.style.left=`${c}px`,r.style.top=`${p}px`,r.style.position="absolute",r.style.border="2px dashed #f00",r.style.pointerEvents="none",r.style.zIndex="2147483577",r}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let t={},r=e.commonAncestorContainer;r?.nodeType===Node.TEXT_NODE&&(r=r.parentElement);let a=document.body;if(r){let c=this.getTextXPath(r);this.isXpathWithId(c)&&(a=r)}let s=this.getAdditionalLocationContainer(r);if(s&&(a=s),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);if(c){t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let p=this.generateAnchorRecord(c);p&&(t.commonAncestorContainerAnchor=p)}}return t.text=e.toString(),t.occurrence=Qh(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,r=e.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&t++,r=r.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 r=e?.closest("picture");return r?r?.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:r}){try{let a=[];if(e?.length)for(let s=0;s<e.length;s++){let c=document.getElementById(e[s]);c&&a.push(c)}if(t?.length)for(let s=0;s<t.length;s++){let c=document.getElementsByClassName(t[s]);for(let p=0;p<c.length;p++){let g=c[p];g&&g instanceof HTMLElement&&a.push(g)}}if(r?.length)for(let s=0;s<r.length;s++){let c=document.querySelectorAll(r[s]);for(let p=0;p<c.length;p++){let g=c[p];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 r=0;r<t.length;r++){let a=document.getElementById(t[r]);if(a&&a.contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",r),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.getElementsByClassName(t[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",r),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let r=0;r<t.length;r++){let a=document.querySelectorAll(t[r]);for(let s=0;s<a.length;s++)if(a[s].contains(e))return!0}return!1}return!0}catch(r){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",r),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(r){this.loggingService.catch("Error in DomService addClassToElement: ",r)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(r){this.loggingService.catch("Error in DomService removeClassFromElement: ",r)}}isElementInsideParentWithAttribute(e,t,r){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===r)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(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),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let r=e?.shadowRoot?.querySelector(`[${U.VELT_CUSTOM_CSS}]`);if(r&&r.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 r=t.innerHTML;return r=r.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),r}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(s){return r.test(s.innerHTML)};var t=a;let r=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(r){this.loggingService.catch("Error in DomService removeEmptyElements: ",r)}}normalizeWhitespace(e){try{e.childNodes.forEach(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;"),jI.sanitize(e,upe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeSvg(e){try{return jI.sanitize(e,upe)}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 Yn;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),se(new Yn)}}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=on(),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 Yn}}isMobileDevice(){try{return new Yn().getDeviceType()===sr.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new Yn().getDeviceType()===sr.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new Yn().getDeviceType()===sr.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(r=>{t.setAttribute(r.nodeName,r.nodeValue)}),e.childNodes.forEach(r=>{r.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(r)):r.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(r.nodeValue))}),t}catch(r){return this.loggingService.catch("Error in DomService deepCloneElement: ",r),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(r=>{if(this.removeWireframeSuffixFromTags(r),r.tagName.toLowerCase().endsWith("-wireframe")){let a=r.tagName.toLowerCase().replace("-wireframe",""),s=document.createElement(a);for(Array.from(r.attributes).forEach(c=>{s.setAttribute(c.name,c.value)});r.firstChild;)s.appendChild(r.firstChild);r.parentNode.replaceChild(s,r)}})}isMonitorDevice(){try{return new Yn().getDeviceType()===sr.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}};o.MULTIPLE_NBSP_REGEX=/(?: \s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?: \s*)+|(?: \s*)+$/g,o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Zo),ee(y),ee(ml))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ue=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.afAuth=e,this.configService=t,this.avatarService=r,this.coreActionsService=a,this.domService=s,this.functions=c,this.analyticsService=p,this.loggingService=g,this.user$=new ve(null),this.userOptions$=new ve(null),this.userContacts$=new ve(null),this.userOrganization$=new ve(null),this.providedUser=new Bo,this.firebaseConfig$=new ve(null),this.advancedQueries$=new ve(null),this.planDetails$=new ve(null),this.signOutPreviousUser$=new ve(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{this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(f=>{this.config=f}),this.forceReLoggedIn=localStorage.getItem(U.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=ei(this.afAuth).pipe(no(this.afAuth.currentUser),Ti(),he(([f,I])=>this.domService.onNetworkStatusChange$().pipe(Fe(T=>T),ot(1),de(()=>({previousUser:f,currentUser:I}))))).subscribe(T=>Q(this,[T],function*({previousUser:f,currentUser:I}){if(!I&&f){let N=f?.stsTokenManager?.expirationTime,G=new Date().getTime(),z=N-G;G>N&&(this.analyticsService.trackEvent(K.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:z,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&f?.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:z,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:z,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"))))}}),f=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",f)}),this.getUser$().pipe(vt(Kt)).subscribe(f=>{let I=Qr(f);this.coreActionsService.triggerAction(Un.USER_UPDATE,I),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:Un.USER_UPDATE,payload:{user:I}})})}catch(f){this.loggingService.catch("Error in AuthService constructor: ",f)}}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 B9),this.configService.initConfig(t),t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||ei(this.afAuth).pipe(ot(1)).subscribe(r=>Q(this,null,function*(){if(this.autoLoginCalled=!0,r){let a=yield ap(r,!0).catch(s=>null);if(a){let{user:s}=a?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?D(E({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(r){this.loggingService.catch("Error in setApiKey: ",r)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(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)}}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)}}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;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let r=yield ez(()=>window.Velt.identify(e.user,E(E({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}),e.retryConfig||{retryCount:0,retryDelay:0});return r&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(Un.ERROR).pipe(Fe(a=>a.code==="token_expired"),ot(10)).subscribe(a=>Q(this,null,function*(){if(a.code==="token_expired"){let s=this.docService?.getDocumentIds()?.map(T=>({id:T.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,p=[],g=this.docService?.getLocation();g&&p.push(g.location);let f=this.docService?.getLocations();f&&Object.values(f).forEach(T=>{p.push(T.location)}),(yield ez(()=>Q(this,null,function*(){try{let T=yield e.generateToken?.();return T?window.Velt.identify(e.user,E(E({},e.options||{}),T&&{authToken:T}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:s,options:c,source:"internal"}),yield this.docService?.setLocations({locations:p,source:"internal",options:{appendLocation:!g}}))}}))),r}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return Q(this,null,function*(){try{if(e){let t=yield bl(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 j0(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}updateUserWithColorAndTextColor(e){return Q(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),r=yield this.getUserFromStorage(t);return!r||Object.keys(r).length===0?(delete t?.color,delete t?.textColor,t):(r?.color&&(t.color=r?.color),r?.textColor&&(t.textColor=r?.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);this.loggingService.debugAuth("updateUserIfRequired currentUser",t&&typeof t=="object"?JSON.parse(JSON.stringify(t)):t),this.loggingService.debugAuth("updateUserIfRequired user",e&&typeof e=="object"?JSON.parse(JSON.stringify(e)):e);let r={};if(e.color&&e.color!==t?.color&&(r.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(r.textColor=e.textColor),this.loggingService.debugAuth("updateUserIfRequired fieldsToUpdate",r&&typeof r=="object"?JSON.parse(JSON.stringify(r)):r),Object.keys(r).length>0&&e.organizationId){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));ad({data:{type:"addUserInfoToOrganization",metadata:{organizationId:e.clientOrganizationId},user:D(E({},r),{userId:e.userId})},getSdkProxy:a,userId:e?.userId??""})}}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,r,a,s){return Q(this,null,function*(){try{if(this.loggingService.logPerf(`[PERF] identify() called at ${performance.now().toFixed(2)}ms`),this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=s;else{e.userSnippylyId=z0(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=r;let c=yield ei(this.afAuth).pipe(ot(1)).toPromise().catch(g=>null),p=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let g=yield ap(c,!0).catch(T=>null);if(!g)return;let{user:f,firebaseConfig:I}=g.claims;if(c?.uid!==e?.userSnippylyId||e?.groupId!==f?.groupId||e?.organizationId!==f?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,I)||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");else{this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user");let T=yield ap(c,!0).catch(J=>null);if(!T)return;let{firebaseConfig:N,user:G,advancedQueries:z}=T.claims;yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(N),this.setAdvancedQueries(z),G&&(this.providedUser.isAdmin=!!G.isAdmin),this.initializeSignedInUser(c,a,e),p=!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:s})}}if(p){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:s},!0,e.userSnippylyId,e.userId);let g=Ki(this.functions,Zi({url:Dn.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),f=ga(),I=performance.now();this.loggingService.logPerf(`[PERF] validateClient() started at ${I.toFixed(2)}ms`);let T=(yield g({apiKey:this.apiKey,user:e,version:f,authToken:t?.authToken}))?.data;if(this.loggingService.logPerf(`[PERF] validateClient() completed in ${(performance.now()-I).toFixed(2)}ms`),T.error){if(this.analyticsService.trackEvent(K.Events.Core.SDK_VALIDATE_CLIENT_FAILED,D(E({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:T.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},T),{source:s}),!0,e.userSnippylyId,e.userId),T.error&&typeof T.error=="string")if(T.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let N={code:"token_expired",message:"Token expired",error:T?.error,source:T?.source};this.coreActionsService.triggerAction(Un.ERROR,N)}else{let N={code:"too_many_retries",message:"Token expired. Too many retries.",error:T?.error,source:T?.source};this.coreActionsService.triggerAction(Un.ERROR,N),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:s},!0,e.userSnippylyId,e.userId)}else{let N=T;this.coreActionsService.triggerAction(Un.ERROR,N)}throw T}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:s},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),T.firebaseConfig){this.setFirebaseConfig(T.firebaseConfig),yield this.signInWithCustomToken(e,T.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let N=yield ap(this.afAuth.currentUser,!0).catch(J=>null);if(!N)return;let{user:G,advancedQueries:z}=N.claims;this.setAdvancedQueries(z),this.providedUser.isAdmin=!!G?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:r,autoLogin:a},this.checkForPendingLogin()}return e}catch(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=ga();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=ga();if(e){let t=e.split("."),r=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),s=parseInt(t[2]||"0");if(r>=4&&a>=5)return r===4&&a===5&&s===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(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(r=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),r=!1;try{let a=localStorage.getItem(U.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(r=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!r)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(r){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",r),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:E(E({},Dn.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 gn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(de(()=>this.getAdvancedQueriesEnabled()),zn(()=>se(!1)))}getAdvancedQueriesEnabled(){try{return!this.configService.getConfig()?.advancedQueriesDisabled&&!!this.getAdvancedQueries()?.advancedQueriesEnabled}catch(e){return this.loggingService.catch("Error in getAdvancedQueriesEnabled: ",e),!1}}signOutPreviousUser(){return this.signOutPreviousUser$.asObservable()}getUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.afAuth?.currentUser?this.user$.value:null}getUser$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUser$","color: green;"),ei(this.afAuth).pipe(he(e=>e?this.user$.asObservable():se(null)),vt(Kt))}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=E(E({},this.providedUser),e),t){let r=E(E({},t),e);this.updateUserInternally(r)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,r="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return nie(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:r,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:r,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.commonDbService?.unsubscribeFromObservables(),this.docService?.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,r){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new Bo;a.userSnippylyId=e.uid,a.type="signedIn",r&&(a=E(E({},a),r)),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 r=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0});a&&a[e.userId]&&(r=JSON.parse(JSON.stringify(a[e.userId]||{}))),e=E(E({},e),r||{})}e.name=r?r?.name:this.providedUser?.name||e.name,e.clientUserName=r?r?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=r?r?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=r?r?.email:this.providedUser?.email||e.email,e.color=r?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=r?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=r?.initial||this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(r){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",r)}})}updateUserInternally(e){return 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();try{if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let r=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:Mo.ORGANIZATION,source:Ir.IDENTIFY,organizationId:e.clientOrganizationId}}],a=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.IDENTIFY,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:r}}),yield this.userPermissionService?.onResourceAccessRequired({requests:r,uniqueId:a,userId:e.userId,methodName:Ir.IDENTIFY,fromCache:!1})}}catch(r){this.loggingService.catch("Error in updateUserInternally: ",r)}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)),r=D(E({},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 Ki(this.functions,Zi({url:Dn.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:ga(),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(Fe(e=>!!e),de(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreSignOutFuction: ",r)}}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(he(e=>e?this.userOrganization$.asObservable().pipe(de(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return Q(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),yield 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 ei(this.afAuth).pipe(ot(1)).toPromise().catch(r=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[r,a]of this.preSignOutFunctions)try{yield a(t)}catch(s){this.loggingService.catch(`Error in signOutUser ${r} function: `,s)}return this.user$.next(null),yield nm(1e3),iie(this.afAuth).catch(r=>{this.loggingService.catch("Error in signOutUser:",r)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return eo(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 Qr(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Rn(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)(ee(Ai),ee(Rt),ee(cm),ee(ts),ee(Le),ee(Io),ee(et),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var dm=class{constructor({apiKey:o,documentId:n,organizationId:e,folderId:t,veltFolderId:r,clientDocumentId:a,clientOrganizationId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.folderId=t,this.veltFolderId=r,this.clientDocumentId=a,this.clientOrganizationId=s,a&&(this.documentId=br(a)),s&&(this.organizationId=Qa(s)),t&&(this.folderId=t,this.veltFolderId=Ui(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 nR=class{constructor({apiKey:o,documentId:n,organizationId:e,clientDocumentId:t,clientOrganizationId:r,folderId:a,veltFolderId:s}){this.paths={},this.apiKey=o,this.documentId=n,this.organizationId=e,this.veltFolderId=s,t&&(this.documentId=br(t)),r&&(this.organizationId=Qa(r)),a&&(this.folderId=a,this.veltFolderId=Ui(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.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.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var iR=class{};var bn=(()=>{let o=class o{constructor(e,t){this.authService=e,this.loggingService=t,this.db$=new ve(null);try{this.authService.getFirebaseConfig$().subscribe(r=>{r&&this.db$.next(dM(void 0,r.firebaseOptions.databaseURL))},r=>{this.loggingService.catch("Error in DatabaseService constructor: ",r)})}catch(r){this.loggingService.catch("Error in DatabaseService constructor:",r)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ys=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.commentAnnotationById$=new ve({}),this.fieldsToRemove=[],this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Comment annotation resolution timeout")))},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return s(),c({});let f={},I=[...new Set(e.commentAnnotationIds||[])],T=D(E({},e),{commentAnnotationIds:I});Q(this,null,function*(){try{if(I.length>0||e.documentIds?.length||e.folderId){let G=rd(()=>g?.get(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(z=>r?{}:(s(),z&&z.statusCode!==200?(this.loggingService.catch(z?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):z?.data)).catch(z=>{throw s(),z});try{f=(yield G)||{},this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:I});let z={};Object.entries(f).forEach(([J,ce])=>{let ye=this.commentAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ce)&&(z[J]=ce):z[J]=ce}),Object.keys(z).length>0&&this.commentAnnotationById$.next(E(E({},this.commentAnnotationById$.getValue()),z)),c(z)}catch(z){r||p(z),c(f)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",t),{}}})}saveCommentAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let t=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=E(E({},r),e.commentAnnotation);let a=yield rd(()=>t?.save({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0),"saveCommentAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=r),this.loggingService.catch(a?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(t){return this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),s=E({},a);delete s?.[e],this.commentAnnotationById$._value=s;let c=yield rd(()=>r?.delete({commentAnnotationId:e.toString(),metadata:t,event:Oa.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0),"deleteCommentAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[e]:void 0}catch(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}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(e)}}catch(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)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var mm=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,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 ve(null),this.reactionAnnotationById$=new ve({}),this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let t,r=!1,a=!1,s=()=>{t&&(clearTimeout(t),t=void 0,a=!0)};return new Promise((c,p)=>{t=setTimeout(()=>{a||(r=!0,s(),p(new Error("Reaction annotation resolution timeout")))},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return s(),c({});let f={},I=[...new Set(e.reactionAnnotationIds||[])],T=D(E({},e),{reactionAnnotationIds:I});Q(this,null,function*(){try{if(I.length>0||e.documentIds?.length||e.folderId){let G=rd(()=>g?.get(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(z=>r?{}:(s(),z&&z.statusCode!==200?(this.loggingService.catch(z?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):z?.data)).catch(z=>{throw s(),z});try{f=(yield G)||{},this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:I});let z={};Object.entries(f).forEach(([J,ce])=>{let ye=this.reactionAnnotationById$.value?.[J];ye?ye&&JSON.stringify(ye)!==JSON.stringify(ce)&&(z[J]=ce):z[J]=ce}),Object.keys(z).length>0&&this.reactionAnnotationById$.next(E(E({},this.reactionAnnotationById$.getValue()),z)),c(z)}catch(z){r||p(z),c(f)}}else s(),c({})}catch(G){s(),p(G)}})})}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",t),{}}})}saveReactionAnnotation(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let t=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=E(E({},r),e);let a={reactionAnnotation:e,event:Oa.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},s=yield rd(()=>t?.save(a)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=r),this.loggingService.catch(s?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:a.event}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(t){return this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",t),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=E({},a);delete s?.[e],this.reactionAnnotationById$._value=s;let c=yield rd(()=>r?.delete({reactionAnnotationId:e.toString(),metadata:t,event:Oa.REACTION_DELETE})||Promise.resolve(void 0),"deleteReactionAnnotation",this.retryDeleteConfig);return c&&c.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){return this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",t);return}}setReactionAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting reaction annotation data provider");let r=["get","save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(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)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var rt=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.analyticsService=e,this.authService=t,this.databaseService=r,this.domService=a,this.configService=s,this.loggingService=c,this.commentResolverService=p,this.reactionResolverService=g,this.coreActionsService=f,this.functions=I,this.documentPaths$=new ve(null),this.docContext$=new ve(null),this.documentIds$=new ve([]),this.organizationConfig$=new ve(null),this.firestorePaths$=new ve(null),this.location$=new ve(null),this.excludedLocationIds$=new ve([]),this.organizationMetadata$=new ve(null),this.documentMetadata$=new ve(null),this.locationMetadata$=new ve(null),this.customerMetadata$=new ve(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new ve({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new ve({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new tt,this.DEBOUNCE_TIME=5e3,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,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(jo(this.DEBOUNCE_TIME)).subscribe({next:T=>Q(this,null,function*(){try{yield this.setDocumentIdImpl(T.documentId,T.clientOrganizationId,T.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:T=>{this.loggingService.catch("Error in setDocumentId subscription:",T),this.queueSize--}}),this.databaseService.getDb().pipe(Fe(T=>!!T),ot(1)).subscribe(T=>{T&&(this.db=T)}),this.configService.getApiKey$().subscribe(T=>{if(this.apiKey=T,this.apiKey){if(!this.isCustomDocId){let N=xk(window.location.href);this.currentUrl=N}this.analyticsService.updateDefaultProperties({apiKey:T})}}),this.authService.getUser$().subscribe(T=>Q(this,null,function*(){if(T&&(this.analyticsService.updateDefaultProperties({organizationId:T?.organizationId,clientOrganizationId:T?.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&&T?.organizationId&&this.documentPaths$.value?.organizationId!==T?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(N=>({id:N.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),T?.organizationId&&T?.clientOrganizationId)){let N={organizationId:T?.organizationId,clientOrganizationId:T?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:T?.organizationId,clientOrganizationId:T?.clientOrganizationId}),yield this.updateOrganizationMetadata(N)}})),this.documentPaths$.subscribe(T=>{let N={documentId:T?.documentId,clientDocumentId:T?.clientDocumentId,folderId:T?.folderId,allDocuments:T?.allDocuments,veltFolderId:T?.veltFolderId};T?.organizationId&&(N.organizationId=T.organizationId,N.clientOrganizationId=T.clientOrganizationId),this.analyticsService.updateDefaultProperties(N),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(T=>{this.analyticsService.updateDefaultProperties({clientLocation:T?.location,locationId:T?.locationId})}),this.organizationMetadata$.subscribe(T=>{this.authService.setUserOrganization(T?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Fe(T=>!!T),ot(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(T){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",T)}},T=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",T)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(T){this.loggingService.catch("Error in DocService constructor:",T)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,organizationId:this.documentPaths$.value?.clientOrganizationId}: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.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)}}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=xk(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=xk(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(s){return Q(this,arguments,function*({documentId:e,documentMetadata:t,options:r,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(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocument",source:a,payload:{documentId:e,documentMetadata:t,options:r}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:E({organizationId:t?.organizationId},r??{}),source:a})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(e,t={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let r=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,s=this.documentIds$.value.map(g=>g.clientDocumentId),c=GH(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(g=>s.includes(g.id))||!gi(c,t)||r!==a}catch(r){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",r),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let r=[];return e.forEach(a=>{let s=a.id,c=`${Rn(s)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[s]=a.metadata),r.push({documentId:c,clientDocumentId:s})}),r}catch(r){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",r),[]}}setDocuments(s){return Q(this,arguments,function*({documents:e,options:t,source:r="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocuments",source:r,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:r,skipPermissionValidation:a})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(r){return Q(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:"setRootDocument",source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},s=this.documentIds$.value.map(c=>c.clientDocumentId);if(!s.includes(e.id)){let c=[...s.map(g=>({id:g})),{id:e.id}],p=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(p)}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()}getProcessedDocContext(){return Xle(this.getDocContext())}filterRelevantDocuments(a){return Q(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:r=!1}){try{let s=this.authService.getUser();return!s||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,s),yield this.handlePermissionProvider(e,t,s),t=yield this.filterDocumentsByPermissions(e,t,s,r),t=t.slice(0,50)),t}catch(s){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",s),t}})}fetchDocumentsFromFolder(e,t,r){return Q(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield ad({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??r?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:r?.userId??""}))?.data?.data?.forEach(c=>{t.find(p=>p.clientDocumentId===c.id)||t.push({documentId:br(c.id),clientDocumentId:c.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,r){try{let a=[];return e.organizationId&&e.organizationId!==r.clientOrganizationId&&a.push({userId:r.userId,resource:{id:e.organizationId,type:Mo.ORGANIZATION,source:Ir.SET_DOCUMENTS,organizationId:e.organizationId}}),e.folderId&&a.push({userId:r.userId,resource:{id:e.folderId,type:Mo.FOLDER,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??""}}),t&&t.forEach(s=>{a.push({userId:r.userId,resource:{id:s.clientDocumentId,type:Mo.DOCUMENT,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??""}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&Jle({input:e?.context}).forEach(c=>{let p=JSON.stringify(c.access);a.push({userId:r.userId,resource:{id:p,type:Mo.CONTEXT,source:Ir.SET_DOCUMENTS,organizationId:e?.organizationId??r?.clientOrganizationId??"",context:c}})}),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 r=e.data.filter(a=>a.type===Mo.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(r?.length){let a=t.filter(c=>r.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),s=ece({input:a});s?.access&&this.setDocContext(s)}}catch(r){this.loggingService.catch("Error in processAccessibleContexts:",r)}}handlePermissionProvider(e,t,r){return Q(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{let a=this.buildPermissionRequests(e,t,r),s=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.SET_DOCUMENTS,uniqueId:s,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}});let c=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:s,methodName:Ir.SET_DOCUMENTS,fromCache:!1});this.processAccessibleContexts(c,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,r,a=!1){return Q(this,null,function*(){if(a)return t;let s=this.currentValidationToken,c=[...t];return s&&this.validatePermissionsInBackground(e,t,r,s),c})}validatePermissionsInBackground(e,t,r,a){this.userPermissionService?.getUserPermissions({organizationId:e?.organizationId??r?.clientOrganizationId,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let c=[];Object.entries(s?.[r.userId]?.documents??{}).forEach(([p,g])=>{g?.errorCode===Wo.PERMISSION_DENIED&&c.push(p)}),c.length>0&&this.handleDeniedDocumentAccess(c,r,a)}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,r){try{if(this.currentValidationToken!==r)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(Un.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 s=this.documentIds$.value||[],c=s.filter(p=>!e.includes(p.clientDocumentId));c.length!==s.length&&(c.length>0?this.setDocuments({documents:c.map(p=>({id:p.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(Un.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(r){return Q(this,arguments,function*({organizationId:e,user:t}){try{let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield ad({data:{type:"addUserInfoToOrganization",metadata:{organizationId:e},user:t},getSdkProxy:a,userId:t?.userId??""})}catch(a){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",a)}})}setDocumentsImpl(s){return Q(this,arguments,function*({documents:e,options:t,source:r,skipPermissionValidation:a=!1}){try{let c=t?.organizationId??this.documentPaths$.value?.clientOrganizationId;if(!this.shouldSetDocumentsAgain(e,GH(D(E({},t),{organizationId:c})))){r==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let p=on();this.currentValidationToken=p;let g=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(g?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let f=this.authService.getUser();if(!f){this.draftDocuments=e,this.draftOptions=t;return}if(this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1}),this.addUserInfoToOrganization({organizationId:t?.organizationId??f?.clientOrganizationId??"",user:f}),g=yield this.filterRelevantDocuments({options:t,documentIds:g,skipPermissionValidation:a}),this.documentIds$.next(g),g?.length){let I=g[0]?.clientDocumentId;t?.rootDocumentId&&g.find(T=>T.clientDocumentId===t?.rootDocumentId)&&(I=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:I,clientOrganizationId:t?.organizationId,options:t})}return}catch(c){this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:"setDocumentId",source:r,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:r})}catch(s){this.loggingService.catch("Error in setDocumentId:",s);return}})}debounceSetDocuments(a){return Q(this,arguments,function*({documentId:e,clientOrganizationId:t,options:r}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let s=Date.now(),c=s-this.lastSetDocumentIdCallTime,p=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||c>this.DEBOUNCE_TIME&&p>this.DEBOUNCE_TIME){yield this.setDocumentIdImpl(e,t,r),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:r??void 0});return}catch(s){this.loggingService.catch("Error in debounceSetDocuments:",s)}})}setDocumentIdImpl(e,t,r){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 s=this.currentDocumentId;if(this.apiKey){let c=`${Rn(e)}`,p=r?.folderId,g=r?.folderId?Ui(r?.folderId):void 0,f=r?.locationId,I=r?.allDocuments,T=a?.organizationId?t?Et(t):a?.organizationId:void 0;if(yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({documentIds:this.documentIds$.value.map(N=>N.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}),this.reactionResolverService.resolveReactionAnnotations({documentIds:this.documentIds$.value.map(N=>N.clientDocumentId),organizationId:t??a?.clientOrganizationId??""})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==T){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let N=new j9,G=new iR;N.clientDocumentId=e,G.clientDocumentId=e,N.folderId=p,G.folderId=p,N.locationId=f,G.locationId=f,N.allDocuments=I,G.allDocuments=I,N.veltFolderId=g,G.veltFolderId=g,N.documentId=c,G.documentId=c,T&&(N.organizationId=T,N.clientOrganizationId=t??a?.clientOrganizationId,G.organizationId=T,G.clientOrganizationId=t??a?.clientOrganizationId);let z=`${this.apiKey}`,J=`apiKey/${this.apiKey}`;T&&(z=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${N.organizationId}`,J=`${J}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${N.organizationId}`),G.organization=`apiKey/${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,G.document=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}`,N.presence=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_PRESENCE}/`,N.cursor=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CURSOR}/`,N.comment=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_COMMENT}/`,G.comment=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_COMMENT}`,N.multiThread=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,G.multiThread=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,N.tag=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_TAG}/`,N.area=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AREA}/`,G.area=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AREA}`,N.arrow=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_ARROW}/`,N.selection=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_SELECTION}/`,N.audioHuddle=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,N.huddle=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_HUDDLE}/`,N.recorder=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_RECORDER}/`,G.recorder=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_RECORDER}`,N.flock=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,N.syncVideoPlayer=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,N.liveState=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,N.liveStateSingleEditorMode=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,N.reaction=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_REACTION}/`,G.reaction=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_REACTION}`,N.crdt=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CRDT}/`,G.crdt=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_CRDT}`,N.customerMetadata=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,N.views=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_VIEWS}/`,G.notificationViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,G.documentViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,G.locationViews=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,N.notifications=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,N.metadata=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_METADATA}/`,N.users=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,N.documentIam=`${z}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.workspaceIam=`${this.apiKey}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.groupContacts=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GROUPS}/`,N.globalContacts=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_GLOBAL}/`,N.logins=`${z}/${U.FIREBASE_PARTIAL_PATH_CONTACTS}/${U.FIREBASE_PARTIAL_PATH_LOGINS}/`,N.userFeedback=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,N.userReportBugs=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_BUGS}/`,N.userContactUs=`${z}/${U.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${U.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,T&&(N.organizationMetadata=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,N.organizationIam=`${z}/${U.FIREBASE_PARTIAL_PATH_IAM}/`,N.organizationGroups=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,N.organizationNotifications=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(N.organizationNotificationsWithDocumentId=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,N.heartbeatByDocument=`${z}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),N.organizationNotificationsLastNotificationTimestamp=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${U.FIREBASE_PARTIAL_PATH_DOCS}/`,N.organizationNotificationsUsers=`${z}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${U.FIREBASE_PARTIAL_PATH_USERS}/`,N.heartbeat=`${z}/${U.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),G.organizationUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,G.users=`${J}/${U.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,G.documentUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${U.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,G.notificationDocs=`${J}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,G.notificationUsers=`${J}/${U.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,!this.documentPaths$.value&&this.loggingService.logPerf(`[PERF] documentPaths$ FIRST SET at ${performance.now().toFixed(2)}ms`),this.documentPaths$.next(N),this.firestorePaths$.next(G),N?.clientOrganizationId&&N?.organizationId&&!(N?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&N?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:N?.organizationId,clientOrganizationId:N?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),s&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:e}}),this.analyticsService.trackEvent(K.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,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(Un.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:"unsetDocumentId",source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocumentId: ",r)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),this.userPermissionService?.revokeAccessOnDocumentUnset(),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.clientDocumentMetadata=void 0,this.clientDocumentMetadataMap={},this.locations$.next({}),this.documentIds$.next([]),this.coreActionsService.triggerAction(Un.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(r){this.loggingService.catch("Error in unsetDocumentImpl: ",r)}}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(Un.INIT_UPDATE,{event:K.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:"unsetDocuments"}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(r){this.loggingService.catch("Error in unsetDocuments: ",r)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(r){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",r)}}callPreDocumentIdChangeFunctions(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,r]of this.preDocumentIdChangeFunctions)try{yield r(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(r=>{r&&!r?.errorCode&&this.organizationMetadata$.next(D(E({},this.organizationMetadata$.value),{[t]:r}))}).catch(r=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",r)})}}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,r=this.documentMetadata$.value;if(e=e.filter(a=>!r?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,s=[],c={organizationId:t?.clientOrganizationId,folderId:a},p=[],g=20;for(let I=0;I<e.length;I+=g)p.push(e.slice(I,I+g));p.forEach(I=>{let T=JSON.parse(JSON.stringify(c));T.documentIds=I.map(N=>N.clientDocumentId),s.push(this.fetchDocuments(T))});let f={};s.length>0&&(yield Promise.all(s).then(I=>{I?.forEach(T=>{T?.forEach(N=>{N?.metadata?.documentId&&(f[N.metadata.documentId]=N.metadata)})}),this.setAllDocumentMetadata(E(E({},this.documentMetadata$.value),f))}).catch(I=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",I)}))}else r?.[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,r=e?.folderId,a=e?.allDocuments,s=[],c={organizationId:e?.clientOrganizationId,folderId:r,allDocuments:a},p=[],g=20;for(let I=0;I<t.length;I+=g)p.push(t.slice(I,I+g));p.forEach(I=>{let T=JSON.parse(JSON.stringify(c));T.documentIds=I.map(N=>N.clientDocumentId),s.push(this.fetchLocations(T))});let f=this.locationMetadata$.value??{};s.length>0&&Promise.all(s).then(I=>{I?.forEach(T=>{T?.forEach(N=>{N?.metadata?.documentId&&(f[N.metadata.documentId]=D(E({},f?.[N.metadata.documentId]??{}),{[N.location.id]:N}))})}),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}).catch(I=>{this.loggingService.catch("Error in fetchLocationMetadata: ",I)})}}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(zn(t=>se(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(de(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`${Rn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${Et(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(r){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(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:"setLocation",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:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),r==="internal"&&this.analyticsService.trackEvent(K.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:r}}),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"setLocations",source:r,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(s){this.loggingService.catch("Error in setLocations: ",s)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(r=>{if(r&&typeof r=="object"){let a=!0;r?.version&&(!r?.version?.id||!r?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${r?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(r)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(r){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(Un.INIT_UPDATE,{event:K.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:"setRootLocation",source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(s=>s.location).filter(s=>String(s.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=D(E(E({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=E(E({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),s=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(f=>f.location.id)].filter(f=>f!==void 0);let p;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(p=a.find(f=>f.id===t?.rootLocationId),!p)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(p){let f=er(p),I=Rn(JSON.stringify(f));f.id&&s.push({locationId:I,location:f}),this.location$.next({locationId:I,location:f})}}else{p||(p=a[0]);let f=er(p),I=Rn(JSON.stringify(f));f.id&&s.push({locationId:I,location:f}),this.location$.next({locationId:I,location:f})}let g=[];return a.slice(t?.appendLocation?0:1).forEach(f=>{if(f.id!==this.location$.value?.location.id){let I=E({},f),T=this.locations$.value;f?.id&&Object.keys(T).forEach(J=>{let ce=T[J];ce.location?.id===f.id&&(I=E(E({},ce.location),f),delete T?.[J])});let N=this.genarateLocationId(I),G={locationId:N,location:I};I.id&&s.push({locationId:N,location:I}),g.push(G);let z=D(E({},T),{[N]:G});this.locations$.next(z)}}),this.updateDocumentLocationMetadata(s),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:"setLocations",payload:{locations:a,options:t}}),this.analyticsService.trackEvent(K.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),g}catch(r){this.loggingService.catch("Error in setLocationImpl: ",r);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(Un.INIT_UPDATE,{event:K.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:"addLocation",source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(r){this.loggingService.catch("Error in DocService addLocation:",r);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(Un.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:"removeLocation",payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(r){this.loggingService.catch("Error in removeLocation: ",r)}}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(Un.INIT_UPDATE,{event:K.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:"removeLocations",source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(r){this.loggingService.catch("Error in removeLocations: ",r)}}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(r=>{let a=this.genarateLocationId(r);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==r.id))),this.removeCustomLocation(r)}):(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(r){this.loggingService.catch("Error in removeLocation: ",r)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:"unsetLocationIds",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(r=>{this.getLocation()?.location.id===r&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==r))),this.removeCustomLocationId(r)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(Un.INIT_UPDATE,{event:K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:"removeLocationsSuccess",source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(K.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(r){this.loggingService.catch("Error in unsetLocationIds: ",r)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(e){return Q(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,r=this.documentPaths$.value;if(this.db&&t&&r?.documentId){if(this.organizationMetadata$.value?.[t])return;let s=new Q9;s.apiKey=this.configService?.getApiKey()??"",s.organizationId=t,s.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:t,documentId:r?.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 r={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield ad({methodName:"createFolder",data:{type:"createFolder",metadata:r},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 r=t.map(a=>Q(this,null,function*(){let s=new U9;this.clientDocumentMetadata&&(this.clientDocumentMetadata?.clientDocumentId===e.clientDocumentId&&this.clientDocumentMetadata?.documentMetadata&&(s=E(E({},this.clientDocumentMetadata.documentMetadata),s)),this.clientDocumentMetadata=void 0),this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(s=E(E({},this.clientDocumentMetadataMap[a.clientDocumentId]),s)),s.apiKey=this.configService?.getApiKey()??"",s.documentId=a.documentId,s.clientDocumentId=a.clientDocumentId,s.organizationId=e.organizationId,s.clientOrganizationId=e.clientOrganizationId,s.pageInfo=Mi();let c=e?.folderId,p=e?.veltFolderId;s?.pageInfo?.deviceInfo&&delete s?.pageInfo?.deviceInfo;let g=!0,f=this.documentMetadata$.value?.[a.documentId];if(c&&p){let I=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));I?.clientDocumentId&&!I?.errorCode?I?.folderId&&(I?.folderId!==c||I?.veltFolderId!==p)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),g=!1):I?.folderId===c?(c&&(s.folderId=c),p&&(s.veltFolderId=p)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),g=!1):(c&&(s.folderId=c),p&&(s.veltFolderId=p))}if(f){let I={};Object.entries(s).forEach(([T,N])=>{I[T]=N}),gi(I,f)&&(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(s)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(r),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 r=this.getDocumentIds();r.find(a=>a.documentId===t.documentId)||r.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of r){let s=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});s?.errorCode&&(s={});let c=[];for(let p of e){let g=new G9;g.locationId=p?.locationId,g.veltLocationId=jH(p?.location?.id??""),g.location=p?.location,g.pageInfo=Mi(),g?.pageInfo?.deviceInfo&&delete g?.pageInfo?.deviceInfo;let f=D(E({},s),{[U.FIREBASE_PARTIAL_PATH_LOCATIONS]:D(E({},s[U.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[p?.locationId]:g})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(f)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let I=this.locationMetadata$.value;if(I||(I={}),p?.location?.id){let T=I?.[a.documentId],N=T?.[p?.location?.id??""];I&&(T||(I[a.documentId]={}),N||(I[a.documentId][p?.location?.id??""]={}),I[a.documentId][p?.location?.id??""]=D(E({},N),{location:p?.location})),Object.keys(I||{}).length>0&&this.locationMetadata$.next(I)}}yield Promise.allSettled(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Rn(JSON.stringify(er(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let r=this.genarateLocationId(e),a=this.locations$.value;a[r]&&(delete a[r],this.locations$.next(E({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e.id)))}catch(r){this.loggingService.catch("Error in DocService removeLocation:",r)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let r=this.locations$.value;Object.entries(r).forEach(([a,s])=>{s.location.id===e&&(delete r[a],this.locations$.next(E({},r)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==e)))})}catch(r){this.loggingService.catch("Error in DocService removeCustomLocationId:",r)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let r=this.getLocations();Object.keys(r).forEach(a=>{let s=r[a];s.location?.id===e&&(t=s.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}]`),r=[];t.forEach(a=>{let s=a.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(s){let c=JSON.parse(s),p=this.genarateLocationId(c);r.push(p)}}),Object.keys(e).forEach(a=>{let s=e[a];r.includes(s.locationId)||delete e[a]}),this.locations$.next(E({},e))}catch(e){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",e)}}getLocations$(){try{return this.locations$.asObservable()}catch(e){return this.loggingService.catch("Error in DocService getLocations$:",e),se({})}}getLocations(){try{return this.locations$.value}catch(e){return this.loggingService.catch("Error in DocService getLocations:",e),{}}}getLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let t=null;if(e?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${U.ATTRIBUTES.VELT_LOCATION}]`),t){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r){let a=JSON.parse(r);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(r=>{if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(r);a?.locationId&&(e[a.locationId]={element:r,location:a})}else if(r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let a=r.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(a){let s=this.getLocationByClientLocationId(a);s?.locationId&&(e[s.locationId]={element:r,location:s});let c={id:a},p=this.genarateLocationId(c);e[a]={element:r,location:{locationId:p,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${U.ATTRIBUTES.VELT_LOCATION}], [${U.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION)){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION);if(r)return JSON.parse(r)}else if(t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID)){let r=t?.getAttribute(U.ATTRIBUTES.VELT_LOCATION_ID);if(r)return{id:r}}}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(de(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),vt(Kt))}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(de(e=>e||{}),vt(Kt))}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={},r=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(r&&a)Object.values(e).forEach(s=>{s?.documentId&&s?.veltFolderId===r&&(t[s.documentId]=s)});else{let s=this.documentIds$.value;if(s?.length)s.forEach(c=>{let p=e?.[c.documentId];p&&(t[c.documentId]=p)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(de(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),vt(Kt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let r=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));r[e]=t,this.documentMetadata$.next(r)}catch(r){this.loggingService.catch("Error in DocService setDocumentMetadata:",r)}}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(de(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(de(e=>e||{}),vt(Kt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(vt(Kt))}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(r){this.loggingService.catch("Error in DocService getMetadataFromType:",r);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let r=this.documentPaths$.value;if(!r)return;let a=e||r.clientDocumentId,s=t||r.documentId,c=this.getDocumentMetadata(s);if(!c)return;let p=c?.folderId,g=c?.veltFolderId;return E(E({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:r.clientOrganizationId,documentId:s,organizationId:r.organizationId},p?{folderId:p}:{}),g?{veltFolderId:g}:{})}catch(r){this.loggingService.catch("Error in DocService getDefaultMetadata:",r);return}}getBaseMetadata(e,t){try{let r,a;t?.element?r=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(r=t.clientDocumentId),r&&(a=this.generateDocumentId(r));let s=this.getMetadataFromType(e,t),c=this.getDefaultMetadata({clientDocumentId:r,documentId:a});return s||c||{}}catch(r){return this.loggingService.catch("Error in DocService getBaseMetadata:",r),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(r){return this.loggingService.catch("Error in DocService getServerId:",r),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 r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let s=Ui(e?.folderId);r.push(ht("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(ht("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(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 r=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let s=Ui(e?.folderId);r.push(ht("metadata.veltFolderId","==",s))}return e?.documentIds?.length&&!e?.allDocuments&&r.push(ht("metadata.documentId","in",e?.documentIds?.map(s=>this.generateDocumentId(s)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:r,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(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:r,documents:a,folderId:s}=e;if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Qa(r);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let p=[],g=this.documentMetadata$.value??{};for(let f of a)if(f?.documentId){f.organizationId=c,f.clientOrganizationId=r,f.clientDocumentId=f.documentId;let I=br(f.documentId);f.documentId=I,f.apiKey=this.configService.getApiKey()??void 0,(s||this.documentPaths$.value?.folderId)&&(f.folderId=s||this.documentPaths$.value?.folderId,f.veltFolderId=Ui(s||this.documentPaths$.value?.folderId||""));let T=()=>{if(s&&this.documentPaths$.value?.folderId&&s!==this.documentPaths$.value?.folderId)return;let G=g?.[I];G?g[I]=E(E({},G),f):g[I]=f},N=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:I,organizationId:c,field:"metadata"}});if(N?.errorCode&&(N={}),N&&N.apiKey&&N.folderId&&s&&N.folderId!=f.folderId){this.loggingService.catch(`Error in updateDocuments: document ${f.clientDocumentId} already exists with different folderId: ${N.folderId}`);continue}if(N&&N.apiKey&&!N.folderId&&f.folderId){this.loggingService.catch(`Error in updateDocuments: document ${f.clientDocumentId} already exists, move this document to folder with REST API`);continue}T(),f&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:f?.documentId??""})&&p.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(f)),properties:{organizationId:c,documentId:I}}))}yield Promise.all(p),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:r,locations:a,documentIds:s}=e;if((!s||s.length===0)&&(s=this.documentIds$.value.map(f=>f.clientDocumentId)??[],s.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!r&&(r=this.documentPaths$.value?.clientOrganizationId,!r))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=s.map(f=>br(f)),p=[],g=this.locationMetadata$.value;g||(g={}),c.forEach(f=>{a.forEach(I=>{let T=this.location$.value;if(I?.id===T?.location?.id&&this.location$.next({locationId:T?.locationId,location:I}),I?.id){delete I?.metadata;let N=jH(I.id),G=g?.[f],z=G?.[I.id];g&&(G||(g[f]={}),z||(g[f][I.id]={}),g[f][I.id]=D(E({},z),{location:I})),I&&this.commonDbService&&p.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:I})),properties:{organizationId:Qa(r),documentId:f,id:N}}))}})}),yield Promise.all(p),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 r=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],s=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let c=Ui(e?.folderId);r=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}}),r&&(r=[r]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ht("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}})}else r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:s,documentId:this.documentPaths$.value?.documentId}});return{data:r,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(he(e=>e?this.documentPaths$.pipe(he(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(de(r=>r?.data?.docIamConfig??r?.data),vt((r,a)=>JSON.stringify(r??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?Ei.RESTRICTED:Ei.PUBLIC:e&&e.documentAccessType?e.documentAccessType:Ei.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),Ei.PUBLIC}}changeDocumentAccessType(e){return Q(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let r=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(r?.errorCode)return;switch(delete r.documentAccessType,r.features||(r.features={}),r.features.all||(r.features.all={}),e){case Ei.PUBLIC:r.features.all.restricted=!1;break;case Ei.RESTRICTED:r.features.all.restricted=!0,r.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(r)),properties:{documentId: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(E(E({},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)(ee(et),ee(Ue),ee(bn),ee(Le),ee(Rt),ee(y),ee(Ys),ee(mm),ee(ts),ee(Io))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Fn=(()=>{let o=class o{constructor(e,t,r,a){this.analyticsService=e,this.authService=t,this.docService=r,this.loggingService=a,this.resolveOrganizationUsers=new ve(!0),this.resolveFolderUsers=new ve(!0),this.resolveDocumentUsers=new ve(!0),this.unresolvedUsers=new ve([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Tn,this.userDataProvider$=new ve(null),this.userById$=new ve({}),this.userByIdCalled$=new ve({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(c){this.loggingService.catch("Error in UsersService getUserById:",c);return}};try{this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Fe(s=>!!s),he(()=>this.getUnresolvedUsers$().pipe(Fe(s=>s.length>0),jo(300),ot(20),he(s=>{let c=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:c,isCollection:!0,useQuery:!0,firestoreQuery:[_i(ht("user.userId","in",s.slice(0,20)))]}}).pipe(de(p=>p?.data),tn(p=>{if(p&&typeof p=="object"){delete p.undefined,delete p.null;let g=Object.values(p??{});this.setUserByIds(g.map(I=>I.user));let f=s.filter(I=>!g.some(T=>T.user.userId===I));f.length!==s.length&&this.setUnresolvedUsers(f)}})):se([])})))).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)}}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(r){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",r),!1}}resolveUsers(c){return Q(this,arguments,function*({userIds:e,forceResolve:t,feature:r,organizationId:a,skipUserCheck:s=!1}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let p=!1;if(r&&(p=this.isResolverForFeatureDisabled(r)),p)return{};{let g={},f=[],I={};if(e?.forEach(T=>{let N=this.getUserById(T);N?g[T]=N:this.userByIdCalled$.getValue()[T]?t&&f.push(T):(f.push(T),this.userByIdCalled$.next(D(E({},this.userByIdCalled$.getValue()),{[T]:!0})))}),f.length>0){let T={};try{let N,G=new Promise((z,J)=>{N=setTimeout(()=>{J(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});T=yield Promise.race([this.getUsersFromDB({userIds:f,organizationId:a,skipUserCheck:s}).finally(()=>{clearTimeout(N)}),G]),this.analyticsService.trackEvent(K.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:f})}catch(N){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",N,{userIds:f})}finally{f?.forEach(N=>{if(!T[N]){let G=new Set([...this.getUnresolvedUsers(),N]);this.unresolvedUsers.next(Array.from(G)),T[N]={userId:N,name:`User ${N}`}}})}Object.entries(T).forEach(([N,G])=>{G&&(g[N]=T?.[N],I[N]=T?.[N])})}return Object.keys(I).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(I)),this.userById$.next(E(E({},this.userById$.getValue()),I))),g}}catch(p){return this.loggingService.catch("Error in UsersService resolveUsers:",p),{}}})}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:r=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let s=this.userDataProvider$.getValue();if(s)return s.get(e);if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:r}))??[],p={};return c.forEach(g=>{g.forEach(f=>{f?.user?.userId&&(p[f.user.userId]=f.user)})}),p}catch(s){return this.loggingService.catch("Error in UsersService getUsersFromDB:",s),{}}})}getUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:r=!1}){try{if(!e?.length)return[];let s=[];for(let g=0;g<e.length;g+=30)s.push(e.slice(g,g+30));let c=s.map((g,f)=>Q(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ht("user.userId","in",g)],skipUserCheck:r}}))||[]}catch(I){return this.loggingService.catch(`Error in batch ${f+1}:`,I),[]}}));return yield Promise.all(c)}catch(s){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",s),[]}})}getTemporaryUsersFromDBWithBatching(a){return Q(this,arguments,function*({userIds:e,organizationId:t,resourceIds:r}){try{if(!e?.length||!r?.length)return[];let s=[];for(let G=0;G<e.length;G+=30)s.push(e.slice(G,G+30));let c=[];for(let G=0;G<r.length;G+=30)c.push(r.slice(G,G+30));let p=[],g=0,f=(G,z)=>Q(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_i(ht("userId","in",G),ht("veltResourceId","in",z))]}}))??[])||[]}catch(J){return this.loggingService.catch(`Error in batch ${g+1}:`,J),[]}});for(let G of s)for(let z of c)p.push(f(G,z)),g++;return(yield Promise.all(p)).flat().filter((G,z,J)=>z===J.findIndex(ce=>ce.userId===G.userId&&ce.resourceId===G.resourceId))}catch(s){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",s),[]}})}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(vt(Kt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),se({})}}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(r=>{t[r.userId]=E(E({},t?.[r.userId]??{}),r)}),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;"),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)}}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)(ee(et),ee(Ue),ee(rt),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var hpe=(()=>{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 r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var fpe=(()=>{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 r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var qg=class{static getFirestoreProdDbName(o,n){return n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(n){return nt.error("Error in isTestingDb:",n),!1}}};var Yg=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.attachmentDataProvider$=new ve(null);try{this.loggingService.log("AttachmentResolverService initialized"),this.attachmentDataProvider$.subscribe(r=>{r&&(r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig))})}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(){try{let e=this.attachmentDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}saveAttachment(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let t=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment save data provider not available");let r=yield rd(()=>t?.save({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0),"saveAttachment",this.retrySaveConfig);if(r?.statusCode!==200){this.loggingService.catch(r?.message??"Error in AttachmentResolverService saveAttachment:");return}return this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),r}catch(t){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",t);return}})}deleteAttachment(r){return Q(this,arguments,function*({attachmentId:e,metadata:t}){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let a=this.getProvider();if(!this.attachmentDataProviderAvailable())throw new Error("Attachment delete data provider not available");let s=yield rd(()=>a?.delete({attachmentId:e,metadata:t,event:Oa.ATTACHMENT_DELETE})||Promise.resolve(void 0),"deleteAttachment",this.retryDeleteConfig);return s?.statusCode!==200?(this.loggingService.catch(s?.message??"Error in AttachmentResolverService deleteAttachment:"),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(K.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){return this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",a),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e){try{if(e){this.loggingService.log("Setting attachment data provider");let r=["save","delete"].filter(a=>!(a in e)||typeof e[a]!="function");if(r.length>0){let a=`DataProviders.attachment is invalid. The following methods are missing or are not functions: ${r.join(", ")}.`;this.loggingService.catch(a);return}else this.attachmentDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",t)}}attachmentDataProviderAvailable(){try{return!!this.attachmentDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(et))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Kg=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.commentAnnotationsResolverService=c,this.attachmentResolverService=p,this.coreActionsService=g,this.notificationActionTypeMap={[$t.NEWLY_ADDED]:Oa.COMMENT_ANNOTATION_ADD,[$t.ADDED]:Oa.COMMENT_ADD,[$t.UPDATED]:Oa.COMMENT_UPDATE,[$t.DELETED]:Oa.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 r of e){if(r?.from?.userId&&t.add(r?.from?.userId),r?.comments)for(let a of r?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let s of a?.to)s?.userId&&t.add(s?.userId);if(a?.taggedUserContacts)for(let s of a?.taggedUserContacts)s?.userId&&t.add(s?.userId)}if(r?.assignedTo?.userId&&t.add(r?.assignedTo?.userId),r?.subscribedUsers)for(let a of Object.values(r?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(r?.unsubscribedUsers)for(let a of Object.values(r?.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 s=this.usersService.getUserById(a?.userId);if(s)return E(E({},a),s)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let s=this.usersService.getUserById(a?.contact?.userId);s&&(a.contact=s,(s?.name||s?.email)&&(a.text=`@${s?.name||s?.email}`))}return a})),(t?.taggedUserContacts?.filter((a,s,c)=>c.findIndex(p=>p.text===a.text)===s)||[]).forEach(a=>{if(a?.text){let s=new RegExp(id(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(s=new RegExp(id(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(s,a.text),t.commentHtml=t.commentHtml?.replaceAll(s,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=r)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let r=this.usersService.getUserById(t.user.userId);r&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=r)}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?.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),r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(s=>{let c=t?.comments?.[s?.commentId];if(c){s.commentHtml=c?.commentHtml,s.commentText=c?.commentText;let p=c?.attachments;r&&p&&s.attachments?.forEach(g=>{let f=g?.attachmentId;p?.[f]&&(g.name=p?.[f]?.name,g.url=p?.[f]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(s=>{t?.[s]&&(e[s]=t[s])})),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 r=e?.location?.id,a=e?.metadata?.documentId;if(!r||!a)return e;let s=t?.[a]?.[r];return s&&(e.location=s?.location),e}catch(r){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",r),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let r=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return r?!gi(e,r):!0}catch(r){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",r),!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 r=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new dd;if(Object.assign(a,e),a.isCommentResolverUsed=t,r){let s=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));a.attachments=s}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}stripCommentAnnotationData({data:e,actionType:t,commentId:r}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),c;t&&(c=this.notificationActionTypeMap?.[t]);let p={},g=null,f=!1;if(e&&e.annotationId){let T=e.annotationId;p[T]=E(E(E(E({annotationId:T,metadata:Y0(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(G=>{e?.[G]&&(p[T][G]=e[G],delete e[G])}),e.comments?.forEach(G=>{if(G.commentId){let z;a&&(z={},G.attachments?.forEach(J=>{z[J.attachmentId]={attachmentId:J.attachmentId,name:J.name,url:J.url}})),p[T].comments[G.commentId]=E(E(E(E(E(E({commentId:G.commentId},G?.commentHtml&&{commentHtml:G?.commentHtml}),G?.commentText&&{commentText:G?.commentText}),z&&{attachments:z}),G?.from&&{from:G?.from}),G?.to&&{to:G?.to}),G?.taggedUserContacts&&{taggedUserContacts:G?.taggedUserContacts})}}),f=this.isCommentsDataChanged(p[T],T);let N=new Go;Object.assign(N,e),N.comments=e.comments?.map(G=>this.stripCommentsFromAnnotationData({comment:G}))||[],g=N}let I=g?.comments?.find(T=>T.commentId===r);return I?.isDraft&&(c=g?.comments?.length&&g?.comments?.length>0?Oa.COMMENT_ADD:Oa.COMMENT_ANNOTATION_ADD),{strippedData:f&&(t||I?.isDraft)?p:null,originalData:g,eventType:c}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(r=>r?.userId?{userId:r.userId}:r)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>r?.contact?.userId?D(E({},r),{contact:{userId:r.contact.userId}}):r));let t=e?.taggedUserContacts?.filter((r,a,s)=>s.findIndex(c=>c.text===r.text)===a)||[];t.forEach(r=>{if(r?.text&&r?.contact?.userId){let a=new RegExp(id(r.text),"g");e.commentText=e.commentText?.replaceAll(a,s=>`{{${r.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,s=>`{{${r.userId}}}`)}}),t.forEach(r=>{r?.text&&r?.contact?.userId&&(r.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 r=Object.values(e?.annotationData?.subscribedUsers||{}).map(s=>s.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&r.length){let s=e?.metadata?.clientDocumentId,c=[];r.forEach(f=>{if(c.push({userId:f,resource:{id:s,type:Mo.DOCUMENT,source:Ir.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??""}}),e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()){let I=JSON.stringify(e?.annotationData?.context?.access);c.push({userId:f,resource:{id:I,type:Mo.CONTEXT,source:Ir.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:e?.annotationData?.context?.access}}})}});let p=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Ir.SET_NOTIFICATIONS,uniqueId:p,timestamp:new Date().getTime(),source:"internal",payload:{requests:c}});let g=yield this.userPermissionService?.onResourceAccessRequired({requests:c,uniqueId:p,methodName:Ir.SET_NOTIFICATIONS});g?.success&&g?.data?.length&&g.data.forEach(f=>{f.hasAccess||a.push(f.userId)})}return a}catch(r){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",r),[]}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let p=yk(this.authService.getFirebaseConfig()?.firebaseOptions),g=Ki(this.functions,Zi({url:Dn.cloudFunction?.[p]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(r){r=this.notificationService?.processNotificationData(r),r.annotationData=e;let G=r?.targetAnnotationData?.commentId;if(G){let z=e?.comments?.find(J=>J?.commentId===G);z&&(r.targetAnnotationData=z)}try{let z=this.stripCommentAnnotationData({data:r.annotationData,actionType:r?.actionType??$t.NEWLY_ADDED});z?.originalData&&(r.annotationData=this.formatCommentData(z.originalData)),r?.targetAnnotationData&&(r.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:r.targetAnnotationData})))}catch(z){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",z)}}let f=qg.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),I=yield this.getDeniedForYouUsers({extraData:r}),T={path:t??"",data:e??{},dbId:f??"",notificationData:r||void 0,notificationURL:Dn.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:ga(),deniedForYouUsers:I,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),metadata:s},N=yield bl(T,this.authService.getUser()?.userId??"");yield g({veltData:N})}catch(p){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",p)}})}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn),ee(Ue),ee(Io),ee(Rt),ee(Ys),ee(Yg),ee(ts))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vpe=(()=>{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 r of e)r?.user?.userId&&t.add(r?.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 r=t;e?.user&&typeof e.user=="object"&&(r=E(E({},r),e.user)),e=D(E({},e),{user:r})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Cpe=(()=>{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 r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var aR=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=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 r of e)r?.from?.userId&&t.add(r?.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),r=yield this.usersService.resolveUsers({userIds:t});for(let a of e)a?.from?.userId&&r[a.from.userId]&&(a.from=r[a.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var sR=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}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 r of e)r?.updatedBy?.userId&&t.add(r?.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}});return t.length?(yield this.usersService.resolveUsers({userIds:t}),this.mergeSingleEditorLiveStateDataWithUser(e)):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 r=this.usersService.getUserById(t?.updatedBy?.userId);r&&(t.updatedBy=r)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Spe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var wC=(()=>{let o=class o{constructor(e,t,r){this.authService=e,this.loggingService=t,this.usersService=r}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let r of e)r?.from?.userId&&t.add(r?.from?.userId),r?.transcription?.from?.userId&&t.add(r?.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?D(E({},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(r){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",r),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return Q(this,null,function*(){try{return yield bl(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var lR=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=r,this.usersService=a,this.authService=s,this.commentAnnotationsResolverService=c}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let r of e){let{notification:a}=r;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 s=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let c of s)t.add(c)}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),r=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[r]?.commentText,s=t?.comments?.[r]?.commentHtml;return a&&s&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=s),e}catch(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 r=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!r||!a)return e;let s=t?.[a]?.[r];return s&&(e.notification.notificationSourceData.location=s?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=s?.location)),e}catch(r){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",r),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let r=this.usersService.getUserById(t?.actionUser?.userId);r&&(t.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);r&&(t.displayHeadlineMessageTemplateData.actionUser=r)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let r=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);r&&(t.displayHeadlineMessageTemplateData.recipientUser=r)}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(r){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",r),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(r=>{r?.notification?.targetAnnotationId&&r?.raw?.notificationSource==="comment"&&t.push(r.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 r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield bl(e,r)}catch(r){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",r),e}})}};o.\u0275fac=function(t){return new(t||o)(ee(Kg),ee(wC),ee(y),ee(Fn),ee(Ue),ee(Ys))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ipe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let r of e)r?.userId&&t.add(r?.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=E(E({},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(r=>{t.includes(r)||(e[r]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Epe=(()=>{let o=class o{constructor(e,t,r,a,s,c){this.loggingService=e,this.usersService=t,this.authService=r,this.functions=a,this.configService=s,this.reactionAnnotationsResolverService=c}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r?.from?.userId),r?.reactions?.length)for(let a of r?.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:r}){try{let s=yk(this.authService.getFirebaseConfig()?.firebaseOptions),c=Ki(this.functions,Zi({url:Dn.cloudFunction?.[s]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),p=qg.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=this.authService.getUser()?.userId??"",f={path:t??"",data:e??{},dbId:p??"",feature:"reaction",eventType:r??"PATCH",sdkVersion:ga()},I=yield bl(f,g);yield c({veltData:I})}catch(s){this.loggingService.catch("Error in handleReactionEncryption:",s)}})}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 r=this.usersService.getUserById(t?.from?.userId);r&&(t.from=r)}}}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 r=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return r?!gi(e,r):!0}catch(r){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",r),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let t={};if(e&&e.annotationId){let r=e.annotationId;if(t[r]=E({annotationId:r,metadata:Y0(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[r],r))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)(ee(y),ee(Fn),ee(Ue),ee(Io),ee(Rt),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var xpe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let r of e)r?.user?.userId&&t.add(r.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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Tpe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let r of e)if(r?.from?.userId&&t.add(r.from.userId),r?.to?.length)for(let a of r.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 r=this.usersService.getUserById(t?.userId);r&&(t=r)}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)(ee(y),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pm=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I,T,N,G,z,J,ce,ye,Oe,$e){this.areaUtilsService=e,this.arrowUtilsService=t,this.commentUtilsService=r,this.contactUtilsService=a,this.cursorUtilsService=s,this.huddleUtilsService=c,this.liveStateUtilsService=p,this.loggingService=g,this.multiThreadUtilsService=f,this.notificationUtilsService=I,this.presenceUtilsService=T,this.reactionUtilsService=N,this.recorderUtilsService=G,this.selectionUtilsService=z,this.tagUtilsService=J,this.usersService=ce,this.docService=ye,this.commentAnnotationsResolverService=Oe,this.reactionAnnotationsResolverService=$e}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",r),null}}getFirestorePath({feature:e,properties:t,documentPaths:r,apiKey:a}){try{if(!a)return;let{documentId:s,organizationId:c,folderId:p}=t;c||(c=r?.organizationId);let g=new nR({apiKey:a,documentId:s?`${s}`:"",organizationId:c?`${c}`:"",veltFolderId:p?`${p}`:void 0});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"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"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"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"allDocNotifications":return t?.documentId&&g?.docNotification?`${g?.docNotification}`: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(s){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",s);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return U.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return U.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return U.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return U.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return U.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return U.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return U.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return U.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"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:r,apiKey:a,useFirestore:s}){try{if(!a)return;let{documentId:c,organizationId:p}=t;p||(p=r?.organizationId);let g=new dm({apiKey:a,documentId:c?`${c}`:"",organizationId:p?`${p}`:""});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!s&&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!s&&t?.documentId&&t?.id&&g?.comment?`${g?.comment}${t?.id}`:void 0;case"allMultiThreads":return!s&&t?.documentId&&g?.multiThread?`${g?.multiThread}`:void 0;case"crdt":return!s&&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"multiThread":return!s&&t?.documentId&&t?.id&&g?.multiThread?`${g?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!s&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!s&&t?.id&&g?.organizationNotificationsLastNotificationTimestamp?`${g?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!s&&t?.documentId&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocuments":return!s&&g?.docs&&t?.documentId?`${g?.docs}/${t?.documentId}/${U.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!s&&t?.documentId&&g?.area?`${g?.area}`:void 0;case"area":return!s&&t?.id&&g?.area?`${g?.area}${t?.id}`:void 0;case"folder":return!s&&t?.folderId&&g?.folder?`${g?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!s&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!s&&t?.documentId&&t?.id&&g?.documentIam?`${g?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!s&&t?.documentId&&g?.documentIam?`${g?.documentIam}users/`:void 0;case"allOrganizationGroups":return!s&&g?.organizationGroups?`${g?.organizationGroups}`:void 0;case"allOrganizationUsers":return!s&&g?.organizationIam?`${g?.organizationIam}users/`:void 0;case"reaction":return!s&&t?.id&&g?.reaction?`${g?.reaction}${t?.id}`:void 0;case"allReactions":return!s&&t?.documentId&&g?.reaction?`${g?.reaction}`:void 0;case"recorder":return!s&&t?.documentId&&t?.id&&g?.recorder?`${g?.recorder}${t?.id}`:void 0;case"allRecorders":return!s&&t?.documentId&&g?.recorder?`${g?.recorder}`:void 0;case"organizationMetadata":return!s&&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!s&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentIam":return!s&&g?.documentIam?`${g?.documentIam}`:void 0;case"documentMetadata":return!s&&t?.documentId&&g?.metadata?`${g?.metadata}`:void 0;case"allDocumentViews":return!s&&t?.documentId&&g?.views?`${g?.views}documentViews/`:void 0;case"documentViews":return!s&&t?.documentId&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!s&&t?.documentId&&g?.views?`${g?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!s&&t?.id&&t?.user&&g?.views?`${g?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!s&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!s&&t?.id&&g?.views?`${g?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!s&&t?.id&&t?.date&&t?.user&&g?.views?`${g?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/location`:void 0;case"location":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!s&&t?.id&&t?.user&&t?.date&&g?.views?`${g?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!s&&t?.id&&g?.views?`${g?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!s&&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(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(r){return Q(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}case"allReactions":{this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionAnnotationsResolverService.resolveReactionAnnotations({reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""});break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(c){return Q(this,arguments,function*({feature:e,data:t,shouldAwait:r=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:s=!1}){try{if(this.usersService.userDataProviderAvailable()){let p=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(p=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}default:p=[]}p?.length&&(r?yield this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}):this.usersService.resolveUsers({userIds:p,forceResolve:a,feature:e}))}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let p=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let g=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...g],p=p.filter(f=>!this.commentAnnotationsResolverService.getCommentAnnotationById(f))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let g=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);p=[...p,...g],p=p.filter(f=>!this.commentAnnotationsResolverService.getCommentAnnotationById(f))}break}default:p=[]}p?.length&&(s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}):this.commentAnnotationsResolverService.resolveCommentAnnotations({commentAnnotationIds:p,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}))}return t}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),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((r,[a,s])=>(r[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(s),r),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",r),e}}mergeReactionAnnotationsWithData({data:e,feature: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((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(s),r),{}):e;default:return e}return e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",r),e}}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:r}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),r&&typeof r=="object"&&!Array.isArray(r))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,r),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[s,c])=>(a[s]=this.notificationUtilsService.mergeLocationWithNotification(c,r),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data: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((r,[a,s])=>(r[a]=this.areaUtilsService.mergeAreaWithUser(s),r),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.arrowUtilsService.mergeArrowWithUser(s),r),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.cursorUtilsService.mergeCursorUserWithUser(s),r),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.commentUtilsService.mergeCommentWithUser(s),r),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.contactUtilsService.mergeUserIamWithUser(s),r),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(s),r),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(r=>this.notificationUtilsService.mergeNotificationWithUser(r)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.notificationUtilsService.mergeNotificationWithUser(s),r),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.presenceUtilsService.mergePresenceUserWithUser(s),r),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.recorderUtilsService.mergeRecorderWithUser(s),r),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.reactionUtilsService.mergeReactionWithUser(s),r),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.tagUtilsService.mergeTagWithUser(s),r),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[a,s])=>(r[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(s),r),{}):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((r,[a,s])=>(r[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(s),r),{}):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((r,[a,s])=>(r[a]=this.selectionUtilsService.mergeSelectionWithUser(s),r),{}):t;default:return t}return t}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",r),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(de(()=>{let r=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",r),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(de(()=>{let r=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:r??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",r),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(de(()=>{let r=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,r),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(de(r=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:r});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),vt(Kt))}catch(r){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,r),se(e)}}handleDataStripping({feature:e,data:t,actionType:r,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:r,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);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:r,offset:a,isRealtimeDb:s}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let c=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return s?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,c);case"notificationViewsTimestamp":return{views:{[r.user??""]:t}};case"documentUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"documentDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"documentMetadataViews":return s?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return s?t:{metadata:t};case"locationUsersViews":return s?t:{users:{[r.user??""]:{[r.date??""]:t}}};case"locationDayViews":return s?t:{day:{[r.date??""]:{[r.user??""]:t}}};case"locationViews":return s?t:{location:t};case"docNotificationViews":return s?t:{views:t.views};case"userNotificationViews":return s?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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(s){return Q(this,arguments,function*({feature:e,data:t,subscriber:r,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});r.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:r}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(r??{}).includes(t.doc.id);if(r?.[t.doc.id]){let a=t.doc.data(),s=r?.[t.doc.id];return a?.lastUpdated===s?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(r){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)?D(E({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",r),e}}setDataInLocal(p){return Q(this,arguments,function*({feature:e,data:t,observablesCache:r,eventType:a,id:s,operation:c=null}){try{let f={comment:"allComments",reaction:"allReactions"}[e];if(!f)return null;let I=t?.metadata?.documentId,T=t?.metadata?.veltFolderId;return Object.keys(r).filter(N=>N.includes(f)&&(!I||N.includes(I)||T&&N.includes(T))).forEach(N=>{let G=r[N]?.subject?.getValue()??{};a==="DELETE"?s&&G?.data?.[s]&&(delete G?.data?.[s],r[N]?.subject&&r[N].subject.next({data:G?.data,operation:c})):r[N]?.subject?.next({data:D(E({},G?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(g){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",g),null}})}handleCommentEncryption(c){return Q(this,arguments,function*({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:r,eventType:a,metadata:s})}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",p),e}})}handleReactionEncryption(a){return Q(this,arguments,function*({data:e,firestorePath:t,eventType:r}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:r})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",s),e}})}rtdbDefaultTransactionCallback(e,t){try{let r=E({},e||{});return Object.entries(t).forEach(([a,s])=>{s==null?delete r[a]:r[a]=s}),r}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",r),e}}};o.\u0275fac=function(t){return new(t||o)(ee(hpe),ee(fpe),ee(Kg),ee(vpe),ee(Cpe),ee(aR),ee(sR),ee(y),ee(Spe),ee(lR),ee(Ipe),ee(Epe),ee(wC),ee(xpe),ee(Tpe),ee(Fn),ee(rt),ee(Ys),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Dpe=(()=>{let o=class o{constructor(e,t,r){this.configService=e,this.authService=t,this.loggingService=r,this.firestore$=new ve(null);try{gn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$()]).pipe(Fe(([a,s])=>!!a&&!!s),ot(1)).subscribe(([a,s])=>{a&&s&&a?.firebaseOptions?.storeDbId&&this.firestore$.next(A9(qg.getFirestoreProdDbName(s,a.firebaseOptions)))},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||A9("DocumentIdDb");if(e){let t=wI(e,"generateDocumentId");return yC(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(ee(Rt),ee(Ue),ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.authService=e,this.commonDbUtilsService=t,this.loggingService=r,this.firestoreService=a,this.databaseService=s,this.configService=c,this.docService=p,this.usersService=g,this.commentAnnotationsResolverService=f,this.reactionAnnotationsResolverService=I,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(T=>{if(T){this.db=T;let N=Pi(T,".info/serverTimeOffset");this.offsetListener=bg(N,G=>{let z=G.val();this.offset=z})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(T=>{T&&(this.firestore=T)}))}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 r=Pi(this.db,e);return _l(r).update(t)}return Promise.resolve()}catch(r){return this.loggingService.catch("Error in setupOnDisconnect:",r),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){gn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Fe(([t,r])=>!!t),ot(1),tn(([t,r])=>{e({db:t,firestore:r})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,r,a,s,c){return Q(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(f=>Q(this,[f],function*({db:p,firestore:g}){let I;t?.skipFirestore||(I=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let T=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!p){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let N,G;try{T&&(N=Pi(p,`${T}`))}catch{this.loggingService.catch("Error in dbRef")}try{I?.includes("/organizations")&&g&&I&&(G=yC(g,`${I}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield r({dbRef:N,firestoreRef:G,data:a,firestorePath:I}),c&&c({firestoreAvailable:!!g})}catch(N){this.loggingService.catch(`Error in ${e} operation: `,N),s&&s(N)}}))}catch(p){this.loggingService.catch("Error in performDatabaseOperation:",p)}})}setData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){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.performDatabaseOperation(e,r,g=>Q(this,null,function*(){if(g.dbRef){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Lh(g.dbRef,()=>JSON.parse(JSON.stringify(f))):yield m0(g.dbRef,JSON.parse(JSON.stringify(f)))}try{if(g.firestoreRef&&g.data&&!r?.skipFirestore){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset()});typeof f=="object"&&(f=JSON.parse(JSON.stringify(f)));let{strippedData:I,originalData:T,eventType:N}=this.commonDbUtilsService.handleDataStripping({feature:e,data:f,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??r?.targetCommentId});if(e==="comment"){let G=null;I&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:I,eventType:N,commentId:c?.targetAnnotationData?.commentId})),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:T,firestorePath:g.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let G=null;I&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(I)),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:T,firestorePath:g.firestorePath??""}))}else e==="recorder"?this.firestore&&(yield Qme(this.firestore,G=>Q(this,null,function*(){G.set(g.firestoreRef,f)}))):yield wW(g.firestoreRef,f)}}catch(f){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,f)}}),t,s,a))}catch(g){this.loggingService.catch(`Error in setData for ${e}`,g)}})}updateData(p){return Q(this,arguments,function*({feature:e,data:t,properties:r,callback:a,errorCallback:s,extraData:c}){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.performDatabaseOperation(e,r,g=>Q(this,null,function*(){if(g.dbRef&&!r?.skipRtdb){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset(),isRealtimeDb:!0});r?.rtdbTransaction?yield Lh(g.dbRef,I=>{let T;return r?.rtdbTransactionCallback?T=r.rtdbTransactionCallback(I,f):T=this.commonDbUtilsService.rtdbDefaultTransactionCallback(I,f),JSON.parse(JSON.stringify(T))}):yield fM(g.dbRef,JSON.parse(JSON.stringify(f)))}try{if(g.firestoreRef&&g.data&&!r?.skipFirestore){let f=this.commonDbUtilsService.formatData({feature:e,data:g.data,properties:r,offset:this.getOffset()});typeof f=="object"&&(f=JSON.parse(JSON.stringify(f)));let{strippedData:I,originalData:T,eventType:N}=this.commonDbUtilsService.handleDataStripping({feature:e,data:f,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(e==="comment"){let G=null;I&&(G=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:I,eventType:N,commentId:c?.targetAnnotationData?.commentId})),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:T,firestorePath:g.firestorePath??"",extraData:c,metadata:r?.metadata}))}else if(e==="reaction"){let G=null;I&&(G=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(I)),T&&(G?.isSuccess||G===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:T,firestorePath:g.firestorePath??""}))}else yield wW(g.firestoreRef,f,{merge:!0})}}catch(f){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,f)}}),t,s,a))}catch(g){this.loggingService.catch(`Error in updateData for ${e}`,g)}})}deleteData(s){return Q(this,arguments,function*({feature:e,properties:t,callback:r,errorCallback:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.performDatabaseOperation(e,t,c=>Q(this,null,function*(){c.dbRef&&(yield hM(c.dbRef));try{if(c.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let p=null;p=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let p=null;p=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??""),(p?.isSuccess||p===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:c.firestorePath??"",eventType:"DELETE"}))}else yield qme(c.firestoreRef)}catch(p){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,p)}}),void 0,a,r)}catch(c){this.loggingService.catch(`Error in deleteData for ${e}`,c)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=on()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),on()||"noDocumentId"}}queryData(r){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 r=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=wI(this.firestore,r);t?.useCollectionGroup&&(a=xW(this.firestore,r));let s=t?.firestoreQuery??[],c=DW(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let p=yield Kme(c).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,g),null));return p?p.data().count:0}catch(p){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,p),0}else try{let p=yield Xme(c).catch(f=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,f),null));if(!p)return[];let g=p.docs.map(f=>f.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:g})}catch(f){return this.loggingService.catch(`Error in modifyData for ${e}`,f),g}}catch(p){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,p),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${e}:`,r),[]}})}handleRtdbQuery(e,t){return Q(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let r=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Pi(this.db,r),s=t?.rtdbQuery??[],c=Jj(a,...s);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let p=yield Xj(c).catch(f=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,f),null));if(!p)return[];let g=p.val();return g?t?.skipObjectValues?g:Object.values(g??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(r){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 s=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield Zme(yC(this.firestore,s)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${s}`),{};let p=c.data();return t?.field?p?.[t.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}if(this.db){let s=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let c=yield Xj(Pi(this.db,s)).catch(g=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,g),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:g})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${s}`),{};let p=c.val();return t?.field?p?.[t.field]??{}:p??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let r=this.shouldUseFirestore();t?.skipFirestore&&(r=!1);let a=`${e}-${JSON.stringify(t)}`;return gn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Fe(s=>!!s))]).pipe(Fe(([s,c])=>s?r&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),he(([s,c])=>{try{if(r&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let f=this.handleFirestoreListener(e,t,c).subscribe(I=>{this.observablesCache[a]?.subject?.next(I)},I=>this.observablesCache[a]?.subject?.error(I));this.firestoreSubscriptions[a]=f}return new Ut(g=>{let f=this.observablesCache[a]?.subject?.subscribe(I=>g.next(I),I=>g.error(I),()=>g.complete());return this.observablesCache[a].count+=1,()=>{f?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new ve({}),count:0};let f=this.handleRealtimeDbListener(e,t,s).subscribe(I=>{this.observablesCache[a]?.subject?.next(I)},I=>this.observablesCache[a]?.subject?.error(I));this.rtdbSubscriptions[a]=f}return new Ut(g=>{let f=this.observablesCache[a]?.subject?.subscribe(I=>g.next(I),I=>g.error(I),()=>g.complete());return this.observablesCache[a].count+=1,()=>{f?.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 se({})}catch(p){return this.loggingService.catch(`Error setting up listener for ${e}:`,p),se({})}}),Lu(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,r){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()}),s=`${e}-${JSON.stringify(t)}`;return a?new Ut(c=>{let p=t.isCollection?this.setupCollectionListener(r,a,e,c,t):this.setupDocumentListener(r,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),p(),this.observablesCache[s]?.subject?.complete(),this.observablesCache[s]?.subject?.unsubscribe(),delete this.observablesCache[s]}}).pipe(he(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),he(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):se(c)),he(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):se(c)),vt(Kt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${s}`),se({}))}setupCollectionListener(e,t,r,a,s){let c=`${r}-${JSON.stringify(s)}`,p=wI(e,t);if(s?.useCollectionGroup&&(p=xW(e,t)),s?.useQuery&&s?.firestoreQuery){let I=s?.firestoreQuery??[];p=DW(p,...I)}let g=!0,f=[];return r==="allComments"&&this.loggingService.logPerf(`[PERF] allComments listener started at ${performance.now().toFixed(2)}ms`),TW(p,I=>{try{let T=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),N=null,G=!1;I?.docChanges()?.length?I.docChanges().forEach(z=>{["allComments","allReactions"].includes(r)&&!g&&z.type!=="removed"&&f.push(z.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:r,change:z,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(G=!0,Object.assign(T,this.handleCollectionChange(z,T)),z.type==="removed"&&(N||(N={type:z.type,ids:[]}),N.ids.push(z.doc.id)))}):G=!0,G&&(["allComments","allReactions"].includes(r)&&f?.length&&(this.commonDbUtilsService.resolveAnnotations({data:f,feature:r}),f=[]),r==="allComments"&&g&&Object.keys(T).length>0&&this.loggingService.logPerf(`[PERF] allComments first snapshot received at ${performance.now().toFixed(2)}ms, entries count: ${Object.keys(T).length}`),this.commonDbUtilsService.modifyAndSetData({feature:r,data:T,subscriber:a,operation:N})),g=!1}catch(T){this.handleListenerError(T,r,a)}},I=>this.handleListenerError(I,r,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,r,a,s){let c=yC(e,t);return TW(c,p=>{try{let g=p.data()||{};s?.field&&(g=g?.[s?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:r,data:g,subscriber:a,operation:null})}catch(g){this.handleListenerError(g,r,a)}},p=>this.handleListenerError(p,r,a))}handleListenerError(e,t,r){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,r){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}`),se({});let s=Pi(r,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];s=Jj(s,...c)}return this.objectValFromChildEvents(s,e).pipe(zn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),se({}))),de(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((g,[f,I])=>(g[f]=this.commonDbUtilsService.addMetadata(I,t),g),{}):this.commonDbUtilsService.addMetadata(c,t))),he(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),he(c=>this.usersService.getUserById$().pipe(de(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}objectValFromChildEvents(e,t){return new Ut(r=>{let a={},s=!1,c=null,p=z=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,z),r.error(z)}catch{}},g=z=>{try{if(!gi(z,c)){let J=JSON.parse(JSON.stringify(z));c=J,r.next(J)}}catch{}},f=z=>{try{z.key&&(a[z.key]=z.val(),s&&g(E({},a)))}catch{}},I=z=>{try{z.key&&(a[z.key]=z.val(),s&&g(E({},a)))}catch{}},T=z=>{try{z.key&&(delete a[z.key],s&&g(E({},a)))}catch{}},N=z=>{try{if(!s){let J=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=J,r.next(J),s=!0}}catch{}};lre(e,f,p),cre(e,I,p),dre(e,T,p);let G=bg(e,N,p,{onlyOnce:!0});return()=>{try{G&&typeof G=="function"&&G(),uM(e,"child_added",f),uM(e,"child_changed",I),uM(e,"child_removed",T)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(pm),ee(y),ee(Dpe),ee(bn),ee(Rt),ee(rt),ee(Fn),ee(Ys),ee(mm))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var yi=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.analyticsService=e,this.authService=t,this.configService=r,this.databaseService=a,this.docService=s,this.loggingService=c,this.commonDbService=p,this.usersService=g,this.db=hs(),this.internalUserContacts$=new ve([]),this.userGlobalContact$=new ve(!1),this.userGroupContact$=new ve(null),this.users$=new ve([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new ve({}),this.userOrganizationContacts$=new ve([]),this.userFolderContacts$=new ve([]),this.userDocumentContacts$=new ve([]),this.userOrganizationGroups$=new ve([]),this.onContactSelectedSubject$=new tt,this.documentAccessType=null,this.atHereEnabled$=new ve(!1),this.atHereLabel$=new ve("here"),this.atHereDescription$=new ve(null),this.contactListScopeForOrganizationUsers$=new ve([zi.ALL]),this.customUserContacts$=new ve(null),this.customUserContactsConfig$=new ve({merge:!1}),this.currentOrganizationUserIAM$=new ve(null),this.userContacts$=new ve([]),this.userSnippylyIdContacts$=new ve(null),this.usersByOrganizationId$=new ve({}),this.temporaryUserIds$=new ve([]),this.usersByOrganizationIdAndDocumentId$=new ve({}),this.usersByOrganizationIdAndFolderId$=new ve({}),this.userById$=new ve({}),this.authService.setContactService(this),this.authService.getUser$().pipe(he(f=>this.docService.getDocumentPaths$().pipe(tn(I=>{this.documentPaths=I}),de(()=>f)))).subscribe(f=>Q(this,null,function*(){if(this.user=f,f&&this.documentPaths)if(!f?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(f),this.setLoggedInUser(f),yield this.moveGlobalContactUserFromEmailToUserIdPath(f),this.updateUserInGlobalContactsIfAvailable(f),f?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(f?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let I=this.userPermissionService?.getCurrentUserPermissions(),T=this.documentPaths.folderId,N=!0;T&&I?.[f?.userId]?.folders?.[T]?.errorCode===Wo.PERMISSION_DENIED&&(N=!1),this.getOrganizationContactsFromDb$(),N&&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}),f=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",f)}),this.databaseService.getDb().pipe(Fe(f=>!!f),ot(1)).subscribe(f=>{f&&(this.db=f)},f=>{this.loggingService.catch("Error in ContactService constructor getDb: ",f)}),this.getOrganizationGroups$().subscribe(f=>{this.authService.setOrganizationUserGroups(f)}),gn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([f,I,T])=>{I?T?.merge?this.userContacts$.next([...f||[],...I||[]]):this.userContacts$.next(I||[]):this.userContacts$.next(f||[])}),this.getUserContacts$().subscribe(f=>{try{f?.forEach(I=>{let T=I?.userSnippylyId||z0(this.configService.getApiKey(),I.userId);T&&this.userSnippylyIdContacts$.next(D(E({},this.userSnippylyIdContacts$.value),{[T]:I}))})}catch{}})}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=[]}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:Et(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:Et(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:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(D(E({},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:Et(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;if(r){if(r?.contacts){let a={};Object.keys(r?.contacts??{})?.forEach(s=>{let c=r.contacts[s];if(c?.userId){let p=Et(c?.userId);a[p]=c}}),r.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(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:Et(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{if(!this.userPermissionService?.getIsContextEnabled())return;let t=this.getUserAccessFields();e.forEach(r=>{t[r.user.userId]=r.accessFields||[]}),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 r=new Bo;r.userId=e?.userId,r.userSnippylyId=e?.userSnippylyId,r.email=e?.email,r.name=e?.name,r.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})}}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:Et(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let r=t;r&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(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 r,a=t?.filter(c=>c?.visibility!=="group"),s=!1;this.authService.getUserOptions()&&(s=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(r={},a?.forEach(c=>{if(c?.userId){let p=Et(c?.userId);r[p]=c}}),s?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(r))})):s&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:Et(e?.userId),skipFirestore:!0}})}}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",r)}}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(r=>Q(this,null,function*(){let a=t[r];a?.email&&a?.userId&&Et(a?.email)===r&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:r,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:Et(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(ot(1)).subscribe(t=>Q(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let r=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===Ei.PUBLIC)r=!0;else if(a===Ei.RESTRICTED){let s=Et(this.user?.userId);if(t?.users?.[s]&&(r=!0),this.user?.email){let c=Et(this.user?.email);t?.users?.[c]&&(r=!0)}}if(r){let s=new Sp;s.email=this.user.email,s.visibility="group",s.name=this.user.name,s.photoUrl=this.user.photoUrl,s.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[s]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,t){try{let r=t?.filter(a=>a?.visibility==="group");r?.length&&r.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:Et(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:Et(a?.email),skipFirestore:!0}}))}}))}catch(r){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",r)}}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(r=>{r?.userId?(!r?.email||!t[r.email])&&(t[r.userId]=r):r?.email&&(!r?.userId||!t[r.userId])&&(t[r.email]=r)}),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:r,veltFolderId:a}=e||{};return t&&r?gn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(de(([s,c,p,g,f,I,T,N])=>{let G={},z=!1;I&&!I?.merge&&(z=!0);let J=Be=>T.some(be=>Be.includes(be)),ce=J([zi.ALL,zi.ORGANIZATION])?Object.keys(s?.[t]||{}):[],ye=a?J([zi.ALL,zi.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],Oe=J([zi.ALL,zi.DOCUMENT])?Object.keys(p?.[t]?.[r]||{}):[];if([...ce,...ye||[],...Oe,...N].forEach(Be=>{let be=g?.[Be];be&&(G[Be]=be)}),f){let{merge:Be,options:be}=I||{},{organizationId:Se,documentId:Ae,folderId:Ce}=be||{},fe=Ce?Ui(Ce):void 0;(!Se||Se===t)&&(!Ae||Ae===r)&&(!fe||fe===a)&&(Be||(G={}),f.forEach(we=>{we?.userId&&(G[we.userId]=we)}))}return Object.values(G??{})})):this.userContacts$.asObservable().pipe(de(s=>s))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),se([])}}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(Fe(e=>!!e),he(e=>this.docService.getDocumentPaths$().pipe(Fe(t=>!!t),tn(t=>{this.documentPaths=t}),de(()=>e))),he(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return se();if(!this.documentPaths)return se();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(de(r=>r?.data),tn(r=>{r?(this.userGlobalContacts=Object.values(r??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(de(r=>r?.data),tn(r=>{r?(this.userGroupContacts=Object.values(r??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:Et(e?.userId)}}).pipe(de(r=>r?.data),tn(r=>{r?this.userPersonalContacts=Object.values(r??{}):this.userPersonalContacts=[]}))),No(...t).pipe(fo(this.authService.getUser$().pipe(Fe(r=>!r))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(vt(Kt))}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(he(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(de(t=>t?.data),tn(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],se()):se():se())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(he(e=>e?.organizationId?this.userById$.pipe(de(t=>{let r={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(r[a?.userSnippylyId]=a)}),r})):this.users$.pipe(de(t=>{let r={};return t.forEach(a=>{r[a.userSnippylyId]=a}),r}))))}getUserByEmail$(e){return this.users$.pipe(de(t=>t.find(r=>r.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(de(t=>t.find(r=>r.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Fe(t=>!!t),de(t=>t?.organizationId)).subscribe(t=>Q(this,null,function*(){if(t&&e){let r=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ht("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(r?.length){let a=yield this.usersService.resolveUsers({userIds:r.map(s=>s?.userId)});if(a){let s={};Object.entries(a).forEach(([p,g])=>{s[p]=g}),this.userById$.next(E(E({},this.userById$.value),s));let c=new Set([...this.temporaryUserIds$.value,...Object.keys(s)]);this.temporaryUserIds$.next(Array.from(c))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>this.usersService.getResolveOrganizationUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],r),t?r?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:r,isCollection:!0,useQuery:!0,firestoreQuery:[_i(R9(ht("organizationIds","array-contains-any",[r]),ht("viewerOrganizationIds","array-contains-any",[r]))),Xi("id")]}}).pipe(de(a=>a?.data),de(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let s=Object.values(a??{});this.setUserAccessFields(s),this.setUserOrganizationContacts(s,r)}else this.setUserOrganizationContacts([],r)})):se():se()}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>this.usersService.getResolveFolderUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>{let r=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return se();if(!this.commonDbService.shouldUseFirestore())return se();if(!this.documentPaths?.veltFolderId)return se();let a=se([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:r,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[_i(R9(ht("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ht("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),Xi("id")]}}).pipe(de(s=>s?.data)),a.pipe(de(s=>{if(s){typeof s=="object"&&(s?.undefined&&delete s.undefined,s?.null&&delete s.null);let c=Object.values(s??{});this.setUserAccessFields(c),this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(he(e=>e?se(e).pipe(he(t=>this.docService.getDocumentPaths$().pipe(Fe(r=>!!r),tn(r=>{this.documentPaths=r}),de(()=>t))),he(t=>this.usersService.getResolveDocumentUsers$().pipe(Fe(r=>r),de(()=>t))),he(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(he(r=>{let a=r?.length>0?r.map(g=>g.documentId):[this.documentPaths?.documentId??""];if(a.some(g=>!g)||!this.documentPaths)return se();let s=se([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let p=[];for(let g=0;g<a.length;g+=U.LISTENER_BATCH_SIZE)p.push(a.slice(g,g+U.LISTENER_BATCH_SIZE));return s=gn(p.map(g=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:D(E({},c),{firestoreQuery:[_i(R9(ht("documentIds","array-contains-any",g),ht("viewerDocumentIds","array-contains-any",g))),Xi("id")]})}).pipe(xr()))).pipe(de(g=>Xr(g)?.data)),s.pipe(de(g=>{if(g){typeof g=="object"&&(g?.undefined&&delete g.undefined,g?.null&&delete g.null);let f=Object.values(g??{});this.setUserAccessFields(f),this.setUserDocumentContacts(f)}else this.setUserDocumentContacts([])}))})):se():se())),he(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),se()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t){try{let r=e.find(s=>s.user.userId===this.user?.userId);r?this.currentOrganizationUserIAM$.next(r):this.currentOrganizationUserIAM$.next(null);let a=e.map(s=>s.user);if(this.userOrganizationContacts$.next(a),this.usersService.setUserByIds(a),t){let s={};s[t]={};let c={};e.forEach(p=>{s[t][p.user.userId]=p,c[p.user.userId]=p.user}),this.userById$.next(E(E({},this.userById$.value),c)),this.usersByOrganizationId$.next(D(E({},this.usersByOrganizationId$.value),{[t]:s[t]}))}else this.usersByOrganizationId$.next({})}catch(r){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",r)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION])?this.userOrganizationContacts$.asObservable():se([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e){try{let t=e?.map(s=>s?.user);this.userFolderContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.folderIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(E(E({},this.userById$.value),a)),this.usersByOrganizationIdAndFolderId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",t)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.FOLDER])?this.userFolderContacts$.asObservable():se([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e){try{let t=e?.map(s=>s?.user);this.userDocumentContacts$.next(t),this.usersService.setUserByIds(t);let r={},a={};e?.forEach(s=>{let{organizationId:c}=s?.metadata||{};c&&(r[c]||(r[c]={}),s.documentIds?.forEach(p=>{r[c][p]||(r[c][p]={}),r[c][p][s.user.userId]=s,a[s.user.userId]=s.user}))}),this.userById$.next(E(E({},this.userById$.value),a)),this.usersByOrganizationIdAndDocumentId$.next(r)}catch(t){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",t)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.userDocumentContacts$.asObservable():se([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.userDocumentContacts$.value:[]}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable()}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{let e=[];this.getContactListScopeForOrganizationUsers().includes(zi.ALL)?e=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.ORGANIZATION)?e=[...this.getUserOrganizationContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.FOLDER)?e=[...this.getUserFolderContacts()]:this.getContactListScopeForOrganizationUsers().includes(zi.DOCUMENT)&&(e=[...this.getUserDocumentContacts()]);let t=[...new Map(e.filter(r=>r?.userId).map(r=>[r.userId,r])).values()];this.internalUserContacts$.next(t)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(he(e=>e?.organizationId?se(e).pipe(he(t=>this.docService.getOrganizationConfig$().pipe(Fe(r=>!!r),de(()=>t))),he(t=>{if(this.setUserOrganizationGroups([]),!t)return se();let r=this.docService.getOrganizationConfig()?.organizationId;return r?this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:r,isCollection:!0}}).pipe(de(a=>a?.data),de(a=>{a?(typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null),this.setUserOrganizationGroups(Object.values(a??{}))):this.setUserOrganizationGroups([])})):se()})):(this.setUserOrganizationGroups([]),se()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(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),r=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case Ei.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:r,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(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():se([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:Re.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:Re.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:Re.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(he(()=>this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.DOCUMENT])?this.atHereEnabled$.asObservable():se(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([zi.ALL,zi.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(r){this.loggingService.catch("Error in CommentService updateContactList: ",r)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:r}=this.docService.getServerId(e?.options);e.options=D(E({},e?.options),{documentId:t,organizationId:r})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(he(e=>e?gn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(de(([t,r,a,s,c])=>{let p={};p.organizationUsers=t?.map(f=>this.convertToClientUser(f)),p.folderUsers=r?.map(f=>this.convertToClientUser(f)),p.documentUsers=a?.map(f=>this.convertToClientUser(f)),p.updatedContactList=c?.map(f=>this.convertToClientUser(f));let g=[];return s?.forEach(f=>{let I=this.convertToClientUserGroup(f,p.organizationUsers||[]);I&&g.push(I)}),p.userGroups=g,p}),vt(Kt)):se(null)),zn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),se(null)}}convertToClientUserGroup(e,t){try{let r={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(s=>{if(s?.userId){let c=Et(s.userId);a[c]=s}}),Object.keys(e?.users??{}).forEach(s=>{a[s]&&r.users?.push(a[s])}),r}catch(r){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",r),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(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)(ee(et),ee(Ue),ee(Rt),ee(bn),ee(rt),ee(y),ee(pn),ee(Fn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var wpe=i=>{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 jI.sanitize(i,o)}catch(o){return nt.catch("Error in File utils sanitizeSvg: ",o),""}},Ope=i=>{try{return i.name.split(".").slice(0,-1).join(".")}catch(o){nt.catch("Error in File utils getFileName: ",o);return}},UW=i=>{try{return/(?:\.([^.]+))?$/.exec(i?.name)[1]}catch(o){nt.catch("Error in File utils getFileExtension: ",o);return}},Ape=(i,o)=>{try{let n=i.slice(0,-1,i.type);return new File([n],o+"."+UW(i),{type:i.type})}catch(n){nt.catch("Error in File utils updateFile: ",n);return}},Ppe=i=>new Promise((o,n)=>{let e=new FileReader;e.readAsDataURL(i),e.onload=()=>{o(e.result)},e.onerror=t=>{n(t)}}),jW={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 Zg=(()=>{let o=class o{constructor(e,t,r,a){this.authService=e,this.configService=t,this.loggingService=r,this.attachmentResolverService=a,this.storage=bb();try{this.configService.getApiKey$().subscribe(s=>{this.apiKey=s}),this.authService.getFirebaseConfig$().subscribe(s=>{s&&s.firebaseOptions?.storageBucket&&(this.storage=bb(void 0,s?.firebaseOptions?.storageBucket))},s=>{this.loggingService.catch("Error in StorageService constructor: ",s)})}catch(s){this.loggingService.catch("Error in StorageService constructor:",s)}}createAttachment({path:e,file:t}){try{let r=new SC;r.name=t.name;let a=Ape(t,`${r.attachmentId}_${Ope(t)}`),s=`${this.apiKey}/${e}/${a?.name}`;return r.bucketPath=s,r.size=t.size,r.type=UW(t),r?.type&&(r.mimeType=jW[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return Q(this,null,function*(){if(e.type===jW.svg)try{let t=yield e.text(),r=wpe(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(s){return Q(this,arguments,function*({attachment:e,file:t,resolve:r,reject:a}){try{let c=Ib(this.storage,e.bucketPath),p=x$(c,t,{cacheControl:"public,max-age=3600"});p.on("state_changed",g=>{let f=g.bytesTransferred/g.totalBytes*100},g=>{a(g)},()=>{E$(p.snapshot.ref).then(g=>{e.url=g,r(e)})})}catch(c){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",c),a(c)}})}uploadToResolver(c){return Q(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:a,reject:s}){try{r.attachmentId=t.attachmentId;let p={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},g=yield this.attachmentResolverService.saveAttachment({attachment:p,eventType:Oa.ATTACHMENT_ADD});g&&g.data?.url?(t.url=g.data?.url,a(t)):s(new Error("Failed to upload attachment to resolver"))}catch(p){this.loggingService.catch("Error in StorageService uploadToResolver: ",p),s(p)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:a}){return new Promise((s,c)=>Q(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let p=yield this.sanitizeSvgFile(t),g=this.createAttachment({path:e,file:p});if(!g)throw new Error("Attachment not created");r?this.uploadToResolver({file:p,attachment:g,metadata:a,resolve:s,reject:c}):this.uploadAttachmentToStorage({attachment:g,file:p,resolve:s,reject:c})}catch(p){this.loggingService.catch("Error in StorageService uploadFile:",p),c(p)}}))}uploadChunk(e,t,r){return new Promise((a,s)=>{try{if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,p=Ib(this.storage,c),g=x$(p,t,{cacheControl:"public,max-age=3600"});g.on("state_changed",f=>{let I=f.bytesTransferred/f.totalBytes*100},f=>{s(f)},()=>{E$(g.snapshot.ref).then(f=>{a(f)}).catch(f=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,f),s(f)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),s(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),s(c)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let r=t.response,a=document.createElement("a"),s=window.URL.createObjectURL(r);a.setAttribute("type","hidden"),a.setAttribute(U.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=s,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(s),a.remove()},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:r}){return new Promise((a,s)=>{if(r)this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t}).then(()=>{a(null)}).catch(c=>{s(c)});else{let c=Ib(this.storage,e.bucketPath);I$(c).then(()=>{a(null)}).catch(p=>{a(null)})}})}deleteFileFromPath(e){return new Promise((t,r)=>{let a=Ib(this.storage,e);I$(a).then(()=>{t(null)}).catch(s=>{r(s)})})}};o.\u0275fac=function(t){return new(t||o)(ee(Ue),ee(Rt),ee(y),ee(Yg))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var In=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=a,this.docService=s,this.configService=c,this.loggingService=p,this.commonDbService=g,this.documentIAM$=new ve(null),this.workspaceIAM$=new ve(null),this.roles$=new ve([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Fe(f=>!!f),ot(1)).subscribe(f=>{f&&(this.getUser(),this.getDocumentPaths())},f=>{this.loggingService.catch("Error in CommentService getDb subscription: ",f)}),this.getRole$().pipe(ot(1)).subscribe(f=>{this.authService?.getUser()&&!f&&this.analyticsService.trackEvent(K.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(f=>{f?.accessType&&this.contactService.setDocumentAccessType(f.accessType)})}catch(f){this.loggingService.catch("Error in IamService constructor: ",f)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(Fe(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(Fe(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new V9;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(zn(e=>se(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(de(e=>!!e),vt())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(de(e=>e?.length?e:U.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(de(e=>e?.features),he(e=>this.getRole$().pipe(de(t=>(t===so.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(he(()=>this.documentIAM$.pipe(Fe(t=>!!t),he(()=>this.workspaceIAM$.pipe(de(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),se(!1)}}getRole$(){try{return this.authService.getUser$().pipe(he(()=>this.configService.getSF$()),he(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():se(null)),he(()=>this.configService.getSF()?this.documentIAM$.pipe(Fe(e=>!!e),vt(Kt)):se(null)),he(()=>this.workspaceIAM$.pipe(vt(Kt))),de(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),se(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return so.ADMIN;if(!e)return this.user?.isAdmin?so.ADMIN:so.COMMENTER;let t=null,r;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?Ei.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||Ei.PUBLIC:null){case Ei.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||so.COMMENTER;break;case Ei.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.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(de(e=>e===so.ADMIN),vt())}isUserAdmin(){try{return this.getRole()===so.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[Et(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[Et(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[Et(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[Et(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(ee(et),ee(Ue),ee(yi),ee(bn),ee(rt),ee(Rt),ee(y),ee(pn))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Ss=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I){this.authService=e,this.docService=t,this.loggingService=r,this.commonDbService=a,this.usersService=s,this.commentUtilsService=c,this.coreActionsService=p,this.functions=g,this.configService=f,this.contactService=I,this.currentUserPermissions$=new ve(null),this.permissionsCache$=new ve(null),this.permissionProvider$=new ve(null);try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(T){this.loggingService.catch("Error in UserPermissionService constructor:",T)}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled())return!0;let r=this.contactService.getUserAccessFieldsByUserId(e);return r?t.every(a=>r.includes(a)):!0}catch(r){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",r),!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:Wo.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:Wo.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(r){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:Wo.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:Wo.DOES_NOT_EXIST,error:!0};let s=this.docService.getDocumentMetadata(e)??{};return this.docService.setDocumentMetadata(e,E(E({},s),a?.metadata??{})),{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(r){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:Wo.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:Wo.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:Wo.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return Q(this,null,function*(){try{let t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return{};let r=yield this.validateResources(t),[a,s]=yield this.fetchUserPermissionsFromDB(t),c=this.buildPermissionsResponse(t,r,a,s);return!e&&Object.keys(c).length>0&&this.setCurrentUserPermissions(c),c}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",t),{}}})}extractResourceIds(e){let t=this.docService.getDocumentPaths(),r=this.docService.getDocumentIds();return{folderIds:e?.folderIds?.length?e.folderIds:t?.folderId?[t.folderId]:[],documentIds:e?.documentIds?.length?e.documentIds:r.map(a=>a.clientDocumentId),clientOrganizationId:e?.organizationId??t?.clientOrganizationId,organizationId:e?.organizationId??t?.clientOrganizationId?Qa(e?.organizationId??t?.clientOrganizationId??""):void 0}}validateResources(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a,clientOrganizationId:s}=e,c=[],p=[];a&&(c.push(this.organizationDetails(a)),p.push({id:s??"",type:"organization"})),t.forEach(f=>{c.push(this.folderDetails({folderId:Ui(f),organizationId:a??""})),p.push({id:f,type:"folder"})}),r.forEach(f=>{c.push(this.documentDetails({documentId:br(f),organizationId:a??""})),p.push({id:f,type:"document"})});let g=yield Promise.allSettled(c);return this.processValidationResults(g,p)})}processValidationResults(e,t){let r=[],a=[],s,c=e.map((p,g)=>({result:p,metadata:t[g]})).filter(({result:p})=>p.status==="rejected"||p.status==="fulfilled"&&p.value.error);for(let{result:p,metadata:g}of c){let f=p.status==="fulfilled"?p.value.errorCode??Wo.SOMETHING_WENT_WRONG:Wo.SOMETHING_WENT_WRONG,I={id:g.id,errorCode:f};switch(g.type){case"organization":if(s=I,f===Wo.DOES_NOT_EXIST)throw new Error(`Organization with id '${g.id}' does not exist`);break;case"folder":r.push(I);break;case"document":a.push(I);break}}return{failedFolderIds:r,failedDocumentIds:a,failedOrganizationId:s}}fetchUserPermissionsFromDB(e){return Q(this,null,function*(){let{folderIds:t,documentIds:r,organizationId:a}=e,s=[this.authService.getUser()?.userId??""],c=[...t.map(f=>Ui(f)),...r.map(f=>br(f)),a??""],[p,g]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:s,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:s,organizationId:a,resourceIds:c})]);return[p.status==="fulfilled"?p.value:[],g.status==="fulfilled"?g.value:[]]})}buildPermissionsResponse(e,t,r,a){let{folderIds:s,documentIds:c,clientOrganizationId:p,organizationId:g}=e,{failedFolderIds:f,failedDocumentIds:I,failedOrganizationId:T}=t,N={};return this.processRegularUserPermissions(N,r,s,c,p??"",g??"",f,I,T),this.processTemporaryUserPermissions(N,a),N}processRegularUserPermissions(e,t,r,a,s,c,p,g,f){for(let I of t)for(let T of I)T?.user?.userId&&(e[T.user.userId]=D(E({},r.length&&{folders:this.buildFolderPermissions(r,T,p)}),{documents:this.buildDocumentPermissions(a,T,g),organization:{[s]:this.buildOrganizationPermission(c,T,f)}}))}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case Wo.DOES_NOT_EXIST:return`${t} does not exist`;case Wo.PERMISSION_DENIED:return`User does not have access to ${t}`;case Wo.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(r){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",r),"Something went wrong"}}buildFolderPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"folder"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerFolderIds?.includes(Ui(s))?qs.VIEWER:qs.EDITOR},a},{})}buildDocumentPermissions(e,t,r){return e.reduce((a,s)=>{let c=r.find(p=>p.id===s);return c?a[s]={error:this.getErrorMessage(c.errorCode,"document"),errorCode:c.errorCode}:a[s]={accessRole:t.viewerDocumentIds?.includes(br(s))?qs.VIEWER:qs.EDITOR},a},{})}buildOrganizationPermission(e,t,r){return r?{error:this.getErrorMessage(r.errorCode,"organization"),errorCode:r.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?qs.VIEWER:qs.EDITOR}}processTemporaryUserPermissions(e,t){for(let r of t)if(r?.userId)switch(this.ensureUserPermissionStructure(e,r.userId),r.type){case"folder":this.addTemporaryFolderPermission(e,r);break;case"document":this.addTemporaryDocumentPermission(e,r);break;case"organization":this.addTemporaryOrganizationPermission(e,r);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].folders||(e[r].folders={}),e[r].folders[a]||(e[r].folders[a]={accessRole:s??qs.EDITOR,expiresAt:c})}addTemporaryDocumentPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].documents||(e[r].documents={}),e[r].documents[a]={accessRole:s??qs.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:r,resourceId:a,role:s,expiresAt:c}=t;e[r].organization||(e[r].organization={}),e[r].organization[a]={accessRole:s??qs.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:r}){try{let a=!0,s=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return s&&(e&&typeof e=="string"&&s?.[c]?.organization?.[e]&&(s?.[c]?.organization?.[e]?.accessRole===qs.VIEWER||s?.[c]?.organization?.[e]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&s?.[c]?.folders?.[t]&&(s?.[c]?.folders?.[t]?.accessRole===qs.VIEWER||s?.[c]?.folders?.[t]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1),r&&typeof r=="string"&&s?.[c]?.documents?.[r]&&(s?.[c]?.documents?.[r]?.accessRole===qs.VIEWER||s?.[c]?.documents?.[r]?.errorCode===Wo.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(vt(Kt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),r=this.authService.getUser()?.userId??"";if(t?.[r]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[r]?.organization?.[a]){let s=Qa(a);t[r].organization&&(t[r].organization[s]=t[r].organization[a],delete t[r].organization[a])}t?.[r]?.folders&&(t[r].folders=Object.fromEntries(Object.entries(t?.[r]?.folders??{}).map(([s,c])=>[Ui(s),c]))),t?.[r]?.documents&&(t[r].documents=Object.fromEntries(Object.entries(t?.[r]?.documents??{}).map(([s,c])=>[br(s),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(de(e=>this.refactorPermissionsWithServerIds(e)),vt(Kt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;"),this.currentUserPermissions$.next(e)}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===IC.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===IC.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return Q(this,null,function*(){try{if(this.isRevokeAccessOnUserLogoutEnabled){let e=[],t=this.authService.getUser()?.userId??"";(this.getPermissionsCache()??[]).forEach(a=>{a.userId===t&&a.hasAccess&&(a.type===Mo.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&e.push(D(E({},a),{hasAccess:!1})):e.push(D(E({},a),{hasAccess:!1})))}),e.length>0&&(this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:on(),methodName:"revokeAccessOnUserLogout",source:"internal",payload:{requests:e}}),this.setPermissionsCache([]),yield this.revokeAccess({requests:e,userId:this.authService.getUser()?.userId??""}))}}catch(e){this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",e)}})}revokeAccessOnDocumentUnset(){return Q(this,null,function*(){try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let e=[],t=this.docService.getDocumentIds(),r=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.docService.getDocumentPaths()?.folderId??"",s=this.authService.getUser()?.userId??"",c=this.getPermissionsCache()??[];t.forEach(g=>{c.find(f=>f.resourceId===g.clientDocumentId&&f.type===Mo.DOCUMENT&&f.organizationId===r&&f.userId===s)&&(e.push({userId:s,resourceId:g.clientDocumentId,organizationId:r,type:Mo.DOCUMENT,hasAccess:!1}),c=c.filter(f=>!(f.resourceId===g.clientDocumentId&&f.type===Mo.DOCUMENT&&f.organizationId===r&&f.userId===s)))}),a&&c.find(g=>g.resourceId===a&&g.type===Mo.FOLDER&&g.organizationId===r&&g.userId===s)&&(e.push({userId:s,resourceId:a,organizationId:r,type:Mo.FOLDER,hasAccess:!1}),c=c.filter(g=>!(g.resourceId===a&&g.type===Mo.FOLDER&&g.organizationId===r&&g.userId===s))),r&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&c.find(g=>g.resourceId===r&&g.type===Mo.ORGANIZATION&&g.organizationId===r&&g.userId===s)&&(e.push({userId:s,resourceId:r,organizationId:r,type:Mo.ORGANIZATION,hasAccess:!1}),c=c.filter(g=>!(g.resourceId===r&&g.type===Mo.ORGANIZATION&&g.organizationId===r&&g.userId===s)));let p=on();this.setPermissionsCache(c),e.length>0&&(this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:"revokeAccessOnDocumentUnset",source:"internal",payload:{requests:e}}),yield this.revokeAccess({requests:e,userId:s}))}}catch(e){this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",e)}})}getAccess(r){return Q(this,arguments,function*({requests:e,userId:t}){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ad({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(r){return Q(this,arguments,function*({requests:e,userId:t}){let a=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ad({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}onResourceAccessRequired(c){return Q(this,arguments,function*({requests:e,uniqueId:t,methodName:r,userId:a,fromCache:s=!0}){try{if(!e?.length)return;let p=[],g=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&s&&(e.forEach(f=>{let I=g?.find(T=>T.resourceId===f.resource.id&&T.type===f.resource.type&&T.userId===f.userId&&T.organizationId===f.resource.organizationId);I&&p.push(I)}),p.length>0&&(e=e.filter(f=>!p.find(I=>I.resourceId===f.resource.id&&I.type===f.resource.type&&I.userId===f.userId&&I.organizationId===f.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:r,source:"internal",payload:{requests:e,fromCache:s}});let f=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:r,source:"internal",payload:{result:f}}),f?.success&&f?.data?.length&&(this.setPermissionsCache([...g,...f.data]),f.data=[...p,...f.data]),f}else if(p.length>0)return this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:r,source:"internal",uniqueId:t,payload:{results:p}}),{data:p,success:!0,statusCode:200};return}catch(p){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",p),this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:r,source:"internal",uniqueId:t,payload:{error:p,requests:e,fromCache:s}});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 s=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(s,a)});let r=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(r)}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)(ee(Ue),ee(rt),ee(y),ee(pn),ee(Fn),ee(Kg),ee(ts),ee(Io),ee(Rt),ee(yi))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var vn=(()=>{let o=class o{constructor(e,t,r,a,s,c,p,g,f,I,T,N,G,z,J,ce,ye,Oe){this.afAuth=e,this.analyticsService=t,this.authService=r,this.configService=a,this.commonDbService=s,this.commonDbUtilsService=c,this.commentUtilsService=p,this.commentAnnotationsResolverService=g,this.databaseService=f,this.docService=I,this.domService=T,this.iamService=N,this.loggingService=G,this.notificationUtilsService=z,this.usersService=J,this.functions=ce,this.userPermissionService=ye,this.coreActionsService=Oe,this.db=hs(),this.notificationsDb=hs(void 0,Dn.firebaseNotificationsDatabaseURL),this.documentPaths=null,this.notifications$=new ve([]),this.rawNotificationsByIdMap$=new ve(new Map),this.processedNotifications$=new ve([]),this.userNotificationsFromServer$=new ve([]),this.readNotificationsOnForYouTab$=new ve(!1),this.currentDocumentOnly$=new ve(!1),this.notificationViews$=new ve({}),this.notificationsByIdMap$=new ve(new Map),this.historyPanelVisible$=new ve(!1),this.notificationsForYou$=new ve(null),this.notificationsByDocumentIdMap$=new ve(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new ve(null),this.maxNotificationDays$=new ve(15),this.tabConfig$=new ve({people:{enable:!1}}),this.settingsConfig$=new ve(null),this.muteAllNotifications$=new ve(!1),this.enableSettings$=new ve(!1),this.selfNotifications$=new ve(!1),this.settingsInitialConfig$=new ve([{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.notificationsPanelVisible$=new ve(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Fe($e=>!!$e),ot(1)).subscribe($e=>{$e&&(this.db=$e,this.getDocumentIds(),this.subscribeGetNotificationsForYou())},$e=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",$e)}),this.authService.getUser$().subscribe($e=>{$e?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(Be=>{this.notificationsByDocumentIdSubscription[Be]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe($e=>{if($e){let Be=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys($e||{}).forEach(be=>{let Se=Be?.[be]?.notifications;Se?.length&&Se.forEach(Ae=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Ae},$e)?.notification})}),this.notificationsByDocumentIdMap$.next(Be)}})}catch($e){this.loggingService.catch("Error in NotificationService constructor: ",$e)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([r,a])=>{t[r]=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=Et(this.authService.getUser()?.userId??""),r=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?.documentId,userId:t}});if(r?.notificationsConfig)this.setDBConfigDataToInitialConfig(r?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let a={};this.settingsInitialConfig$.getValue().forEach(c=>{if(c.enable){let p=c?.values?.find(g=>g.id===c.default);a[c.id]=p||c?.values?.[0]||{id:"NONE",name:"None"}}});let s={};Object.keys(a).forEach(c=>{s[c]=a[c].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=Et(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Fe(t=>t===!0),he(()=>this.docService.getDocumentPaths$().pipe(Fe(t=>!!t),he(t=>Do(this.getInitialConfigFromDB(t)).pipe(he(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:t?.documentId,userId:e}}).pipe(de(r=>{r?.data?.notificationsConfig&&!gi(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer([]),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(he(()=>this.getCurrentDocumentOnly$().pipe(he(e=>e?this.docService.getDocumentPaths$().pipe(de(t=>{})):se(void 0)))),tn(()=>{this.notificationsByDocumentIdMap$.next(null)}),he(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Ti(),de(([e,t])=>{let r=e?.map(g=>g.documentId),a=t?.map(g=>g.documentId),s=r?.filter(g=>!a?.includes(g)),c=a?.map(g=>({documentId:g,timestamp:t?.find(f=>f.documentId===g)?.timestamp})).filter(g=>!r?.includes(g.documentId)),p=a?.map(g=>{let f=t?.find(I=>I.documentId===g)?.timestamp;return{documentId:g,timestamp:f}}).filter(g=>{let f=e?.find(I=>I.documentId===g.documentId)?.timestamp;return f&&g.timestamp&&f!==g.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),p?.length&&this.fetchNotificationsForDocumentIds(p,1),s?.forEach(g=>{this.removeNotificationsForDocumentId(g)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&this.notificationsByDocumentIdMap$.next({})})))).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(he(t=>this.docService.getOrganizationConfig$().pipe(de(r=>{let a=null,s=this.configService.getApiKey(),c=r?.organizationId||t?.organizationId;return s&&c&&(a=new dm({apiKey:s,organizationId:c})),{user:t,documentPaths:a}}))),he(t=>{let{user:r,documentPaths:a}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return se(null);if(r&&a?.organizationNotificationsLastNotificationTimestamp){let s=new Date,c=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;s.setDate(s.getDate()-c);let p=s.getTime(),g=[_i(ht("timestamp",">=",p),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ht("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];return this.getCurrentDocumentOnly()||(g.push(Xi("timestamp","desc")),g.push(k9(e))),this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:g}}).pipe(de(f=>f?.data),de(f=>{let I=[];return Object.keys(f||{}).forEach(T=>{let N=this.commonDbService.shouldUseFirestore()?f[T]?.timestamp??0:f[T],G=this.commonDbService.shouldUseFirestore()?f[T]?.deletedNotification??!1:!1;if(G&&G.id&&G?.timestamp===N){let z=G.id,J=f[T]?.metadata?.documentId,ce=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),ye=ce?.[J]??{documentMetadata:null,notifications:[]},Oe=ye.notifications??[],$e=Oe?.findIndex(Be=>Be.id===z);$e!==-1&&(Oe.splice($e,1),this.notificationsByDocumentIdMap$.next(D(E({},ce),{[J]:D(E({},ye),{notifications:Oe})})))}I.push({documentId:T,timestamp:N})}),I}),zn(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),se([]))))}return se(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),se([])}}fetchNotificationsForDocumentIds(e,t=15){return Q(this,null,function*(){try{if(e?.length){let r=Ki(this.functions,Zi({url:Dn.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let s=this.getStartAtTimestamp(),c={};if(e.forEach(Oe=>{if(Oe?.documentId){let $e=this.getAllowedDocumentMetadataByDocumentId(Oe.documentId);$e&&(c[Oe.documentId]=$e)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let Oe=[];if(e.forEach(Ae=>{this.docService.getDocumentMetadata(Ae.documentId)||Oe.push(Ae.documentId)}),Oe.length){let Ae=this.authService.getUser(),Ce=Ki(this.functions,Zi({url:Dn?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let fe=yield ad({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Ae?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:Oe},getSdkProxy:Ce,userId:Ae?.userId??""});if(fe?.data?.length){let we={};fe?.data.forEach(Ne=>{Ne?.documentId&&(we[Ne.documentId]=Ne)}),this.docService.setAllDocumentMetadata(E(E({},this.docService.getAllDocumentMetadataMap()),we))}}catch(fe){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",fe)}}let $e=[],Be=[];e.forEach(Ae=>{let Ce=this.docService.getDocumentMetadata(Ae.documentId);Ce?.clientDocumentId?$e.push({userId:this.authService.getUser()?.userId??"",resource:{id:Ce.clientDocumentId,type:Mo.DOCUMENT,source:Ir.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):Be.push(Ae.documentId)}),Be.length&&(e=e.filter(Ae=>!Be.includes(Ae.documentId)));let be=on();this.coreActionsService.triggerAction(Un.PERMISSION_PROVIDER,{event:K.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:be,methodName:Ir.GET_NOTIFICATIONS,source:"internal",payload:{requests:$e}});let Se=yield this.userPermissionService?.onResourceAccessRequired({requests:$e,uniqueId:be,methodName:Ir.GET_NOTIFICATIONS});Se?.success&&Se?.data?.length?Se.data.forEach(Ae=>{!Ae.hasAccess&&Ae.resourceId&&(e=e.filter(Ce=>Ce.documentId!==br(Ae.resourceId)))}):e=[]}catch(Oe){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",Oe),e=[]}if(!e.length)return[];let p=this.userPermissionService?.getPermissionsCache()?.filter(Oe=>Oe.type===Mo.CONTEXT),g={organizationId:a,documentIds:e.filter(Oe=>!!Oe.documentId&&!!Oe.timestamp).map(Oe=>({documentId:Oe.documentId,timestamp:Oe.timestamp??0})),timestamp:s,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:p,retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},f=yield this.notificationUtilsService.handleNotificationEncryption({data:g}),I=yield r({veltData:f}),T=I?.data?.data?.veltData||{},N=I?.data?.data?.veltAdditionalData||{},G="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),z=yield j0(T,G),{userNotifications:J=[],userNotificationIdsInDocNotifications:ce=[],permissionResults:ye=[]}=yield j0(N,G);if(this.userPermissionService?.getIsContextEnabled()){let Oe=[...this.userPermissionService?.getPermissionsCache()??[],...ye??[]];this.userPermissionService?.setPermissionsCache(Oe)}if(z&&typeof z=="object"){let Oe=this.usersService.userDataProviderAvailable(),$e=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Be=[],be=[];Object.keys(z).forEach((Se,Ae)=>{let Ce=z[Se].documentMetadata;if(Ce){let we=this.allowedDocumentMetadataMap$.value||{};(!we?.[Se]||!gi(we?.[Se],Ce))&&this.allowedDocumentMetadataMap$.next(D(E({},we),{[Se]:Ce}))}let fe=z[Se].notifications||[];fe.forEach(we=>{ce.includes(we.notificationId)&&!J.find(Ne=>Ne.notificationId===we.notificationId)&&J.push(JSON.parse(JSON.stringify(we))),we.notification=this.getClientNotificationObject(we)}),this.setNotificationForDocumentIdInCache(Se,Ce,fe),Oe&&(Be.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:fe,shouldAwait:!0,forceResolve:!0})),Be.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:J,shouldAwait:!0,forceResolve:!0}))),$e&&(be.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:fe,shouldCommentAnnotationsResolverAwait:!0})),be.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:J,shouldCommentAnnotationsResolverAwait:!0})))}),this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer(),...J]),Oe&&Promise.all(Be).then(()=>{Object.keys(z).forEach(Se=>{let Ae=z?.[Se]?.documentMetadata||{},Ce=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:z?.[Se]?.notifications||[]});Ce.forEach(fe=>{fe.notification=this.getClientNotificationObject(fe)}),this.setNotificationForDocumentIdInCache(Se,Ae,Ce)})}),$e&&Promise.all(be).then(()=>{Object.keys(z).forEach(Se=>{let Ae=z?.[Se]?.documentMetadata||{},Ce=z?.[Se]?.notifications?.reduce((fe,we)=>(fe[we.notificationId]=we,fe),{});Ce=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:Ce}),Ce=Object.values(Ce??{}),Ce.forEach(fe=>{fe.notification=this.getClientNotificationObject(fe)}),this.setNotificationForDocumentIdInCache(Se,Ae,Ce)})})}}}catch(r){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",r),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t.filter((r,a,s)=>a===s.findIndex(c=>c.notificationId===r.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,r,a){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(s);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let p=this.notificationsByDocumentIdMap$.getValue(),g=p?.[e]?.notifications||[],f=this.docService.getLocationMetadatas(),I=r?.map(G=>{let z=G?.notification;return z?(z.metadata&&(z.metadata.documentName=t?.documentName||z.metadata.documentName,z.metadata.organizationMetadata=c||z.metadata.organizationMetadata,z.metadata.documentMetadata=t||z.metadata.documentMetadata),f&&(z=this.notificationUtilsService.mergeLocationWithNotification({notification:z},f)?.notification),z):null})?.filter(G=>!!G)||[],T=new Map(g.map(G=>[G.id,G]));I.forEach(G=>{T.set(G.id,G)});let N=Array.from(T.values()).sort((G,z)=>(z.timestamp||0)-(G.timestamp||0));this.notificationsByDocumentIdMap$.next(D(E({},p),{[e]:{notifications:N,documentMetadata:t}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}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(he(e=>se(e).pipe(de(t=>{let r=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable();if(r||a){let c=t?.reduce((p,g)=>(p[g.notificationId]=g,p),{});r&&(c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:c||[]})),a&&(c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:c||[]})),t=Object.values(c??{})}return t.forEach(c=>{c.notification=this.getClientNotificationObject(c)}),t.sort((c,p)=>p.timestamp-c.timestamp),t.map(c=>c.notification).filter(c=>!!c)}),he(t=>{let r={data:t?.reduce((a,s)=>(a[s.id]={notification:s},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:r,feature:"allUserNotifications"}).pipe(de(a=>Object.values(a?.data||{}).map(s=>s?.notification)))}))),he(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(de(()=>e))}),he(e=>this.allowedDocumentMetadataMap$.pipe(de(()=>e))),de(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),s=this.docService.getOrganizationMetadata(r);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=s||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([]),se(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),se({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let r,a;try{if(e&&(a=Rn(e)),t&&typeof t=="object"){let s=er(t);r=Rn(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return ei(this.afAuth).pipe(Fe(s=>!!s),he(s=>this.isFeatureAllowed({firebaseUser:s})),he(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(de(c=>(s.featureAllowed=c,s))):se(s)),he(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),se([])):se(s).pipe(he(c=>this.docService.getDocumentPaths$().pipe(de(p=>(this.documentPaths=p,c.documentPaths=p,c)))),he(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Fe(t=>!!t),de(t=>D(E({},e),{config:t})),he(t=>this.authService.getUser$().pipe(de(r=>D(E({},t),{user:r})))),he(t=>eo(t.config,t.user,Re.NOTIFICATION)?se(D(E({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),se(D(E({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Fe(t=>!!t),he(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let r=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(r+=`/${U.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=Pi(this.db,`${e?r+"/"+U.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+U.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return gM(a).pipe(zn(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),se(null))),de(s=>{let c=[],p=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(f=>{let I=s?.raw[f];I?.id&&c.push(I)}),c.forEach(f=>{f.id&&p.set(f.id,f)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(p);let g=[];s?.processed&&Object.keys(s?.processed||{}).forEach(f=>{let I=s?.processed[f];I?.id&&g.push(I)}),this.processedNotifications$.next(g),this.setNotificationsByIdMap()}))}else return se(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),r;e?.email&&(r=Et(e?.email));let a;e?.userId&&(a=Et(e?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(p=>{if(p.id&&p?.displayHeadlineMessageTemplate){let g=!1;(r&&p.notifyUsers?.[r]||a&&p.notifyUsers?.[a])&&(g=!0);let f={id:p.id,notificationSource:p.notificationSource,actionType:p.actionType,actionUser:p.actionUser,timestamp:p.timestamp,targetAnnotationId:p.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(p),displayBodyMessage:this.getNotificationBodyMessage(p),forYou:g,notificationSourceData:p.notificationSourceData},I=this.getRawNotificationById(f.id);if(I?.metadata&&(f.metadata={apiKey:I.metadata.apiKey,organizationId:I.metadata.organizationId,clientOrganizationId:I.metadata.clientOrganizationId,documentId:I.metadata.documentId,clientDocumentId:I.metadata.clientDocumentId,location:I?.location,locationId:I?.locationId}),f?.notificationSource==="comment"&&f?.targetAnnotationId){let T=this.commentService?.getAnnotationById(f.targetAnnotationId);T||I?.annotationData&&(T=I.annotationData),T&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(T))}s.set(p.id,f)}}),s.forEach((p,g)=>{p.isUnread=p?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[g]?.views?.[e?.userSnippylyId],s.set(g,p)}),this.notificationsByIdMap$.next(s)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:r,views:a,notification:s}){try{let c=this.authService.getUser(),p=s||e;if(p.id&&p?.displayHeadlineMessageTemplate&&c){let g=null;c?.email&&(g=Et(c?.email));let f=null;c?.userId&&(f=Et(c?.userId));let I=!1,T=!0;(g&&p.notifyUsers?.[g]||f&&p.notifyUsersByUserId?.[f])&&(I=!0),f&&a?.[f]&&(T=!1);let N={id:p.id};if(s?N=D(E(E({},N),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:I,isUnread:T}):N={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:I,isUnread:T,metadata:r},N?.notificationSource==="comment"&&N?.targetAnnotationId){let G=this.commentService?.getAnnotationById(N.targetAnnotationId);G||s?.notificationSourceData&&(G=s?.notificationSourceData),G||t?.annotationData&&(G=t.annotationData),G&&(N.notificationSourceData=this.commentService?.getCommentAnnotationForClient(G))}return t?.targetAnnotationData?.isCommentResolverUsed&&(N.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),N}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(de(e=>e?Object.keys(e??{}).map(t=>{let r=e[t].notifications||[],a=r.filter(c=>c.isUnread).length,s=r.length>0&&r[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:s,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,r)=>r.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(de(e=>{let t=null;return e?(t=[],e.forEach(r=>{r.notifications.forEach(a=>{t?.push(a)})}),t?.sort((r,a)=>a.timestamp-r.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,r=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(r?this.docService.getOrganizationMetadata(r)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let s=t?.documentId?new dm({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=s?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=s?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let p=this.commonDbService.getServerTimestamp(),g=this.notificationUtilsService.formatNotification(e,p);return JSON.parse(JSON.stringify(g))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{let t=Pi(this.notificationsDb),r=this.processNotificationData(e);iM(t,JSON.parse(JSON.stringify(r)))}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(he(t=>t?t.organizationId?this.getAllNotifications$().pipe(he(r=>this.notificationsForYou$.pipe(de(a=>{if(r||a){let s=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(r||[]).forEach(c=>{c.id&&s.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!s.has(c.id)&&s.set(c.id,c)}),Array.from(s.values()).sort((c,p)=>(p.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(de(r=>Array.from(r.values())),de(r=>r.sort((a,s)=>s.timestamp-a.timestamp)),Bu()):se(null)),vt(Kt))}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 r=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,c=r.replace(s,(p,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]:p);return this.domService.sanitizeHtml(c)}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(r=>{if(r?.userId){let a=this.usersService.getUserById(r?.userId);t=t?.replaceAll(`{{${r.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${r.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,r=!1){try{e?document.querySelector(U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${U.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(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 c=0;c<e.length;c+=50){let g=e.slice(c,c+50).filter(T=>T?.id),f=g.map(T=>this.setNotificationAsRead({notification:T,userNotifications:JSON.parse(JSON.stringify(t))})),I=yield Promise.all(f);g.forEach((T,N)=>{let G=I[N];if(!G.some(J=>J.notificationId===T.id))t=t.filter(J=>J.notificationId!==T.id);else{let J=t.find(ye=>ye.notificationId===T.id),ce=G.find(ye=>ye.notificationId===T.id);J&&ce?.views&&(J.views=ce.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(c=>{let p=c.metadata?.documentId;if(p&&a?.[p]){let g=a?.[p]?.notifications||[],f=g.find(I=>I.id===c.id);f&&(f.isUnread=!1),a[p].notifications=g}}),this.notificationsByDocumentIdMap$.next(a),!gi(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(ot(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(de(e=>e?.filter(r=>r?.isUnread)?.length??null),he(e=>this.getNotifications$().pipe(de(t=>{let r=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:r}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),se({forYou:null,all:null})}}setNotificationAsRead(r){return Q(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let s=Et(a?.userId),{metadata:c}=e;if(c){let{apiKey:p,organizationId:g,documentId:f}=c;if(p&&g&&f&&s){let I=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:g,documentId:f,apiKey:p}});I?.notificationId&&(I?.views?.[s]||(I.views||(I.views={}),I.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:g,documentId:f,apiKey:p},data:I})));let T=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:s,documentId:f,organizationId:g}});if(T?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:s,documentId:f,organizationId:g}}),t=t.filter(N=>N.notificationId!==e.id);else if(!T?.views?.[s]){T.views||(T.views={}),T.views[s]={timestamp:Date.now()};let N=t.find(G=>G.notificationId===e.id);N&&(N.views=T.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:s,documentId:f,organizationId:g},data:T})}}}}}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(ot(1)).subscribe(t=>{if(t){let r=t.filter(a=>a.id===e);this.setNotificationsAsRead(r)}})}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)}}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(r=>{["email","inbox"].includes(r.id)&&(t=!r.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=Et(this.authService.getUser()?.userId??""),r=this.docService.getDocumentPaths(),a={apiKey:this.configService.getApiKey(),organizationId:r?.organizationId,documentId:r?.documentId,clientOrganizationId:r?.clientOrganizationId,clientDocumentId:r?.clientDocumentId,userId:t,clientUserId:this.authService.getUser()?.userId};t&&r?.documentId&&this.getEnableSettings()&&this.enableSettings$.value&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:r.documentId,userId:t},data:{id:r.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:a}}))}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)(ee(Ai),ee(et),ee(Ue),ee(Rt),ee(pn),ee(pm),ee(Kg),ee(Ys),ee(bn),ee(rt),ee(Le),ee(In),ee(y),ee(lR),ee(Fn),ee(Io),ee(Ss),ee(ts))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var Uo=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new ve(U.CommentAnnotationStatusMap),this._customPriorityMap=new ve(U.CommentAnnotationPriorityMap),this._customCategoryMap=new ve(U.CommentCategoryMap);try{let t=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let r=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);r&&this._customStatusMap.next(JSON.parse(r));let a=sessionStorage.getItem(U.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(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(r=>{t[r.id]=r,r.type||(r.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(r=>{t[r.id]=r}),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(r=>{t[r.id]=r}),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(([r,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(([r,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(([r,a])=>a.type==="ongoing");if(t)return t.map(r=>r[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[U.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),r=t.find(([a,s])=>s.type==="default");switch(e.status){case"open":r&&(e.status=r[1]);break;case"inProgress":let a=t.find(([c,p])=>p.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let s=t.find(([c,p])=>p.type==="terminal");s&&(e.status=s[1]);break;default:r&&(e.status=r[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)(ee(y))},o.\u0275prov=Pe({token:o,factory:o.\u0275fac,providedIn:"root"});let i=o;return i})();var pd=(()=>{let o=class o{constructor(e,t,r){this.domService=e,this.loggingService=t,this.sanitizer=r,this.emojis={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let s=o.Icons[a];this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(s))}),Object.keys(o.GIF_PATHS).forEach(a=>{let s=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(s))})}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{return this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let r=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(r=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(r))}catch{return""}}setEmojiList(e){try{this.emojis={},Object.keys(e).forEach(t=>{let r=e[t];if(r.svg)this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(r.svg));else if(r.url){let a=`<img src="${r.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else r.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(r.emoji)))})}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
208
208
|
<path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
209
209
|
<path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
|
210
210
|
<path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|