@veltdev/sdk-dev 5.0.2-beta.53 → 5.0.2-beta.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/velt.js +3 -3
package/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '5.0.2-beta.53';
1
+ var SNIPPYLY_VERSION = '5.0.2-beta.54';
2
2
  (function(c,E){"use strict";function U(){var e=X.splice(0,X.length);for(ue=0;e.length;)e.shift().call(null,e.shift())}function fe(e,t){for(var n=0,r=e.length;n<r;n++)Le(e[n],t)}function ot(e){for(var t,n=0,r=e.length;n<r;n++)t=e[n],_(t,B[pe(t)])}function de(e){return function(t){Lt(t)&&(Le(t,e),L.length&&fe(t.querySelectorAll(L),e))}}function pe(e){var t=ae.call(e,"is"),n=e.nodeName.toUpperCase(),r=H.call(D,t?J+t.toUpperCase():q+n);return t&&-1<r&&!Ie(n,t)?-1:r}function Ie(e,t){return-1<L.indexOf(e+'[is="'+t+'"]')}function Fe(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,o=e.target,l=e[Y]||2,a=e[ge]||3;!se||o&&o!==t||!t[C]||r==="style"||e.prevValue===e.newValue&&(e.newValue!==""||n!==l&&n!==a)||t[C](r,n===l?null:e.prevValue,n===a?null:e.newValue)}function Se(e){var t=de(e);return function(n){X.push(t,n.target),ue&&clearTimeout(ue),ue=setTimeout(U,1)}}function he(e){rt&&(rt=!1,e.currentTarget.removeEventListener(Ze,he)),L.length&&fe((e.target||u).querySelectorAll(L),e.detail===v?v:y),R&&at()}function lt(e,t){var n=this;Je.call(n,e,t),Ee.call(n,{target:n})}function Pe(e,t,n){var r=t.apply(e,n),o=pe(r);return-1<o&&_(r,B[o]),n.pop()&&L.length&&ot(r.querySelectorAll(L)),r}function Te(e,t){Tt(e,t),Q?Q.observe(e,gt):(ce&&(e.setAttribute=lt,e[g]=ve(e),e[b](st,Ee)),e[b](N,Fe)),e[x]&&se&&(e.created=!0,e[x](),e.created=!1)}function at(){for(var e,t=0,n=z.length;t<n;t++)e=z[t],P.contains(e)||(n--,z.splice(t--,1),Le(e,v))}function Ve(e){throw new Error("A "+e+" type is already registered")}function Le(e,t){var n,r,o=pe(e);-1<o&&!Mt.call(e,"TEMPLATE")&&(W(e,B[o]),o=0,t!==y||e[y]?t!==v||e[v]||(e[y]=!1,e[v]=!0,r="disconnected",o=1):(e[v]=!1,e[y]=!0,r="connected",o=1,R&&H.call(z,e)<0&&z.push(e)),o&&(n=e[t+O]||e[r+O])&&n.call(e))}function K(){}function Re(e,t,n){var r=n&&n[k]||"",o=t.prototype,l=we(o),a=t.observedAttributes||Ce,m={prototype:l};le(l,x,{value:function(){if(ne)ne=!1;else if(!this[j]){this[j]=!0,new t(this),o[x]&&o[x].call(this);var i=G[re.get(t)];(!Z||i.create.length>1)&&ke(this)}}}),le(l,C,{value:function(i){-1<H.call(a,i)&&o[C]&&o[C].apply(this,arguments)}}),o[Be]&&le(l,ut,{value:o[Be]}),o[je]&&le(l,ct,{value:o[je]}),r&&(m[k]=r),e=e.toUpperCase(),G[e]={constructor:t,create:r?[r,oe(e)]:[e]},re.set(t,e),u[S](e.toLowerCase(),m),Me(e),V[e].r()}function Ue(e){var t=G[e.toUpperCase()];return t&&t.constructor}function _e(e){return typeof e=="string"?e:e&&e.is||""}function ke(e){for(var t,n=e[C],r=n?e.attributes:Ce,o=r.length;o--;)t=r[o],n.call(e,t.name||t.nodeName,null,t.value||t.nodeValue)}function Me(e){return e=e.toUpperCase(),e in V||(V[e]={},V[e].p=new $e(function(t){V[e].r=t})),V[e].p}function xe(){w&&delete c.customElements,I(c,"customElements",{configurable:!0,value:new K}),I(c,"CustomElementRegistry",{configurable:!0,value:K});for(var e=it.get(/^HTML[A-Z]*[a-z]/),t=e.length;t--;(function(n){var r=c[n];if(r){c[n]=function(o){var l,a;return o||(o=this),o[j]||(ne=!0,l=G[re.get(o.constructor)],a=Z&&l.create.length===1,o=a?Reflect.construct(r,Ce,l.constructor):u.createElement.apply(u,l.create),o[j]=!0,ne=!1,a||ke(o)),o},c[n].prototype=r.prototype;try{r.prototype.constructor=c[n]}catch{pt=!0,I(r,j,{value:c[n]})}}})(e[t]));u.createElement=function(n,r){var o=_e(r);return o?Oe.call(this,n,oe(o)):Oe.call(this,n)},tt||(Ne=!0,u[S](""))}var u=c.document,T=c.Object,it=(function(e){var t,n,r,o,l=/^[A-Z]+[a-z]/,a=function(d){var f,h=[];for(f in i)d.test(f)&&h.push(f);return h},m=function(d,f){(f=f.toLowerCase())in i||(i[d]=(i[d]||[]).concat(f),i[f]=i[f.toUpperCase()]=d)},i=(T.create||T)(null),s={};for(n in e)for(o in e[n])for(r=e[n][o],i[o]=r,t=0;t<r.length;t++)i[r[t].toLowerCase()]=i[r[t].toUpperCase()]=o;return s.get=function(d){return typeof d=="string"?i[d]||(l.test(d)?[]:""):a(d)},s.set=function(d,f){return l.test(d)?m(d,f):m(f,d),s},s})({collections:{HTMLAllCollection:["all"],HTMLCollection:["forms"],HTMLFormControlsCollection:["elements"],HTMLOptionsCollection:["options"]},elements:{Element:["element"],HTMLAnchorElement:["a"],HTMLAppletElement:["applet"],HTMLAreaElement:["area"],HTMLAttachmentElement:["attachment"],HTMLAudioElement:["audio"],HTMLBRElement:["br"],HTMLBaseElement:["base"],HTMLBodyElement:["body"],HTMLButtonElement:["button"],HTMLCanvasElement:["canvas"],HTMLContentElement:["content"],HTMLDListElement:["dl"],HTMLDataElement:["data"],HTMLDataListElement:["datalist"],HTMLDetailsElement:["details"],HTMLDialogElement:["dialog"],HTMLDirectoryElement:["dir"],HTMLDivElement:["div"],HTMLDocument:["document"],HTMLElement:["element","abbr","address","article","aside","b","bdi","bdo","cite","code","command","dd","dfn","dt","em","figcaption","figure","footer","header","i","kbd","mark","nav","noscript","rp","rt","ruby","s","samp","section","small","strong","sub","summary","sup","u","var","wbr"],HTMLEmbedElement:["embed"],HTMLFieldSetElement:["fieldset"],HTMLFontElement:["font"],HTMLFormElement:["form"],HTMLFrameElement:["frame"],HTMLFrameSetElement:["frameset"],HTMLHRElement:["hr"],HTMLHeadElement:["head"],HTMLHeadingElement:["h1","h2","h3","h4","h5","h6"],HTMLHtmlElement:["html"],HTMLIFrameElement:["iframe"],HTMLImageElement:["img"],HTMLInputElement:["input"],HTMLKeygenElement:["keygen"],HTMLLIElement:["li"],HTMLLabelElement:["label"],HTMLLegendElement:["legend"],HTMLLinkElement:["link"],HTMLMapElement:["map"],HTMLMarqueeElement:["marquee"],HTMLMediaElement:["media"],HTMLMenuElement:["menu"],HTMLMenuItemElement:["menuitem"],HTMLMetaElement:["meta"],HTMLMeterElement:["meter"],HTMLModElement:["del","ins"],HTMLOListElement:["ol"],HTMLObjectElement:["object"],HTMLOptGroupElement:["optgroup"],HTMLOptionElement:["option"],HTMLOutputElement:["output"],HTMLParagraphElement:["p"],HTMLParamElement:["param"],HTMLPictureElement:["picture"],HTMLPreElement:["pre"],HTMLProgressElement:["progress"],HTMLQuoteElement:["blockquote","q","quote"],HTMLScriptElement:["script"],HTMLSelectElement:["select"],HTMLShadowElement:["shadow"],HTMLSlotElement:["slot"],HTMLSourceElement:["source"],HTMLSpanElement:["span"],HTMLStyleElement:["style"],HTMLTableCaptionElement:["caption"],HTMLTableCellElement:["td","th"],HTMLTableColElement:["col","colgroup"],HTMLTableElement:["table"],HTMLTableRowElement:["tr"],HTMLTableSectionElement:["thead","tbody","tfoot"],HTMLTemplateElement:["template"],HTMLTextAreaElement:["textarea"],HTMLTimeElement:["time"],HTMLTitleElement:["title"],HTMLTrackElement:["track"],HTMLUListElement:["ul"],HTMLUnknownElement:["unknown","vhgroupv","vkeygen"],HTMLVideoElement:["video"]},nodes:{Attr:["node"],Audio:["audio"],CDATASection:["node"],CharacterData:["node"],Comment:["#comment"],Document:["#document"],DocumentFragment:["#document-fragment"],DocumentType:["node"],HTMLDocument:["#document"],Image:["img"],Option:["option"],ProcessingInstruction:["node"],ShadowRoot:["#shadow-root"],Text:["#text"],XMLDocument:["xml"]}});typeof E!="object"&&(E={type:E||"auto"});var X,Ee,$,ve,Q,He,W,_,A,S="registerElement",qe=1e5*c.Math.random()>>0,g="__"+S+qe,b="addEventListener",y="attached",O="Callback",v="detached",k="extends",C="attributeChanged"+O,ut=y+O,Be="connected"+O,je="disconnected"+O,x="created"+O,ct=v+O,Y="ADDITION",ge="REMOVAL",N="DOMAttrModified",Ze="DOMContentLoaded",st="DOMSubtreeModified",q="<",J="=",mt=/^[A-Z][._A-Z0-9]*-[-._A-Z0-9]*$/,ft=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],D=[],B=[],L="",P=u.documentElement,H=D.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},be=T.prototype,ye=be.hasOwnProperty,ee=be.isPrototypeOf,I=T.defineProperty,Ce=[],te=T.getOwnPropertyDescriptor,Ge=T.getOwnPropertyNames,dt=T.getPrototypeOf,ze=T.setPrototypeOf,Ke=!!T.__proto__,pt=!1,j="__dreCEv1",w=c.customElements,Z=!/^force/.test(E.type)&&!!(w&&w.define&&w.get&&w.whenDefined),Xe=T.create||T,ht=c.Map||function(){var e,t=[],n=[];return{get:function(r){return n[H.call(t,r)]},set:function(r,o){e=H.call(t,r),e<0?n[t.push(r)-1]=o:n[e]=o}}},$e=c.Promise||function(e){function t(l){for(r=!0;n.length;)n.shift()(l)}var n=[],r=!1,o={catch:function(){return o},then:function(l){return n.push(l),r&&setTimeout(t,1),o}};return e(t),o},ne=!1,G=Xe(null),V=Xe(null),re=new ht,oe=function(e){return e.toLowerCase()},we=T.create||function e(t){return t?(e.prototype=t,new e):this},Tt=ze||(Ke?function(e,t){return e.__proto__=t,e}:Ge&&te?(function(){function e(t,n){for(var r,o=Ge(n),l=0,a=o.length;l<a;l++)r=o[l],ye.call(t,r)||I(t,r,te(n,r))}return function(t,n){do e(t,n);while((n=dt(n))&&!ee.call(n,t));return t}})():function(e,t){for(var n in t)e[n]=t[n];return e}),F=c.MutationObserver||c.WebKitMutationObserver,Qe=c.HTMLAnchorElement,p=(c.HTMLElement||c.Element||c.Node).prototype,R=!ee.call(p,P),le=R?function(e,t,n){return e[t]=n.value,e}:I,Lt=R?function(e){return e.nodeType===1}:function(e){return ee.call(p,e)},z=R&&[],We=p.attachShadow,Ye=p.cloneNode,Mt=p.closest||function(e){for(var t=this;t&&t.nodeName!==e;)t=t.parentNode;return t},Ae=p.dispatchEvent,ae=p.getAttribute,Et=p.hasAttribute,vt=p.removeAttribute,Je=p.setAttribute,ie=u.createElement,Ht=u.importNode,Oe=ie,gt=F&&{attributes:!0,characterData:!0,attributeOldValue:!0},et=F||function(e){ce=!1,P.removeEventListener(N,et)},ue=0,tt=S in u&&!/^force-all/.test(E.type),nt=!0,Ne=!1,ce=!0,rt=!0,se=!0;if(F&&(A=u.createElement("div"),A.innerHTML="<div><div></div></div>",new F(function(e,t){if(e[0]&&e[0].type=="childList"&&!e[0].removedNodes[0].childNodes.length){A=te(p,"innerHTML");var n=A&&A.set;n&&I(p,"innerHTML",{set:function(r){for(;this.lastChild;)this.removeChild(this.lastChild);n.call(this,r)}})}t.disconnect(),A=null}).observe(A,{childList:!0,subtree:!0}),A.innerHTML=""),tt||(ze||Ke?(W=function(e,t){ee.call(t,e)||Te(e,t)},_=Te):(W=function(e,t){e[g]||(e[g]=T(!0),Te(e,t))},_=W),R?(ce=!1,(function(){var e=te(p,b),t=e.value,n=function(l){var a=new CustomEvent(N,{bubbles:!0});a.attrName=l,a.prevValue=ae.call(this,l),a.newValue=null,a[ge]=a.attrChange=2,vt.call(this,l),Ae.call(this,a)},r=function(l,a){var m=Et.call(this,l),i=m&&ae.call(this,l),s=new CustomEvent(N,{bubbles:!0});Je.call(this,l,a),s.attrName=l,s.prevValue=m?i:null,s.newValue=a,m?s.MODIFICATION=s.attrChange=1:s[Y]=s.attrChange=0,Ae.call(this,s)},o=function(l){var a,m=l.currentTarget,i=m[g],s=l.propertyName;i.hasOwnProperty(s)&&(i=i[s],a=new CustomEvent(N,{bubbles:!0}),a.attrName=i.name,a.prevValue=i.value||null,a.newValue=i.value=m[s]||null,a.prevValue==null?a[Y]=a.attrChange=0:a.MODIFICATION=a.attrChange=1,Ae.call(m,a))};e.value=function(l,a,m){l===N&&this[C]&&this.setAttribute!==r&&(this[g]={className:{name:"class",value:this.className}},this.setAttribute=r,this.removeAttribute=n,t.call(this,"propertychange",o)),t.call(this,l,a,m)},I(p,b,e)})()):F||(P[b](N,et),P.setAttribute(g,1),P.removeAttribute(g),ce&&(Ee=function(e){var t,n,r,o=this;if(o===e.target){t=o[g],o[g]=n=ve(o);for(r in n){if(!(r in t))return $(0,o,r,t[r],n[r],Y);if(n[r]!==t[r])return $(1,o,r,t[r],n[r],"MODIFICATION")}for(r in t)if(!(r in n))return $(2,o,r,t[r],n[r],ge)}},$=function(e,t,n,r,o,l){var a={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:o};a[l]=e,Fe(a)},ve=function(e){for(var t,n,r={},o=e.attributes,l=0,a=o.length;l<a;l++)t=o[l],(n=t.name)!=="setAttribute"&&(r[n]=t.value);return r})),u[S]=function(e,t){if(n=e.toUpperCase(),nt&&(nt=!1,F?(Q=(function(i,s){function d(f,h){for(var M=0,me=f.length;M<me;h(f[M++]));}return new F(function(f){for(var h,M,me,De=0,bt=f.length;De<bt;De++)h=f[De],h.type==="childList"?(d(h.addedNodes,i),d(h.removedNodes,s)):(M=h.target,se&&M[C]&&h.attributeName!=="style"&&(me=ae.call(M,h.attributeName))!==h.oldValue&&M[C](h.attributeName,h.oldValue,me))})})(de(y),de(v)),He=function(i){return Q.observe(i,{childList:!0,subtree:!0}),i},He(u),We&&(p.attachShadow=function(){return He(We.apply(this,arguments))})):(X=[],u[b]("DOMNodeInserted",Se(y)),u[b]("DOMNodeRemoved",Se(v))),u[b](Ze,he),u[b]("readystatechange",he),u.importNode=function(i,s){switch(i.nodeType){case 1:return Pe(u,Ht,[i,!!s]);case 11:for(var d=u.createDocumentFragment(),f=i.childNodes,h=f.length,M=0;M<h;M++)d.appendChild(u.importNode(f[M],!!s));return d;default:return Ye.call(i,!!s)}},p.cloneNode=function(i){return Pe(this,Ye,[!!i])}),Ne)return Ne=!1;if(-2<H.call(D,J+n)+H.call(D,q+n)&&Ve(e),!mt.test(n)||-1<H.call(ft,n))throw new Error("The type "+e+" is invalid");var n,r,o=function(){return a?u.createElement(m,n):u.createElement(m)},l=t||be,a=ye.call(l,k),m=a?t[k].toUpperCase():n;return a&&-1<H.call(D,q+m)&&Ve(m),r=D.push((a?J:q)+n)-1,L=L.concat(L.length?",":"",a?m+'[is="'+e.toLowerCase()+'"]':m),o.prototype=B[r]=ye.call(l,"prototype")?l.prototype:we(p),L.length&&fe(u.querySelectorAll(L),y),o},u.createElement=Oe=function(e,t){var n=_e(t),r=n?ie.call(u,e,oe(n)):ie.call(u,e),o=""+e,l=H.call(D,(n?J:q)+(n||o).toUpperCase()),a=-1<l;return n&&(r.setAttribute("is",n=n.toLowerCase()),a&&(a=Ie(o.toUpperCase(),n))),se=!u.createElement.innerHTMLHelper,a&&_(r,B[l]),r}),addEventListener("beforeunload",function(){delete u.createElement,delete u.importNode,delete u[S]},!1),K.prototype={constructor:K,define:Z?function(e,t,n){if(n)Re(e,t,n);else{var r=e.toUpperCase();G[r]={constructor:t,create:[r]},re.set(t,r),w.define(e,t)}}:Re,get:Z?function(e){return w.get(e)||Ue(e)}:Ue,whenDefined:Z?function(e){return $e.race([w.whenDefined(e),Me(e)])}:Me},!w||/^force/.test(E.type))xe();else if(!E.noBuiltIn)try{(function(e,t,n){var r=new RegExp(`^<a\\s+is=('|")`+n+"\\1></a>$");if(t[k]="a",e.prototype=we(Qe.prototype),e.prototype.constructor=e,c.customElements.define(n,e,t),!r.test(u.createElement("a",{is:n}).outerHTML)||!r.test(new e().outerHTML))throw t})(function e(){return Reflect.construct(Qe,[],e)},{},"document-register-element-a"+qe)}catch{xe()}if(!E.noBuiltIn)try{if(ie.call(u,"a","a").outerHTML.indexOf("is")<0)throw{}}catch{oe=function(t){return{is:t.toLowerCase()}}}})(window);Promise.allSettled||(Promise.allSettled=function(c){return Promise.all(c.map(function(E){return Promise.resolve(E).then(function(U){return{status:"fulfilled",value:U}}).catch(function(U){return{status:"rejected",reason:U}})}))});
3
3
 
4
4
  var Z3e=Object.create;var K5=Object.defineProperty,X3e=Object.defineProperties,J3e=Object.getOwnPropertyDescriptor,Q3e=Object.getOwnPropertyDescriptors,eOe=Object.getOwnPropertyNames,Y5=Object.getOwnPropertySymbols,Xte=Object.getPrototypeOf,vB=Object.prototype.hasOwnProperty,Jte=Object.prototype.propertyIsEnumerable,tOe=Reflect.get;var Zte=(n,o,r)=>o in n?K5(n,o,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[o]=r,h=(n,o)=>{for(var r in o||={})vB.call(o,r)&&Zte(n,r,o[r]);if(Y5)for(var r of Y5(o))Jte.call(o,r)&&Zte(n,r,o[r]);return n},y=(n,o)=>X3e(n,Q3e(o));var Oh=(n,o)=>{var r={};for(var e in n)vB.call(n,e)&&o.indexOf(e)<0&&(r[e]=n[e]);if(n!=null&&Y5)for(var e of Y5(n))o.indexOf(e)<0&&Jte.call(n,e)&&(r[e]=n[e]);return r};var nOe=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),Z5=(n,o)=>{for(var r in o)K5(n,r,{get:o[r],enumerable:!0})},rOe=(n,o,r,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of eOe(o))!vB.call(n,t)&&t!==r&&K5(n,t,{get:()=>o[t],enumerable:!(e=J3e(o,t))||e.enumerable});return n};var Qte=(n,o,r)=>(r=n!=null?Z3e(Xte(n)):{},rOe(o||!n||!n.__esModule?K5(r,"default",{value:n,enumerable:!0}):r,n));var Cm=(n,o,r)=>tOe(Xte(n),r,o);var J=(n,o,r)=>new Promise((e,t)=>{var i=s=>{try{l(r.next(s))}catch(d){t(d)}},a=s=>{try{l(r.throw(s))}catch(d){t(d)}},l=s=>s.done?e(s.value):Promise.resolve(s.value).then(i,a);l((r=r.apply(n,o)).next())});var hte=nOe((c_i,pte)=>{"use strict";var Rt={};Rt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Rt.localCName=Rt.generateIdentifier();Rt.splitLines=function(n){return n.trim().split(`
@@ -193,7 +193,7 @@ Content-Type: `+d.contentType+`\r
193
193
  <path fill-rule="evenodd" clip-rule="evenodd" d="M9.3086 12.167H3.33301V2.16699H8.33301C9.42152 2.16699 10.3476 2.86267 10.6908 3.83366H14.803C16.0419 3.83366 16.8477 5.13751 16.2937 6.24568L14.9997 8.83366L16.2937 11.4216C16.8477 12.5298 16.0419 13.8337 14.803 13.8337H11.6663C10.5778 13.8337 9.65179 13.138 9.3086 12.167ZM4.99967 3.83366H8.33301C8.79324 3.83366 9.16634 4.20675 9.16634 4.66699V10.5003H4.99967V3.83366ZM10.833 11.3337C10.833 11.7939 11.2061 12.167 11.6663 12.167H14.803L13.1363 8.83366L14.803 5.50033H10.833V11.3337Z" fill="currentColor"/>
194
194
  </g>
195
195
  </svg>`}},yt.WorkspaceRoles=[{id:Lo.COMMENTER?.toLowerCase(),name:Lo.COMMENTER,description:"Can comment on this project",permissions:[]},{id:Lo.ADMIN?.toLowerCase(),name:Lo.ADMIN,description:"Can comment on all projects and has access to the portal",permissions:[]}],yt.DocumentAccessTypeMap={[zr.PUBLIC]:{id:zr.PUBLIC,name:zr.PUBLIC,description:"Anyone with link can view"},[zr.RESTRICTED]:{id:zr.RESTRICTED,name:zr.RESTRICTED,description:"Only people with access can view"}},yt.DocumentAccessTypeMapSF={[zr.PUBLIC]:{id:zr.PUBLIC,name:zr.PUBLIC,description:"Anyone with the link can comment after logging in."},[zr.RESTRICTED]:{id:zr.RESTRICTED,name:zr.RESTRICTED,description:"Only people added to this project can comment."}},yt.CommentCategoryMap={bug:{id:"bug",name:"Bug",color:"#FF7162"},feedback:{id:"feedback",name:"Feedback",color:"#00C48C"},question:{id:"question",name:"Question",color:"#FFD166"}},yt.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"}],yt.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"}],yt.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 N=yt;var wN=(n,o)=>{try{let r=new URL(n),e=r.hostname.split("."),t=e.length>=3?e[0]:"",i=n.replace(r.host,o);if(t){let a=i.includes("?")?"&":"?";i+=`${a}ns=${t}`}return i}catch(r){return it.catch("Error in getProxiedDatabaseUrl: ",r),n}},Qn=(n,o=0)=>{try{let r=3735928559^o,e=1103547991^o;for(let t=0,i;t<n.length;t++)i=n.charCodeAt(t),r=Math.imul(r^i,2654435761),e=Math.imul(e^i,1597334677);return r=Math.imul(r^r>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),4294967296*(2097151&e)+(r>>>0)}catch(r){return it.catch("Error in cyrb53: ",r),0}},rGe=()=>{try{return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+n/4).toString(16))}catch(n){return it.catch("Error in uuidv4: ",n),""}},It=n=>{try{return fl.hashStr(n)}catch(o){return it.catch("Error in hashStr: ",o),n}},ehe=n=>{try{return!n||n.trim().length===0?void 0:fl.hashStr(n)}catch(o){it.catch("Error in hashForAnchor: ",o);return}},mi=n=>Qn(n).toString(),YK=n=>It(n),Pa=n=>It(n).toString(),Pr=n=>It(n).toString(),e1=(n,o)=>{try{let r=n.userIds?.length?[...n.userIds]:[];return r.includes(o)||r.push(o),y(h({},n),{userIds:r})}catch(r){return it.catch("Error in ensureUserIdInVisibility: ",r),n}},Gu=n=>{let o=[];switch(n.type){case"public":o.push(N.DEFAULT_VELT_CONTEXT);break;case"organizationPrivate":if(!n.organizationId)throw new Error("organizationId is required for organizationPrivate visibility type");let r=Pa(n.organizationId);o.push(`organizationPrivate:${r}`);break;case"restricted":if(!n.userIds?.length)throw new Error("userIds is required for restricted visibility type");n.userIds.forEach(e=>{let t=It(e).toString();o.push(`${N.VISIBILITY_SELF_PREFIX}${t}`)});break;default:throw new Error(`Invalid visibility type: ${n.type}`)}return o},Jm=n=>{try{if(n)return typeof n=="string"?fl.hashStr(n):Array.isArray(n)?fl.hashStr(n.join("-")):"";{let o=rGe();return fl.hashStr(o)}}catch(o){return it.catch("Error in getMultiThreadAnnotationId: ",o),""}},Ao=(n,o,r)=>{try{if(n&&o){if(n.featureAllowList&&n.featureAllowList.length&&!n.featureAllowList.includes(r)||n.userIdAllowList&&n.userIdAllowList.length&&!n.userIdAllowList.includes(o.userId)||n.userGroupIdAllowList&&n.userGroupIdAllowList.length&&!n.userGroupIdAllowList.includes(o.groupId||"")||n.userPlanAllowList&&n.userPlanAllowList.length&&!n.userPlanAllowList.includes(o.plan||""))return!1;if(n.urlAllowList){let e=window.location.href;if(n.urlAllowList.length&&!n.urlAllowList.filter(t=>e.includes(t)).length)return!1}return!0}return!1}catch(e){return it.catch("Error in isFeatureAllowed: ",e),!1}},at=()=>{try{let n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o="";for(let r=0;r<20;r++)o+=n.charAt(Math.floor(Math.random()*n.length));return o}catch(n){return it.catch("Error in utils generateId: ",n),""}},zu=n=>{try{let o=0;if(n){let r=new Date().getTime();o=Math.abs(r-n)}return o}catch(o){return it.catch("Error in utils getFirebaseTimeDiffInMins: ",o),0}};var the=()=>{try{return En.debugMode||!!sessionStorage.getItem("debugMode")||!!sessionStorage.getItem("forceDebugMode")}catch(n){return it.catch("Error in showLogs: ",n),!1}},nhe=()=>{try{return!!sessionStorage.getItem("debugContextMode")}catch(n){return it.catch("Error in showContextLogs: ",n),!1}},Oi=n=>{try{return typeof n!="object"?Object.assign({},...Object.keys(n).sort().map(o=>({[o]:n[o]&&typeof n[o]=="object"?Oi(n[o]):n[o]}))):n}catch(o){return it.catch("Error in sortObjectByKeys: ",o),n}},qK=n=>{try{return n!==null&&typeof n=="object"&&!Array.isArray(n)}catch{return!1}},hc=n=>{try{return qK(n)?Object.fromEntries(Object.entries(n).sort(([o],[r])=>o.localeCompare(r)).map(([o,r])=>[o,qK(r)?hc(r):Array.isArray(r)?r.map(e=>qK(e)?hc(e):e):r])):n}catch{return n}},IN=(n,o)=>{try{return typeof o!="object"||o===null?n===o:typeof n!="object"||n===null?!1:Array.isArray(o)?Array.isArray(n)?o.every(r=>n.some(e=>IN(e,r))):!1:Object.keys(o).every(r=>Object.prototype.hasOwnProperty.call(n,r)?IN(n[r],o[r]):!1)}catch{return!1}},KK=(n,o,r)=>J(null,null,function*(){try{let e=yield iGe(o),t=new Uint8Array(new TextEncoder().encode(r)).slice(0,16),i=new TextEncoder().encode(n),a=yield window.crypto.subtle.encrypt({name:"AES-CBC",iv:t},e,i);return btoa(String.fromCharCode(...new Uint8Array(a)))}catch(e){return it.catch("Error in encrypt: ",e),n}}),ZK=(n,o,r)=>J(null,null,function*(){try{let e=yield oGe(o),t=new Uint8Array(new TextEncoder().encode(r)).slice(0,16),i=new Uint8Array(atob(n).split("").map(l=>l.charCodeAt(0))),a=yield window.crypto.subtle.decrypt({name:"AES-CBC",iv:t},e,i);return new TextDecoder().decode(a)}catch(e){return it.catch("Error in decrypt: ",e),n}}),oGe=n=>J(null,null,function*(){try{let o=new TextEncoder().encode(n),r=new Uint8Array(32);return r.fill(0),r.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",r,"AES-CBC",!1,["decrypt"])}catch(o){throw it.catch("Error in importDecryptKey:",o),o}}),fc=(n,o)=>J(null,null,function*(){try{let r="Velt"+o;return yield KK(JSON.stringify(n),r,It(r))}catch(r){return it.catch("Error in encryptData: ",r),n}}),t1=(n,o)=>J(null,null,function*(){try{let r="Velt"+o,e=yield ZK(n,r,It(r));return JSON.parse(e)}catch(r){return it.catch("Error in decryptData: ",r),null}}),DN=n=>{try{switch(n?.region){case"asiaSouthEast1":return"asiaSouthEast1";case"asiaNorthEast1":return"asiaNorthEast1";case"europeWest1":return"europeWest1";default:return"usCentral1"}}catch(o){return it.catch("Error in getRegion: ",o),"usCentral1"}},iGe=n=>J(null,null,function*(){try{let o=new TextEncoder().encode(n),r=new Uint8Array(32);return r.fill(0),r.set(o.slice(0,32)),yield window.crypto.subtle.importKey("raw",r,"AES-CBC",!1,["encrypt"])}catch(o){throw it.catch("Error in importKey:",o),o}}),rhe=n=>{try{if(n&&typeof n=="object"){let o=Oi(n);return Qn(JSON.stringify(o))}else return null}catch(o){return it.catch("Error in utils generateLocationId: ",o),null}},Co=(n,o=[])=>(n?.tagName?.toLowerCase().indexOf("velt-")>=0&&![N.TAGS.VELT_VIDEO_PLAYER.toLowerCase()].includes(n?.tagName?.toLowerCase())||n?.tagName?.toLowerCase().indexOf("snippyly-")>=0||n?.className?.split&&(n?.className?.split(" ")?.indexOf("snippyly-overlay-panel")>=0||n?.className?.split(" ")?.indexOf("cdk-overlay-container")>=0))&&!o?.includes(n?.tagName?.toLowerCase())?!0:n?.parentNode&&Co(n?.parentNode,o),l0=[N.TAGS.SNIPPYLY_TEXT_HIGHLIGHT?.toLowerCase()],XK=(n,o=l0)=>{try{let r=n?.nodeType===Node.TEXT_NODE?n?.parentElement:n;if(!r)return!1;let e=r;for(;e;){let t=e?.tagName?.toLowerCase();if(t&&(t.indexOf("velt-")>=0&&t!==N.TAGS.VELT_VIDEO_PLAYER.toLowerCase()||t.indexOf("snippyly-")>=0)&&!o?.includes(t))return!0;e=e?.parentElement}return!1}catch(r){return it.catch("Error in utils isNodeInsideSnippylyElement: ",r),!1}},xN=(n,o)=>{try{return(n.indexOf("velt-")>=0&&n!==N.TAGS.VELT_VIDEO_PLAYER.toLowerCase()||n.indexOf("snippyly-")>=0)&&!o?.includes(n)}catch(r){return it.catch("Error in utils isVeltTagName: ",r),!1}},ohe=(n,o=l0,r=!0)=>{try{let e=[],t=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:a=>{if(a.nodeType===Node.ELEMENT_NODE){let l=a?.tagName?.toLowerCase();return l&&xN(l,o)||r&&l==="script"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_SKIP}return NodeFilter.FILTER_ACCEPT}}),i;for(;i=t.nextNode();)e.push(i);return e}catch(e){return it.catch("Error in utils getFilteredTextNodes: ",e),[]}},Zr=n=>{try{return!!document?.body?.contains(n)}catch(o){return it.catch("Error in utils isElementInsideBody: ",o),!1}};var Mr=(n,o)=>{try{return Object.prototype.toString.call(n)===Object.prototype.toString.call(o)?Object.prototype.toString.call(n)==="[object Object]"||Object.prototype.toString.call(n)==="[object Array]"?Object.keys(n).length!==Object.keys(o).length?!1:Object.keys(n).every(r=>Mr(n[r],o[r])):n===o:!1}catch(r){return it.catch("Error in utils deepCompare: ",r),!1}},Wu=(n,o,r=1)=>{try{if(o){let e=ohe(o),t=e.reduce((v,u)=>v+(u.textContent||""),""),i=aGe(t,n,r);if(i<0)return[];let a=[],l=n.length,s=i+l,d=0;for(let v=0;v<e.length;v++){let u=e[v],_=d;if(d+=u.textContent?.length,d>=i&&!a.length?a.push({textNode:u,startOffset:i-_}):d>=i&&d<s&&a.push({textNode:u}),d>=s){if(a.length===1&&a[0].textNode===u){a.push({textNode:u,endOffset:i-_+n.length});break}let I=l;a.forEach(A=>{I-=A.textNode.textContent?.length-(A.startOffset||0)}),a.push({textNode:u,endOffset:I});break}}return a}return[]}catch(e){return it.catch("Error in utils calculateNodes: ",e),[]}},aGe=(n,o,r=1)=>{try{if(n?.includes(o)){let e=n.split(o,r);return e.length===r?e.join(o).length:-1}else return-1}catch(e){return it.catch("Error in utils getTextPosition: ",e),-1}},s0=(n,o,r,e,t)=>{try{let i=new Range;i.setStart(n,o),i.setEnd(r,e);let a=i.commonAncestorContainer,s=(a.nodeType===Node.ELEMENT_NODE?a:a.parentElement)?.querySelector("script")!==null,d,v=i.cloneContents();s&&v.querySelectorAll("script").forEach(_=>_.remove()),v.querySelectorAll("*").forEach(_=>{let I=_?.tagName?.toLowerCase();I&&xN(I,l0)&&_.remove()}),d=v.textContent||"";let u=0;if(n.nodeType===Node.TEXT_NODE){let _=n,I="";if(_)for(;_=_.previousSibling;){if(_.nodeType===Node.ELEMENT_NODE){let A=_?.tagName?.toLowerCase();if(A&&xN(A,l0))continue}if(_.nodeType===Node.TEXT_NODE)!XK(_)&&!(s&&_.parentElement?.tagName==="SCRIPT")&&(I=(_.textContent||"")+I);else if(_.nodeType===Node.ELEMENT_NODE){if(s&&_.tagName==="SCRIPT")continue;let A=_.cloneNode(!0);s&&A.querySelectorAll("script").forEach(M=>M.remove()),A.querySelectorAll("*").forEach(M=>{let B=M?.tagName?.toLowerCase();B&&xN(B,l0)&&M.remove()}),I=(A.textContent||"")+I}}if(I){let A=new RegExp(Qc(t),"g");u=(I.match(A)||[]).length}}if(d){let _=new RegExp(Qc(t),"g");return(d.match(_)||[]).length+u}else return u}catch(i){return it.catch("Error in utils getSelectedTextOccurrenceInRange: ",i),0}},Qc=n=>{try{return n&&typeof n=="string"?n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):n}catch(o){return it.catch("Error in utils escapeRegExp: ",o),n}},n1=n=>{try{return n==null?null:n.scrollHeight>n.clientHeight?n:n1(n?.parentNode)}catch(o){return it.catch("Error in utils getScrollableParent: ",o),null}},Hu=n=>{try{return n==null?[]:n.scrollHeight>n.clientHeight?[n,...Hu(n?.parentNode)]:Hu(n?.parentNode)}catch(o){return it.catch("Error in utils getScrollableParents: ",o),[]}},JK=(n,o)=>{try{if(n&&o){let r=n.getBoundingClientRect(),e=o.getBoundingClientRect(),t=r.top-e.top+(o.tagName?.toLowerCase()==="html"?0:o.scrollTop),i=r.left-e.left;return{top:t,left:i}}else return null}catch(r){return it.catch("Error in utils getRelativeTopLeftPosition: ",r),null}},ed=(n,o)=>`${Qn(n+"_"+o)}`,no=()=>{try{let n=new Oo;return n.url=window.location.href,n.path=window.location.pathname,n.queryParams=window.location.search,n.baseUrl=window.location.origin,n.title=document.title,n}catch(n){it.catch("Error in utils getPageInfo: ",n);return}},fg=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(N.ATTRIBUTES.VELT_COMMENT_DISABLED)?!0:fg(n?.parentElement):!1}catch(o){return it.catch("Error in utils isCommentDisabledOnElement: ",o),!1}},ON=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(N.ATTRIBUTES.VELT_TAG_DISABLED)?!0:ON(n?.parentElement):!1}catch(o){return it.catch("Error in utils isTagDisabledOnElement: ",o),!1}},AN=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(N.ATTRIBUTES.VELT_ARROW_DISABLED)?!0:AN(n?.parentElement):!1}catch(o){return it.catch("Error in utils isArrowDisabledOnElement: ",o),!1}},MN=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(N.ATTRIBUTES.VELT_AREA_DISABLED)?!0:MN(n?.parentElement):!1}catch(o){return it.catch("Error in utils isAreaDisabledOnElement: ",o),!1}},PN=n=>{try{return n?n?.hasAttribute&&n?.hasAttribute(N.ATTRIBUTES.VELT_RECORDER_DISABLED)?!0:PN(n?.parentElement):!1}catch(o){return it.catch("Error in utils isRecorderDisabledOnElement: ",o),!1}};var fa=()=>{try{return window?.Snippyly?.version}catch(n){return it.catch("Error in utils getSdkVersion: ",n),null}},RN=n=>{try{return Object.fromEntries(Object.entries(n).filter(([o,r])=>r!==void 0))}catch(o){return it.catch("Error in utils removeUndefinedKeys: ",o),n}},NN=n=>{try{let o=new URL(n);return Object.values(N.URL_PARAMS).forEach(r=>{o.searchParams.delete(r)}),o.href}catch(o){return it.catch("Error in utils excludeSnippylyParamsFromUrl: ",o),n}},Vs=n=>{try{navigator.clipboard.writeText(n)}catch(o){it.catch("Error in copyToClipboard: ",o)}},l3=n=>{try{let o=ihe(n);return o&&typeof o=="string"&&o.includes("/svg")&&(o=o.split("/svg")[0]+"/*[name()='svg']"),o}catch(o){it.catch("Error in utils getXPath:",o)}},ihe=n=>{try{if(n){if(typeof n=="string")return document.evaluate(n,document,null,0,null);if(!n||n.nodeType!=1)return"";if(n.id&&n?.tagName?.toLowerCase()!=="svg"&&document.querySelectorAll(`[id='${n.id}']`)?.length===1)return"//*[@id='"+n.id+"']";let o=[].filter.call(n.parentNode?.children?n.parentNode?.children:[],function(r){return r.tagName==n.tagName});return ihe(n.parentNode)+"/"+n.tagName.toLowerCase()+(o.length>1?"["+([].indexOf.call(o,n)+1)+"]":"")}}catch(o){it.catch("Error in utils calculateXPath:",o)}},ahe=n=>{try{let o=[];return n.forEach(r=>{let e={};e.commonAncestorContainer=lGe(r.commonAncestorContainer),e.text=r.toString(),e.occurrence=s0(r.commonAncestorContainer,0,r.startContainer,r.startOffset,r.toString())+1,o.push(e)}),o}catch{return[]}},lGe=n=>{try{if(n.nodeType===Node.TEXT_NODE){let o=1,r=n.previousSibling;for(;r;)r.nodeType===Node.TEXT_NODE&&o++,r=r.previousSibling;return l3(n.parentElement)}else return l3(n)}catch(o){return it.catch("Error in utils getXPathForText: ",o),l3(n)}},QK=(n,o)=>{try{return n?n?.hasAttribute&&(o&&n.hasAttribute("contenteditable")||n?.getAttribute(N.ATTRIBUTES.VELT_LIVE_SELECTION_ENABLED)==="true")?n:QK(n?.parentElement,o):null}catch(r){return it.catch("Error in utils getSelectionEnabledElement: ",r),null}},FN=(n,o=!0)=>{try{if(o)return ohe(n);let r,e=[],t=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);for(;r=t.nextNode();)e.push(r);return e}catch(r){return it.catch("Error in utils getTextNodesInsideElement: ",r),[]}},lhe=n=>{try{return n<576||n>=576&&n<767?"Mobile":n>=768&&n<992?"Tablet":n>=992&&n<1520?"Desktop":"Monitor"}catch(o){return it.catch("Error in utils getDeviceTypeFromDeviceWidth: ",o),""}},qu=n=>new Promise(o=>setTimeout(o,n)),she=(n,o=0)=>new Promise((r,e)=>{let t=document.createElement("video"),i=navigator.userAgent.includes("Firefox");i&&(t.preload="auto"),t.setAttribute("src",URL.createObjectURL(n)),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 l=document.createElement("canvas");l.width=t.videoWidth,l.height=t.videoHeight;let s=l.getContext("2d");s.drawImage(t,0,0,l.width,l.height),s.canvas.toBlob(d=>{t.remove(),r(d)},"image/jpeg",.75)})};if(i&&t.duration>0&&t.duration<10&&n.size>1e6){(()=>{setTimeout(()=>{t.duration<o&&(o=Math.max(.1,t.duration/2)),a()},1e3)})();return}a()})}),che=n=>{try{return new Promise((o,r)=>{let e=new FileReader;e.onloadend=()=>o(e.result),e.readAsDataURL(n)})}catch(o){return it.catch("Error in utils blobToBase64: ",o),Promise.resolve("")}},eZ=(n,o="image/jpeg")=>{try{let r=atob(n.split(",")[1]),e=new ArrayBuffer(r.length),t=new Uint8Array(e);for(let i=0;i<r.length;i++)t[i]=r.charCodeAt(i);return new Blob([e],{type:o})}catch(r){return it.catch("Error in utils base64ToBlob: ",r),null}},dhe=(n,o,r=20)=>new Promise((e,t)=>{let i=new Image;i.crossOrigin="Anonymous",i.onload=()=>{let a=i.width,l=i.height,s=600,d=l/a*s,v="http://www.w3.org/2000/svg",u=document.createElementNS(v,"svg");u.setAttribute("xmlns",v),u.setAttribute("width",s.toString()),u.setAttribute("height",d.toString()),u.setAttribute("viewBox",`0 0 ${s} ${d}`);let _=document.createElementNS(v,"circle"),I=document.createElementNS(v,"polygon"),A=16,M=A+16,B=s/2,q=d/2;if(_.setAttribute("cx",B.toString()),_.setAttribute("cy",q.toString()),_.setAttribute("r",M.toString()),_.setAttribute("fill","lightgrey"),I.setAttribute("points",`${B-A/2},${q-A} ${B-A/2},${q+A} ${B+A},${q}`),I.setAttribute("fill","#ffffff"),u.appendChild(_),u.appendChild(I),o){let xe=o.length*16-10,ye=16*1.5,Oe=(s-xe)/2,Re=d-ye-10,Ue=document.createElementNS(v,"rect");Ue.setAttribute("x",Oe.toString()),Ue.setAttribute("y",Re.toString()),Ue.setAttribute("width",xe.toString()),Ue.setAttribute("height",ye.toString()),Ue.setAttribute("fill","#353945b3"),Ue.setAttribute("rx","12"),u.appendChild(Ue);let ze=document.createElementNS(v,"text");ze.textContent=o,ze.setAttribute("x",(s/2).toString()),ze.setAttribute("y",(Re+16).toString()),ze.setAttribute("font-size","16"),ze.setAttribute("text-anchor","middle"),ze.setAttribute("fill","white"),u.appendChild(ze)}let ae=new XMLSerializer().serializeToString(u),Ce=new Image,oe=new Blob([ae],{type:"image/svg+xml;charset=utf-8"}),fe=URL.createObjectURL(oe);Ce.onload=()=>{let Ie=document.createElement("canvas");Ie.width=s,Ie.height=d;let xe=Ie.getContext("2d");xe.beginPath(),xe.moveTo(r,0),xe.lineTo(s-r,0),xe.quadraticCurveTo(s,0,s,r),xe.lineTo(s,d-r),xe.quadraticCurveTo(s,d,s-r,d),xe.lineTo(r,d),xe.quadraticCurveTo(0,d,0,d-r),xe.lineTo(0,r),xe.quadraticCurveTo(0,0,r,0),xe.closePath(),xe.clip(),xe.drawImage(i,0,0,s,d),xe.drawImage(Ce,0,0,s,d);let ye=Ie.toDataURL("image/png");e(ye)},Ce.onerror=t,Ce.src=fe},i.onerror=t,i.src=n});var LN=n=>{try{return n?.replace(/[\n\t\u200D]/g,"")?.split(/\s+/)?.filter(e=>e?.trim()?.length)||[]}catch(o){return it.catch("Error in utils getWords: ",o),[]}},tl=(n,o=[])=>{try{let r=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelector(r)}catch(r){return it.catch("Error in utils getElementByAttributes: ",r),null}},mhe=(n,o=[])=>{try{let r=o.map(e=>`[${e}="${n}"]`).join(",");return document.querySelectorAll(r)}catch(r){return it.catch("Error in utils getElementsByAttributes: ",r),[]}},Jd=n=>{try{let o=Math.floor(n/3600),r=Math.floor((n-o*3600)/60),e=Math.floor(n-o*3600-r*60);return o&&o<10&&(o="0"+o),r<10&&(r="0"+r),e<10&&(e="0"+e),(o?o+":":"")+r+":"+e}catch{return""}},vhe=(n,o=10)=>{try{if(!n||!n.currentTime)throw new Error("Invalid video element reference provided");let r=n.currentTime,e=Math.floor(r/o)*o,t=e+o;return{startSlot:Jd(e),endSlot:Jd(t),timeSlot:Jd(e)+" - "+Jd(t)}}catch{return null}},c0=(n,o=["@"])=>{try{let r="",e,t=n.getRootNode();if(t instanceof ShadowRoot?e=t?.getSelection():e=window.getSelection(),e?.rangeCount){let i=e.getRangeAt(0),a=i.startOffset,l=i.endOffset,s=i?.commonAncestorContainer?.textContent;s?r=sGe(s,l,o):r=""}return r}catch(r){return it.catch("Error in utils getWordAtCursor: ",r),""}};var sGe=(n,o,r=["@"])=>{try{let e=-1,t=!1;for(let i of r){let a=n.lastIndexOf(i,o),l=a>0?n.lastIndexOf(i,a-1):-1;if(a>e){let s=EN(n,a,o),d=TN(n,a,o);if(s||d){if(l!==-1){let v=EN(n,l,a),u=TN(n,l,a);!v&&!u&&(e=l,t=!0)}}else e=a,t=!0}}return e!==-1&&t?n.substring(e,o):""}catch(e){return it.catch("Error in utils getStringFromLastAtSymbol: ",e),""}},EN=(n,o,r)=>{try{if(o===0)return!1;let e=n.charAt(o-1);return!(e===" "||e==="\xA0"||e===`
196
- `||e===" "||[",",":",";"].includes(e))}catch(e){return it.catch("Error in utils isHotkeyDisabledForAutocomplete: ",e),!1}},TN=(n,o,r)=>{try{return!!n.substring(o+1,r).startsWith(" ")}catch(e){return it.catch("Error in utils isHotkeyFollowedBySpace: ",e),!1}},s3=(n,o,r=["@"])=>{try{let e=cGe(n),t=null;try{e&&typeof e.getSelection=="function"&&(t=e.getSelection())}catch{}if(t||(t=window.getSelection()),t?.rangeCount){let i=t.getRangeAt(0),a=i.startOffset,l=i?.commonAncestorContainer?.textContent;if(l){let s=-1;for(let d of r){let v=l.lastIndexOf(d,a),u=v>0?l.lastIndexOf(d,v-1):-1;if(v>s){let _=EN(l,v,a),I=TN(l,v,a);if(_||I){if(u!==-1){let A=EN(l,u,v),M=TN(l,u,v);!A&&!M&&(s=u)}}else s=v}}if(s!==-1){let d=l.substring(0,s),v=l.substring(i.endOffset),u=document.createElement("span");u.textContent=o,u.style.color="var(--velt-accent)";let _=Date.now()+"_"+Math.random().toString(36).substr(2,9);u.setAttribute("data-recently-added",_),setTimeout(()=>{u.hasAttribute("data-recently-added")&&u.removeAttribute("data-recently-added")},5e3);let I=i.commonAncestorContainer;if(I.nodeType===Node.TEXT_NODE){let A=I.parentNode;if(A){let M=document.createTextNode(d),B=document.createTextNode(v);A.replaceChild(B,I),A.insertBefore(u,B),A.insertBefore(M,u);try{let q=document.createRange();q.setStartAfter(u),q.collapse(!0),t?.removeAllRanges(),t?.addRange(q)}catch(q){it.catch("Error positioning cursor after span:",q);try{let ae=document.createRange();ae.selectNodeContents(n),ae.collapse(!1),t?.removeAllRanges(),t?.addRange(ae)}catch(ae){it.catch("Error with fallback cursor positioning:",ae)}}}}}}}}catch(e){it.catch("Error in utils replaceWordAtCursor: ",e)}},c3=()=>{try{let o=window.getSelection()?.getRangeAt(0),r=o?.commonAncestorContainer,e=o?.startContainer,t=o?.endContainer,i=[];i.push(r),i.push(e),i.push(t);let a=!1;for(let l of i)if(l&&Co(l,[N.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,N.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,N.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,N.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(n){return it.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",n),!1}},ghe=(n,o,r)=>{try{let e=document.querySelector(`[id=${n}]`);if(e)e.name=o,e.content=r;else{let t=document.createElement("meta");t.id=n,t.name=o,t.content=r,document.getElementsByTagName("head")[0].appendChild(t)}}catch{}},uhe=n=>{try{if(n){let o=document.querySelector(`[id=${n}]`);o&&o.remove()}}catch{}},phe=()=>{try{let o=new Date().getTimezoneOffset(),r=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${r?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(n){return it.catch("Error in utils getTimezone: ",n),""}},hhe=()=>{try{let n=[];return document.querySelectorAll("*").forEach(r=>{(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth||["auto","scroll"].includes(getComputedStyle(r).overflow))&&n.push(r)}),n}catch(n){return it.catch("Error in utils getScrollableElements: ",n),[]}},fhe=(n,o)=>Math.sqrt((n.x-o.x)**2+(n.y-o.y)**2),tZ=(n,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let r=n;for(;r.children.length>0;){let e=null,t=Number.MAX_SAFE_INTEGER;for(let i=0;i<r.children.length;i++){let a=r.children[i],l=a.getBoundingClientRect(),s={x:l.left+l.width/2,y:l.top+l.height/2},d=fhe(s,o);(l.top>=0||l.bottom<=window.innerHeight)&&l.width>0&&l.height>0&&d<=t&&(e=a,t=d)}if(e===null)break;r=e}return r}catch(r){return it.catch("Error in utils getInnermostElement: ",r),null}},Che=n=>{try{let{offsetWidth:o,offsetHeight:r,scrollTop:e}=n,t=n,i={x:o/2,y:e+r/2};for(;t.children.length>0;){let a=null,l=Number.MAX_SAFE_INTEGER;for(let s=0;s<t.children.length;s++){let d=t.children[s],v={x:d.offsetLeft+d.offsetWidth/2,y:d.offsetTop+d.offsetHeight/2},u=fhe(v,i);d.offsetTop>=0&&d.offsetWidth>0&&d.offsetHeight>0&&u<=l&&(a=d,l=u)}if(a===null)break;t=a}return t}catch(o){return it.catch("Error in utils getNestedInnermostElement: ",o),null}},bhe=()=>{try{let n=window.innerWidth/2,o=window.innerHeight/2,r=document.elementFromPoint(n,o);for(;r&&r.tagName==="BODY";)o+=2,r=document.elementFromPoint(n,o);return r}catch(n){return it.catch("Error in utils getCenteredBackgroundElement: ",n),null}},nZ=(n,o,r=!1)=>{try{let e=n.getBoundingClientRect(),t=o.getBoundingClientRect(),i=o.offsetTop;r&&(i=i-e.height/2+t.height/2),n.scrollTo({top:i,behavior:"smooth"})}catch(e){it.catch("Error in utils nestedScrollIntoView: ",e)}},UN=(n,o=!0)=>{try{let r=document.body.getBoundingClientRect(),e=n.getBoundingClientRect(),t=e.top-r.top,i=window.innerHeight,a=t;o&&(a=a-i/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(r){it.catch("Error in utils scrollIntoView: ",r)}},_he=(n=!1)=>{try{let o=!0;return n&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return it.catch("Error in utils isTouchDevice: ",o),!1}},She=(n,o,r)=>{try{return(1-r)*n+r*o}catch(e){it.catch("Error in utils lerp: ",e)}return 0},yhe=(n,o)=>{try{if(n===void 0)return n;if(n=n.replace("#",""),n.length===6){let r=parseInt(n,16),e=(r>>16)+o;e>255&&(e=255),e<0&&(e=0);let t=(r&255)+o;t>255&&(t=255),t<0&&(t=0);let i=(r>>8&255)+o;return i>255&&(i=255),i<0&&(i=0),`#${(t|i<<8|e<<16).toString(16)}`}else return n}catch(r){it.catch("Error in utils multiplyColor: ",r)}return n},khe=n=>{try{return n in N.TEXT_COLOR_MAP?N.TEXT_COLOR_MAP[n]:"#141416"}catch(o){return it.catch("Error in generateUserColor:",o),"#141416"}},Qd=()=>{try{let n=localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(n)return JSON.parse(n)}catch(n){return it.catch("Error in getDefaultMediaStreamOptions:",n),{}}},VN=(n,o)=>{try{let r=o*(Math.PI/180),e=Math.cos(r);return e?n/e:n}catch(r){return it.catch("Error in calculateHypotenuse:",r),0}},rZ=(n,o,r=!0)=>{try{let e=[],t=r?n:n.parentNode;for(;t;)e.push(t),t=t.parentNode;let i=r?o:o.parentNode;for(;i;){if(e.indexOf(i)!==-1)return i;i=i.parentNode}return null}catch(e){return it.catch("Error in utils findCommonParent: ",e),null}},oZ=(n,o,r,e,t=!1)=>{try{let i,a;if(t){let l=r,s=e;if(l===s)i=n,a=o;else{let d=0,v=0,u=l;for(;u&&u!==s;)d+=u.offsetLeft,v+=u.offsetTop,u=u.parentElement;i=d+n,a=v+o}}else{let l=r.getBoundingClientRect(),s=e.getBoundingClientRect(),d=l.left+n,v=l.top+o;i=d-s.left,a=v-s.top}return{x:i,y:a}}catch(i){return it.catch("Error in utils calculateParentCoordinates: ",i),{x:n,y:o}}},Yu=n=>{try{let o={height:0,width:0};if(typeof n?.getBBox=="function"){let r=n?.getBBox(),e=n?.getBoundingClientRect();o.height=parseFloat(e?.height||r.height||0),o.width=parseFloat(e?.width||r.width||0)}else{let r=window.getComputedStyle(n);if(o.height=n?.clientHeight||parseFloat(r.getPropertyValue("height"))||0,o.width=n?.clientWidth||parseFloat(r.getPropertyValue("width"))||0,n?.getBoundingClientRect&&typeof n?.getBoundingClientRect=="function"){let e=n?.getBoundingClientRect();o?.height||(o.height=e?.height||n?.clientHeight||n?.offsetHeight||0),o?.width||(o.width=e?.width||n?.clientWidth||n?.offsetWidth||0)}}return o}catch(o){return it.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},Qm=n=>{try{let o=n;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return it.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},cGe=n=>{try{let o=n;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){it.catch("Error in utils findShadowRoot: ",o)}return null},xhe=n=>{try{let o=["attachment","attachments","chunkUrls","transcription","color","position","positionX","positionY","resolved","inProgress","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource"],r=JSON.parse(JSON.stringify(n)),e={};return Object.keys(r).forEach(t=>{o.includes(t)||(e[t]=r[t])}),JSON.parse(JSON.stringify(e))}catch(o){return it.catch("Error in utils getRecorderAnnotationForClient: ",o),null}},r1=n=>n===null||typeof n>"u",o1=(n,o)=>{try{return!!n?.closest(`[${o}]`)}catch(r){return it.catch("Error in utils hasParentWithAttribute: ",r),!1}},iZ=(n,o=!0)=>{try{let r=[];if(!n||!(n instanceof HTMLElement))return[];o&&r.push(n);for(let e=0;e<n.children.length;e++){let t=n.children[e];r=r.concat(iZ(t))}return r}catch(r){return it.catch("Error in utils getAllNestedChildren: ",r),[]}},Ihe=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(n){return it.catch("Error in utils isTabActive: ",n),!1}},aZ=n=>{try{let o="",r=n?.getAttribute("src");if(r)o=`${Qn(r)}`;else{let e=n?.querySelectorAll("source");if(e&&e.length>0){let i=e[0]?.getAttribute("src");i&&(o=`${Qn(i)}`)}}return o}catch{return""}},He=n=>{try{return!(n&&(n?.children?.length>0||n?.textContent?.trim()?.length>0))}catch(o){return it.catch("Error in utils isTemplateEmpty: ",o),!0}},Cl=(n,o)=>{try{if(!n||!o)return;let r=[],e="",t=0;for(let s=0;s<o.length;s++){let d=o[s];d==="["?(t++,t===1&&e&&(r.push(e),e=""),e+=d):d==="]"?(t--,e+=d,t===0&&(r.push(e),e="")):d==="."&&t===0?e&&(r.push(e),e=""):e+=d}e&&r.push(e);let i,a=h({},n),l=r.reduce((s,d)=>{if(s==null)return;so(s)&&(i=s,s=s());let v=d.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(v){let _=v[1];if(/^\d+$/.test(_)){let I=parseInt(_,10);return Array.isArray(s)?s[I]:void 0}if(_.startsWith("'")&&_.endsWith("'")||_.startsWith('"')&&_.endsWith('"')){let I=_.slice(1,-1);return s[I]}if(_.includes(".")||_.includes("[")){let I=Cl(a,_);so(I)&&(I=I());let A=I?.toString()||"";return s[A]}if(a[_]!==void 0){let I=a[_];return so(I)&&(I=I()),s[I]}return s[_]}let u=d;return(d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))&&(u=d.slice(1,-1)),u==="length"&&Array.isArray(s)?s.length:s[u]},n);return i?ie(()=>{try{let s=h({},n);return r.reduce((d,v)=>{if(d==null)return;so(d)&&(d=d());let u=v.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(u){let I=u[1];if(/^\d+$/.test(I)){let A=parseInt(I,10);return Array.isArray(d)?d[A]:void 0}if(I.startsWith("'")&&I.endsWith("'")||I.startsWith('"')&&I.endsWith('"')){let A=I.slice(1,-1);return d[A]}if(I.includes(".")||I.includes("[")){let A=Cl(s,I);so(A)&&(A=A());let M=A?.toString()||"";return d[M]}if(s[I]!==void 0){let A=s[I];return so(A)&&(A=A()),d[A]}return d[I]}let _=v;return(v.startsWith("'")&&v.endsWith("'")||v.startsWith('"')&&v.endsWith('"'))&&(_=v.slice(1,-1)),d[_]},n)}catch{return""}}):l}catch{return""}},d0=(n,o)=>{try{return!!(n?.locationId&&(n.locationId===o?.locationId||o?.location?.id===String(n.locationId))||n?.location?.id&&(n.location.id===o?.location?.id||n.location.id===String(o?.locationId)))}catch(r){return it.catch("Error in utils isLocationSame: ",r),!1}},Ehe=()=>{try{let n=document.activeElement,o=new Set,r=10,e=0;for(;n&&n.shadowRoot&&!(o.has(n)||(o.add(n),n=n.shadowRoot.activeElement,e++,e>r)););return n}catch(n){return it.catch("Error in utils getActiveElement: ",n),null}},Jt=(n,o)=>{try{return typeof n=="object"&&typeof o=="object"?JSON.stringify(n)===JSON.stringify(o):n===o}catch{return!1}},ti=(n,o=0)=>{try{let r=JSON.parse(JSON.stringify(n));return n?.clientDocumentId&&(r.documentId=n.clientDocumentId),n?.clientOrganizationId&&(r.organizationId=n.clientOrganizationId),n?.documentMetadata&&o<5&&(r.documentMetadata=ti(n.documentMetadata,o+1)),delete r?.clientDocumentId,delete r?.clientOrganizationId,delete r?.veltFolderId,delete r?.parentVeltFolderId,delete r?.pageInfo,r}catch{return n}},Ra=n=>{try{if(!n.some(a=>a?.value?.data))return{};let o=null,r=n.reduce((a,l)=>Math.max(a,l.timestamp),0),e=n.find(a=>a.timestamp===r);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let i=n.map(a=>a.value).reduce((a,l)=>({data:h(h({},a?.data??{}),l?.data??{})}),{});return i.operation=o,i}catch{return{}}},Ai=(n,o,r)=>J(null,null,function*(){try{let e=0;for(;e<=(r.retryCount||0);)try{let t=yield n();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>(r.retryCount||0))return{success:!1,statusCode:t.statusCode,message:`${o} failed after ${e} attempts with status code ${t.statusCode}`};r.retryDelay&&(yield new Promise(i=>setTimeout(i,r.retryDelay)));continue}return t}catch(t){if(e++,e>(r.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${t instanceof Error?t.message:"Unknown error"}`};r.retryDelay&&(yield new Promise(i=>setTimeout(i,r.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"}`}}}),ji=(n,o,r,e)=>J(null,null,function*(){try{let i=h(h({},{"Content-Type":"application/json"}),o||{}),a=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(r)});if(!a.ok)return it.catch(`Error in makeConfigBasedRequest: ${a.status} ${a.statusText}`),e?{data:{},success:!1,statusCode:a.status}:{success:!1,statusCode:a.status};let l=yield a.json();return e?{data:l?.data??{},success:!0,statusCode:200}:{success:!0,statusCode:200}}catch(t){return it.catch("Error in makeConfigBasedRequest:",t),e?{data:{},success:!1,statusCode:500}:{success:!1,statusCode:500}}}),The=n=>{try{return!n||!n?.access?[]:Object.keys(n.access).sort().map(t=>n.access?.[t]?.map(i=>`${t}:${i}`)??[]).reduce((t,i)=>t.flatMap(a=>i.map(l=>[...a,l])),[[]]).map(t=>t.join("_"))}catch(o){return it.catch("Error in utils generateProcessedContext: ",o),[]}},d3=n=>{try{if(!n||!n?.access)return[];let o=Object.keys(n.access).sort(),e=(i=>{let a=[],l=Math.pow(2,i.length);for(let s=1;s<l;s++){let d=[];for(let v=0;v<i.length;v++)s&1<<v&&d.push(i[v]);a.push(d)}return a})(o),t=[];for(let i of e){let a=i.map(l=>{let s=n.access?.[l];return s==null?null:`${l}:${s}`}).filter(l=>l!==null);a.length>0&&t.push(a.join("_"))}return[...new Set(t)]}catch(o){return it.catch("Error in utils generateAllContextCombos: ",o),[]}},BN=({input:n})=>{try{if(!n||!n?.access)return[];let o=n?.access,r=Object.keys(o).sort(),e=[];for(let i of r){let a=o[i];a!=null&&Array.isArray(a)&&a.length>0&&e.push({key:i,values:a})}return e.length===0?[]:e.reduce((i,{key:a,values:l})=>i.length===0?l.map(s=>[{key:a,value:s}]):i.flatMap(s=>l.map(d=>[...s,{key:a,value:d}])),[]).map(i=>{let a={};return i.forEach(({key:l,value:s})=>{a[l]=s}),{access:a}})}catch(o){return it.catch("Error in utils expandContextArraysToSingleValues: ",o),[]}},whe=({input:n})=>{try{if(!n||n.length===0)return{access:{}};let o=new Set;n.forEach(e=>{e?.access&&Object.keys(e.access).forEach(t=>o.add(t))});let r={};for(let e of Array.from(o).sort()){let t=new Set;n.forEach(i=>{if(i?.access){let a=i.access[e];a!=null&&t.add(a)}}),r[e]=t.size>0?Array.from(t).sort():null}return{access:r}}catch(o){return it.catch("Error in utils combineContextsToArrays: ",o),{access:{}}}},bl=t=>J(null,[t],function*({data:n,getSdkProxy:o,userId:r,methodName:e}){try{let i="sdkproxyencryptionanddecryptiononsdk"+(r??""),a=yield dGe({data:n,key:i}),l=(yield o({veltData:a}))?.data?.data?.veltData||{};return yield t1(l,i)}catch(i){return it.catch("Error in utils sdkProxyEncryptDecrypt: "+(e??""),i),n}}),dGe=r=>J(null,[r],function*({data:n,key:o}){try{return yield fc(n,o)}catch{return n}}),lZ=(n,o)=>J(null,null,function*(){try{let r=0;for(;r<=(o.retryCount||0);)try{let e=yield n();if(!e)throw new Error("No response received");return e}catch{if(r++,r>=(o.retryCount||0))return null;o.retryDelay&&(yield new Promise(t=>setTimeout(t,o.retryDelay)))}return null}catch{return null}}),Uo=n=>{try{if(n&&typeof n=="object"){let o=JSON.parse(JSON.stringify(n));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,delete o?.email_lowercase,delete o?.name_lowercase,o}else return null}catch(o){return it.catch("Error in utils getUserForClient: ",o),null}},Wr=({url:n,apiProxyDomain:o})=>{try{if(o){let r=new URL(n);r.origin&&(n=n.replace(r.origin,o))}return n}catch(r){return it.catch("Error in utils getResolvedApiUrl: ",r),n}},Dhe=(n,o)=>{try{if(!n||!(n instanceof Element))return!1;let r,e;if(o&&typeof o.x=="number"&&typeof o.y=="number")r=o.x,e=o.y;else{let i=n.getBoundingClientRect();r=i.left+i.width/2,e=i.top+i.height/2}let t=document.elementFromPoint(r,e);return!(!t||t===n||n.contains(t))}catch{return!1}};var st=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.liveStateSyncEvents=Object.values(Y.Events.LiveStateSync||{}),this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3,this.analyticsQueue=[],this.batchTimer=null,this.BATCH_WINDOW_MS=5*1e3,this.MAX_BATCH_SIZE=50;try{this.updateDefaultProperties({sdkVersion:fa()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(t){it.catch("Error in AnalyticsService constructor: ",t)}}updateDefaultProperties(e={}){this.defaultProperties=h(h({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(t){it.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]=h(h({},this.defaultProperties.featureConfigs[e]),t)}catch(i){it.catch("Error in AnalyticsService setFeatureConfig: ",i)}}setSF(e){try{this.sf=e}catch(t){it.catch("Error in AnalyticsService setSF: ",t)}}setAuthService(e){try{this.authService=e}catch(t){it.catch("Error in AnalyticsService setAuthService: ",t)}}setCommentService(e){try{this.commentService=e}catch(t){it.catch("Error in AnalyticsService setCommentService: ",t)}}setConfigService(e){try{this.configService=e}catch(t){it.catch("Error in AnalyticsService setConfigService: ",t)}}setDomService(e){try{this.domService=e}catch(t){it.catch("Error in AnalyticsService setDomService: ",t)}}setLiveStateService(e){try{this.liveStateService=e}catch(t){it.catch("Error in AnalyticsService setLiveStateService: ",t)}}setAreaService(e){try{this.areaService=e}catch(t){it.catch("Error in AnalyticsService setAreaService: ",t)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(t){it.catch("Error in AnalyticsService setRecorderAnnotationService: ",t)}}setReactionService(e){try{this.reactionService=e}catch(t){it.catch("Error in AnalyticsService setReactionService: ",t)}}setUserService(e){try{this.userService=e}catch(t){it.catch("Error in AnalyticsService setUserService: ",t)}}identifyUser(e,t,i={}){try{this.userId=e;let a=typeof t=="object"?JSON.parse(JSON.stringify(t)):t;this.userService?.externalUserDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let l=this.defaultProperties?this.defaultProperties.apiKey:null;if(En.production||En.staging){let s=Date.now(),d={userId:e,clientUserId:this.user?.userId,traits:y(h({},a),{apiKey:l,forceReset:i?.forceReset,eventTimestamp:s}),properties:y(h({},this.defaultProperties),{eventTimestamp:s}),sf:this.sf,context:this.getContext(),eventTimestamp:s};this.setAnalytics("identify",d)}if(this.userId&&this.draftEvents?.length){let s=this.draftEvents?.slice();this.draftEvents=[],s?.forEach(d=>{switch(d.type){case"track":d?.data?.eventName&&this.trackEvent(d.data.eventName,d.data.properties,d.data.mergeDefaultProperties,d.data.userId,d.data.clientUserId);break;default:break}})}}catch(a){it.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,t="",i={}){try{if((En.production||En.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:i,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){it.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(s){return J(this,arguments,function*(e,t={},i=!0,a,l){try{if(this.sf&&Xpe.includes(e))return Promise.resolve();if(En.production||En.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return Promise.resolve();let d=Date.now();if(this.eventRateLimitCache[e]&&d-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 v=h({eventName:e},t||{});this.triggerTrackEvent(Y.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,v,i,a,l)}return Promise.resolve()}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:d,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,t,i,a,l)}else return t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.draftEvents.push({type:"track",data:{eventName:e,properties:t,mergeDefaultProperties:i,userId:a,clientUserId:l}}),Promise.resolve();return Promise.resolve()}catch(d){return it.catch("Error in AnalyticsService trackEvent: ",d),Promise.resolve()}})}triggerTrackEvent(s){return J(this,arguments,function*(e,t={},i=!0,a,l){try{i&&(t||(t={}),t=h(h({},t),this.defaultProperties));let d;if(t?.annotationId){let u=t.annotationId;if(!d&&this.commentService){let _=this.commentService.getAnnotationById(u);_?.metadata&&(d=_.metadata),_?.targetElementId&&(t.targetElementId=_.targetElementId);let I=this.commentService.getMultiThreadAnnotationById(u);I?.metadata&&(d=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId)}if(!d&&this.recorderAnnotationService){let _=this.recorderAnnotationService.getAnnotationById(u);_?.metadata&&(d=_.metadata)}if(!d&&this.reactionService){let _=this.reactionService.getAnnotationById(u);_?.metadata&&(d=_.metadata),_?.targetElementId&&(t.targetElementId=_.targetElementId)}if(!d&&this.areaService){let _=this.areaService.getAnnotationById(u);_?.metadata&&(d=_.metadata)}}if(d&&typeof d=="object"&&(t=h(h({},t),d)),t&&typeof t=="object"&&(t=y(h({},t),{userId:this.userId||a,clientUserId:this.user?.userId||l}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),t?.sessionTabId||(t.sessionTabId=this.domService?.getTabId()),this.liveStateSyncEvents.includes(e))){let u=this.liveStateService?.getSemStats();u&&!t?.semStats&&(t.semStats=u)}let v={userId:this.userId||a,clientUserId:this.user?.userId||l,event:e,properties:t,sf:this.sf,context:this.getContext(),eventTimestamp:t?.eventTimestamp};return this.setAnalytics("track",v)}catch(d){return it.catch("Error in AnalyticsService triggerTrackEvent: ",d),Promise.resolve()}})}setAnalytics(e,t){return J(this,null,function*(){try{return navigator.onLine?new Promise((i,a)=>{this.analyticsQueue.push({type:e,body:t,resolve:i,reject:a}),this.analyticsQueue.length>=this.MAX_BATCH_SIZE?this.flushAnalyticsQueue():this.scheduleBatchFlush()}):void 0}catch(i){return it.catch("Error in AnalyticsService setAnalytics: ",i),Promise.resolve()}})}scheduleBatchFlush(){try{this.batchTimer||(this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushAnalyticsQueue()},this.BATCH_WINDOW_MS))}catch(e){it.catch("Error in AnalyticsService scheduleBatchFlush: ",e)}}flushAnalyticsQueue(){return J(this,null,function*(){try{if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.analyticsQueue.length===0||!navigator.onLine)return;let e=[...this.analyticsQueue];this.analyticsQueue=[];try{let t=Gr(this.functions,Wr({url:En.cloudFunction.sa,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i=e.map(a=>({type:a.type,data:a.body}));try{yield t({type:"batch",data:i}),e.forEach(a=>{try{a.resolve&&a.resolve()}catch(l){it.warn("Error resolving analytics promise: ",l)}})}catch(a){it.warn("Error in AnalyticsService batch flush: ",a),e.forEach(l=>{try{l.reject&&l.reject(a)}catch(s){it.warn("Error rejecting analytics promise: ",s)}})}}catch(t){it.catch("Error in AnalyticsService flushAnalyticsQueue: ",t),e.forEach(i=>{try{i.reject&&i.reject(t)}catch(a){it.warn("Error rejecting analytics promise: ",a)}})}}catch(e){it.catch("Error in AnalyticsService flushAnalyticsQueue: ",e)}})}trackAuthenticatedEvent(e,t={},i=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,t,i):((!t||typeof t!="object")&&(t={}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.authService?.getUser$()?.pipe($e(a=>!!a),ut(1))?.subscribe(()=>{this.trackEvent(e,t,i)})))}catch(a){it.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},t=no();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=phe(),e.userAgent=t?.deviceInfo?.userAgent,e}catch(e){it.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(t){return new(t||o)(X(Do))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var k=(()=>{let o=class o{get debugMode(){return the()}get debugContextMode(){return nhe()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new Se(!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)}}log(e,...t){this.debugMode&&console.log(e,...t)}logContext(e,...t){this.debugContextMode&&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,i,a=!1){try{let l=t?.message;this.logsEnabled$.value&&(l?.toLowerCase()?.includes("permission denied")||l?.toLowerCase()?.includes("permission_denied")||(t!==void 0?console.warn("Velt: ",e,t):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(Y.Events.Core.SDK_ERROR,h({sourceMethod:e,message:(t?.message?t?.message:t)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},i||{}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ohe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ahe={};var Cg,sZ;(function(){var n;function o(xe,ye){function Oe(){}Oe.prototype=ye.prototype,xe.D=ye.prototype,xe.prototype=new Oe,xe.prototype.constructor=xe,xe.C=function(Re,Ue,ze){for(var Ge=Array(arguments.length-2),$r=2;$r<arguments.length;$r++)Ge[$r-2]=arguments[$r];return ye.prototype[Ue].apply(Re,Ge)}}function r(){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,r),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(xe,ye,Oe){Oe||(Oe=0);var Re=Array(16);if(typeof ye=="string")for(var Ue=0;16>Ue;++Ue)Re[Ue]=ye.charCodeAt(Oe++)|ye.charCodeAt(Oe++)<<8|ye.charCodeAt(Oe++)<<16|ye.charCodeAt(Oe++)<<24;else for(Ue=0;16>Ue;++Ue)Re[Ue]=ye[Oe++]|ye[Oe++]<<8|ye[Oe++]<<16|ye[Oe++]<<24;ye=xe.g[0],Oe=xe.g[1],Ue=xe.g[2];var ze=xe.g[3],Ge=ye+(ze^Oe&(Ue^ze))+Re[0]+3614090360&4294967295;ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[1]+3905402710&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[2]+606105819&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[3]+3250441966&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[4]+4118548399&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[5]+1200080426&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[6]+2821735955&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[7]+4249261313&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[8]+1770035416&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[9]+2336552879&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[10]+4294925233&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[11]+2304563134&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[12]+1804603682&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[13]+4254626195&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[14]+2792965006&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[15]+1236535329&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(Ue^ze&(Oe^Ue))+Re[1]+4129170786&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[6]+3225465664&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[11]+643717713&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[0]+3921069994&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[5]+3593408605&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[10]+38016083&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[15]+3634488961&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[4]+3889429448&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[9]+568446438&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[14]+3275163606&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[3]+4107603335&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[8]+1163531501&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[13]+2850285829&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[2]+4243563512&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[7]+1735328473&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[12]+2368359562&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Oe^Ue^ze)+Re[5]+4294588738&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[8]+2272392833&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[11]+1839030562&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[14]+4259657740&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[1]+2763975236&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[4]+1272893353&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[7]+4139469664&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[10]+3200236656&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[13]+681279174&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[0]+3936430074&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[3]+3572445317&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[6]+76029189&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[9]+3654602809&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[12]+3873151461&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[15]+530742520&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[2]+3299628645&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Ue^(Oe|~ze))+Re[0]+4096336452&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[7]+1126891415&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[14]+2878612391&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[5]+4237533241&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[12]+1700485571&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[3]+2399980690&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[10]+4293915773&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[1]+2240044497&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[8]+1873313359&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[15]+4264355552&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[6]+2734768916&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[13]+1309151649&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[4]+4149444226&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[11]+3174756917&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[2]+718787259&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[9]+3951481745&4294967295,xe.g[0]=xe.g[0]+ye&4294967295,xe.g[1]=xe.g[1]+(Ue+(Ge<<21&4294967295|Ge>>>11))&4294967295,xe.g[2]=xe.g[2]+Ue&4294967295,xe.g[3]=xe.g[3]+ze&4294967295}e.prototype.u=function(xe,ye){ye===void 0&&(ye=xe.length);for(var Oe=ye-this.blockSize,Re=this.B,Ue=this.h,ze=0;ze<ye;){if(Ue==0)for(;ze<=Oe;)t(this,xe,ze),ze+=this.blockSize;if(typeof xe=="string"){for(;ze<ye;)if(Re[Ue++]=xe.charCodeAt(ze++),Ue==this.blockSize){t(this,Re),Ue=0;break}}else for(;ze<ye;)if(Re[Ue++]=xe[ze++],Ue==this.blockSize){t(this,Re),Ue=0;break}}this.h=Ue,this.o+=ye},e.prototype.v=function(){var xe=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);xe[0]=128;for(var ye=1;ye<xe.length-8;++ye)xe[ye]=0;var Oe=8*this.o;for(ye=xe.length-8;ye<xe.length;++ye)xe[ye]=Oe&255,Oe/=256;for(this.u(xe),xe=Array(16),ye=Oe=0;4>ye;++ye)for(var Re=0;32>Re;Re+=8)xe[Oe++]=this.g[ye]>>>Re&255;return xe};function i(xe,ye){var Oe=l;return Object.prototype.hasOwnProperty.call(Oe,xe)?Oe[xe]:Oe[xe]=ye(xe)}function a(xe,ye){this.h=ye;for(var Oe=[],Re=!0,Ue=xe.length-1;0<=Ue;Ue--){var ze=xe[Ue]|0;Re&&ze==ye||(Oe[Ue]=ze,Re=!1)}this.g=Oe}var l={};function s(xe){return-128<=xe&&128>xe?i(xe,function(ye){return new a([ye|0],0>ye?-1:0)}):new a([xe|0],0>xe?-1:0)}function d(xe){if(isNaN(xe)||!isFinite(xe))return u;if(0>xe)return B(d(-xe));for(var ye=[],Oe=1,Re=0;xe>=Oe;Re++)ye[Re]=xe/Oe|0,Oe*=4294967296;return new a(ye,0)}function v(xe,ye){if(xe.length==0)throw Error("number format error: empty string");if(ye=ye||10,2>ye||36<ye)throw Error("radix out of range: "+ye);if(xe.charAt(0)=="-")return B(v(xe.substring(1),ye));if(0<=xe.indexOf("-"))throw Error('number format error: interior "-" character');for(var Oe=d(Math.pow(ye,8)),Re=u,Ue=0;Ue<xe.length;Ue+=8){var ze=Math.min(8,xe.length-Ue),Ge=parseInt(xe.substring(Ue,Ue+ze),ye);8>ze?(ze=d(Math.pow(ye,ze)),Re=Re.j(ze).add(d(Ge))):(Re=Re.j(Oe),Re=Re.add(d(Ge)))}return Re}var u=s(0),_=s(1),I=s(16777216);n=a.prototype,n.m=function(){if(M(this))return-B(this).m();for(var xe=0,ye=1,Oe=0;Oe<this.g.length;Oe++){var Re=this.i(Oe);xe+=(0<=Re?Re:4294967296+Re)*ye,ye*=4294967296}return xe},n.toString=function(xe){if(xe=xe||10,2>xe||36<xe)throw Error("radix out of range: "+xe);if(A(this))return"0";if(M(this))return"-"+B(this).toString(xe);for(var ye=d(Math.pow(xe,6)),Oe=this,Re="";;){var Ue=oe(Oe,ye).g;Oe=q(Oe,Ue.j(ye));var ze=((0<Oe.g.length?Oe.g[0]:Oe.h)>>>0).toString(xe);if(Oe=Ue,A(Oe))return ze+Re;for(;6>ze.length;)ze="0"+ze;Re=ze+Re}},n.i=function(xe){return 0>xe?0:xe<this.g.length?this.g[xe]:this.h};function A(xe){if(xe.h!=0)return!1;for(var ye=0;ye<xe.g.length;ye++)if(xe.g[ye]!=0)return!1;return!0}function M(xe){return xe.h==-1}n.l=function(xe){return xe=q(this,xe),M(xe)?-1:A(xe)?0:1};function B(xe){for(var ye=xe.g.length,Oe=[],Re=0;Re<ye;Re++)Oe[Re]=~xe.g[Re];return new a(Oe,~xe.h).add(_)}n.abs=function(){return M(this)?B(this):this},n.add=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0,Ue=0;Ue<=ye;Ue++){var ze=Re+(this.i(Ue)&65535)+(xe.i(Ue)&65535),Ge=(ze>>>16)+(this.i(Ue)>>>16)+(xe.i(Ue)>>>16);Re=Ge>>>16,ze&=65535,Ge&=65535,Oe[Ue]=Ge<<16|ze}return new a(Oe,Oe[Oe.length-1]&-2147483648?-1:0)};function q(xe,ye){return xe.add(B(ye))}n.j=function(xe){if(A(this)||A(xe))return u;if(M(this))return M(xe)?B(this).j(B(xe)):B(B(this).j(xe));if(M(xe))return B(this.j(B(xe)));if(0>this.l(I)&&0>xe.l(I))return d(this.m()*xe.m());for(var ye=this.g.length+xe.g.length,Oe=[],Re=0;Re<2*ye;Re++)Oe[Re]=0;for(Re=0;Re<this.g.length;Re++)for(var Ue=0;Ue<xe.g.length;Ue++){var ze=this.i(Re)>>>16,Ge=this.i(Re)&65535,$r=xe.i(Ue)>>>16,nt=xe.i(Ue)&65535;Oe[2*Re+2*Ue]+=Ge*nt,ae(Oe,2*Re+2*Ue),Oe[2*Re+2*Ue+1]+=ze*nt,ae(Oe,2*Re+2*Ue+1),Oe[2*Re+2*Ue+1]+=Ge*$r,ae(Oe,2*Re+2*Ue+1),Oe[2*Re+2*Ue+2]+=ze*$r,ae(Oe,2*Re+2*Ue+2)}for(Re=0;Re<ye;Re++)Oe[Re]=Oe[2*Re+1]<<16|Oe[2*Re];for(Re=ye;Re<2*ye;Re++)Oe[Re]=0;return new a(Oe,0)};function ae(xe,ye){for(;(xe[ye]&65535)!=xe[ye];)xe[ye+1]+=xe[ye]>>>16,xe[ye]&=65535,ye++}function Ce(xe,ye){this.g=xe,this.h=ye}function oe(xe,ye){if(A(ye))throw Error("division by zero");if(A(xe))return new Ce(u,u);if(M(xe))return ye=oe(B(xe),ye),new Ce(B(ye.g),B(ye.h));if(M(ye))return ye=oe(xe,B(ye)),new Ce(B(ye.g),ye.h);if(30<xe.g.length){if(M(xe)||M(ye))throw Error("slowDivide_ only works with positive integers.");for(var Oe=_,Re=ye;0>=Re.l(xe);)Oe=fe(Oe),Re=fe(Re);var Ue=Ie(Oe,1),ze=Ie(Re,1);for(Re=Ie(Re,2),Oe=Ie(Oe,2);!A(Re);){var Ge=ze.add(Re);0>=Ge.l(xe)&&(Ue=Ue.add(Oe),ze=Ge),Re=Ie(Re,1),Oe=Ie(Oe,1)}return ye=q(xe,Ue.j(ye)),new Ce(Ue,ye)}for(Ue=u;0<=xe.l(ye);){for(Oe=Math.max(1,Math.floor(xe.m()/ye.m())),Re=Math.ceil(Math.log(Oe)/Math.LN2),Re=48>=Re?1:Math.pow(2,Re-48),ze=d(Oe),Ge=ze.j(ye);M(Ge)||0<Ge.l(xe);)Oe-=Re,ze=d(Oe),Ge=ze.j(ye);A(ze)&&(ze=_),Ue=Ue.add(ze),xe=q(xe,Ge)}return new Ce(Ue,xe)}n.A=function(xe){return oe(this,xe).h},n.and=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)&xe.i(Re);return new a(Oe,this.h&xe.h)},n.or=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)|xe.i(Re);return new a(Oe,this.h|xe.h)},n.xor=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)^xe.i(Re);return new a(Oe,this.h^xe.h)};function fe(xe){for(var ye=xe.g.length+1,Oe=[],Re=0;Re<ye;Re++)Oe[Re]=xe.i(Re)<<1|xe.i(Re-1)>>>31;return new a(Oe,xe.h)}function Ie(xe,ye){var Oe=ye>>5;ye%=32;for(var Re=xe.g.length-Oe,Ue=[],ze=0;ze<Re;ze++)Ue[ze]=0<ye?xe.i(ze+Oe)>>>ye|xe.i(ze+Oe+1)<<32-ye:xe.i(ze+Oe);return new a(Ue,xe.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,sZ=Ahe.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=d,a.fromString=v,Cg=Ahe.Integer=a}).apply(typeof Ohe<"u"?Ohe:typeof self<"u"?self:typeof window<"u"?window:{});var jN=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bg={};var cZ,mGe,i1,dZ,m3,$N,mZ,vZ,gZ;(function(){var n,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(G,ce,_e){return G==Array.prototype||G==Object.prototype||(G[ce]=_e.value),G};function r(G){G=[typeof globalThis=="object"&&globalThis,G,typeof window=="object"&&window,typeof self=="object"&&self,typeof jN=="object"&&jN];for(var ce=0;ce<G.length;++ce){var _e=G[ce];if(_e&&_e.Math==Math)return _e}throw Error("Cannot find global object")}var e=r(this);function t(G,ce){if(ce)e:{var _e=e;G=G.split(".");for(var Ne=0;Ne<G.length-1;Ne++){var rt=G[Ne];if(!(rt in _e))break e;_e=_e[rt]}G=G[G.length-1],Ne=_e[G],ce=ce(Ne),ce!=Ne&&ce!=null&&o(_e,G,{configurable:!0,writable:!0,value:ce})}}function i(G,ce){G instanceof String&&(G+="");var _e=0,Ne=!1,rt={next:function(){if(!Ne&&_e<G.length){var Ct=_e++;return{value:ce(Ct,G[Ct]),done:!1}}return Ne=!0,{done:!0,value:void 0}}};return rt[Symbol.iterator]=function(){return rt},rt}t("Array.prototype.values",function(G){return G||function(){return i(this,function(ce,_e){return _e})}});var a=a||{},l=this||self;function s(G){var ce=typeof G;return ce=ce!="object"?ce:G?Array.isArray(G)?"array":ce:"null",ce=="array"||ce=="object"&&typeof G.length=="number"}function d(G){var ce=typeof G;return ce=="object"&&G!=null||ce=="function"}function v(G,ce,_e){return G.call.apply(G.bind,arguments)}function u(G,ce,_e){if(!G)throw Error();if(2<arguments.length){var Ne=Array.prototype.slice.call(arguments,2);return function(){var rt=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(rt,Ne),G.apply(ce,rt)}}return function(){return G.apply(ce,arguments)}}function _(G,ce,_e){return _=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?v:u,_.apply(null,arguments)}function I(G,ce){var _e=Array.prototype.slice.call(arguments,1);return function(){var Ne=_e.slice();return Ne.push.apply(Ne,arguments),G.apply(this,Ne)}}function A(G,ce){function _e(){}_e.prototype=ce.prototype,G.aa=ce.prototype,G.prototype=new _e,G.prototype.constructor=G,G.Qb=function(Ne,rt,Ct){for(var qt=Array(arguments.length-2),Go=2;Go<arguments.length;Go++)qt[Go-2]=arguments[Go];return ce.prototype[rt].apply(Ne,qt)}}function M(G){let ce=G.length;if(0<ce){let _e=Array(ce);for(let Ne=0;Ne<ce;Ne++)_e[Ne]=G[Ne];return _e}return[]}function B(G,ce){for(let _e=1;_e<arguments.length;_e++){let Ne=arguments[_e];if(s(Ne)){let rt=G.length||0,Ct=Ne.length||0;G.length=rt+Ct;for(let qt=0;qt<Ct;qt++)G[rt+qt]=Ne[qt]}else G.push(Ne)}}class q{constructor(ce,_e){this.i=ce,this.j=_e,this.h=0,this.g=null}get(){let ce;return 0<this.h?(this.h--,ce=this.g,this.g=ce.next,ce.next=null):ce=this.i(),ce}}function ae(G){return/^[\s\xa0]*$/.test(G)}function Ce(){var G=l.navigator;return G&&(G=G.userAgent)?G:""}function oe(G){return oe[" "](G),G}oe[" "]=function(){};var fe=Ce().indexOf("Gecko")!=-1&&!(Ce().toLowerCase().indexOf("webkit")!=-1&&Ce().indexOf("Edge")==-1)&&!(Ce().indexOf("Trident")!=-1||Ce().indexOf("MSIE")!=-1)&&Ce().indexOf("Edge")==-1;function Ie(G,ce,_e){for(let Ne in G)ce.call(_e,G[Ne],Ne,G)}function xe(G,ce){for(let _e in G)ce.call(void 0,G[_e],_e,G)}function ye(G){let ce={};for(let _e in G)ce[_e]=G[_e];return ce}let Oe="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Re(G,ce){let _e,Ne;for(let rt=1;rt<arguments.length;rt++){Ne=arguments[rt];for(_e in Ne)G[_e]=Ne[_e];for(let Ct=0;Ct<Oe.length;Ct++)_e=Oe[Ct],Object.prototype.hasOwnProperty.call(Ne,_e)&&(G[_e]=Ne[_e])}}function Ue(G){var ce=1;G=G.split(":");let _e=[];for(;0<ce&&G.length;)_e.push(G.shift()),ce--;return G.length&&_e.push(G.join(":")),_e}function ze(G){l.setTimeout(()=>{throw G},0)}function Ge(){var G=an;let ce=null;return G.g&&(ce=G.g,G.g=G.g.next,G.g||(G.h=null),ce.next=null),ce}class $r{constructor(){this.h=this.g=null}add(ce,_e){let Ne=nt.get();Ne.set(ce,_e),this.h?this.h.next=Ne:this.g=Ne,this.h=Ne}}var nt=new q(()=>new Et,G=>G.reset());class Et{constructor(){this.next=this.g=this.h=null}set(ce,_e){this.h=ce,this.g=_e,this.next=null}reset(){this.next=this.g=this.h=null}}let et,$t=!1,an=new $r,lr=()=>{let G=l.Promise.resolve(void 0);et=()=>{G.then(Hr)}};var Hr=()=>{for(var G;G=Ge();){try{G.h.call(G.g)}catch(_e){ze(_e)}var ce=nt;ce.j(G),100>ce.h&&(ce.h++,G.next=ce.g,ce.g=G)}$t=!1};function _o(){this.s=this.s,this.C=this.C}_o.prototype.s=!1,_o.prototype.ma=function(){this.s||(this.s=!0,this.N())},_o.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Zn(G,ce){this.type=G,this.g=this.target=ce,this.defaultPrevented=!1}Zn.prototype.h=function(){this.defaultPrevented=!0};var So=(function(){if(!l.addEventListener||!Object.defineProperty)return!1;var G=!1,ce=Object.defineProperty({},"passive",{get:function(){G=!0}});try{let _e=()=>{};l.addEventListener("test",_e,ce),l.removeEventListener("test",_e,ce)}catch{}return G})();function Jr(G,ce){if(Zn.call(this,G?G.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,G){var _e=this.type=G.type,Ne=G.changedTouches&&G.changedTouches.length?G.changedTouches[0]:null;if(this.target=G.target||G.srcElement,this.g=ce,ce=G.relatedTarget){if(fe){e:{try{oe(ce.nodeName);var rt=!0;break e}catch{}rt=!1}rt||(ce=null)}}else _e=="mouseover"?ce=G.fromElement:_e=="mouseout"&&(ce=G.toElement);this.relatedTarget=ce,Ne?(this.clientX=Ne.clientX!==void 0?Ne.clientX:Ne.pageX,this.clientY=Ne.clientY!==void 0?Ne.clientY:Ne.pageY,this.screenX=Ne.screenX||0,this.screenY=Ne.screenY||0):(this.clientX=G.clientX!==void 0?G.clientX:G.pageX,this.clientY=G.clientY!==void 0?G.clientY:G.pageY,this.screenX=G.screenX||0,this.screenY=G.screenY||0),this.button=G.button,this.key=G.key||"",this.ctrlKey=G.ctrlKey,this.altKey=G.altKey,this.shiftKey=G.shiftKey,this.metaKey=G.metaKey,this.pointerId=G.pointerId||0,this.pointerType=typeof G.pointerType=="string"?G.pointerType:Mn[G.pointerType]||"",this.state=G.state,this.i=G,G.defaultPrevented&&Jr.aa.h.call(this)}}A(Jr,Zn);var Mn={2:"touch",3:"pen",4:"mouse"};Jr.prototype.h=function(){Jr.aa.h.call(this);var G=this.i;G.preventDefault?G.preventDefault():G.returnValue=!1};var fn="closure_listenable_"+(1e6*Math.random()|0),hi=0;function Po(G,ce,_e,Ne,rt){this.listener=G,this.proxy=null,this.src=ce,this.type=_e,this.capture=!!Ne,this.ha=rt,this.key=++hi,this.da=this.fa=!1}function aa(G){G.da=!0,G.listener=null,G.proxy=null,G.src=null,G.ha=null}function md(G){this.src=G,this.g={},this.h=0}md.prototype.add=function(G,ce,_e,Ne,rt){var Ct=G.toString();G=this.g[Ct],G||(G=this.g[Ct]=[],this.h++);var qt=um(G,ce,Ne,rt);return-1<qt?(ce=G[qt],_e||(ce.fa=!1)):(ce=new Po(ce,this.src,Ct,!!Ne,rt),ce.fa=_e,G.push(ce)),ce};function UC(G,ce){var _e=ce.type;if(_e in G.g){var Ne=G.g[_e],rt=Array.prototype.indexOf.call(Ne,ce,void 0),Ct;(Ct=0<=rt)&&Array.prototype.splice.call(Ne,rt,1),Ct&&(aa(ce),G.g[_e].length==0&&(delete G.g[_e],G.h--))}}function um(G,ce,_e,Ne){for(var rt=0;rt<G.length;++rt){var Ct=G[rt];if(!Ct.da&&Ct.listener==ce&&Ct.capture==!!_e&&Ct.ha==Ne)return rt}return-1}var Ug="closure_lm_"+(1e6*Math.random()|0),vd={};function VC(G,ce,_e,Ne,rt){if(Ne&&Ne.once)return Ch(G,ce,_e,Ne,rt);if(Array.isArray(ce)){for(var Ct=0;Ct<ce.length;Ct++)VC(G,ce[Ct],_e,Ne,rt);return null}return _e=pm(_e),G&&G[fn]?G.K(ce,_e,d(Ne)?!!Ne.capture:!!Ne,rt):BC(G,ce,_e,!1,Ne,rt)}function BC(G,ce,_e,Ne,rt,Ct){if(!ce)throw Error("Invalid event type");var qt=d(rt)?!!rt.capture:!!rt,Go=_h(G);if(Go||(G[Ug]=Go=new md(G)),_e=Go.add(ce,_e,Ne,qt,Ct),_e.proxy)return _e;if(Ne=Vg(),_e.proxy=Ne,Ne.src=G,Ne.listener=_e,G.addEventListener)So||(rt=qt),rt===void 0&&(rt=!1),G.addEventListener(ce.toString(),Ne,rt);else if(G.attachEvent)G.attachEvent(Z2(ce.toString()),Ne);else if(G.addListener&&G.removeListener)G.addListener(Ne);else throw Error("addEventListener and attachEvent are unavailable.");return _e}function Vg(){function G(_e){return ce.call(G.src,G.listener,_e)}let ce=oB;return G}function Ch(G,ce,_e,Ne,rt){if(Array.isArray(ce)){for(var Ct=0;Ct<ce.length;Ct++)Ch(G,ce[Ct],_e,Ne,rt);return null}return _e=pm(_e),G&&G[fn]?G.L(ce,_e,d(Ne)?!!Ne.capture:!!Ne,rt):BC(G,ce,_e,!0,Ne,rt)}function bh(G,ce,_e,Ne,rt){if(Array.isArray(ce))for(var Ct=0;Ct<ce.length;Ct++)bh(G,ce[Ct],_e,Ne,rt);else Ne=d(Ne)?!!Ne.capture:!!Ne,_e=pm(_e),G&&G[fn]?(G=G.i,ce=String(ce).toString(),ce in G.g&&(Ct=G.g[ce],_e=um(Ct,_e,Ne,rt),-1<_e&&(aa(Ct[_e]),Array.prototype.splice.call(Ct,_e,1),Ct.length==0&&(delete G.g[ce],G.h--)))):G&&(G=_h(G))&&(ce=G.g[ce.toString()],G=-1,ce&&(G=um(ce,_e,Ne,rt)),(_e=-1<G?ce[G]:null)&&jC(_e))}function jC(G){if(typeof G!="number"&&G&&!G.da){var ce=G.src;if(ce&&ce[fn])UC(ce.i,G);else{var _e=G.type,Ne=G.proxy;ce.removeEventListener?ce.removeEventListener(_e,Ne,G.capture):ce.detachEvent?ce.detachEvent(Z2(_e),Ne):ce.addListener&&ce.removeListener&&ce.removeListener(Ne),(_e=_h(ce))?(UC(_e,G),_e.h==0&&(_e.src=null,ce[Ug]=null)):aa(G)}}}function Z2(G){return G in vd?vd[G]:vd[G]="on"+G}function oB(G,ce){if(G.da)G=!0;else{ce=new Jr(ce,this);var _e=G.listener,Ne=G.ha||G.src;G.fa&&jC(G),G=_e.call(Ne,ce)}return G}function _h(G){return G=G[Ug],G instanceof md?G:null}var Tv="__closure_events_fn_"+(1e9*Math.random()>>>0);function pm(G){return typeof G=="function"?G:(G[Tv]||(G[Tv]=function(ce){return G.handleEvent(ce)}),G[Tv])}function ki(){_o.call(this),this.i=new md(this),this.M=this,this.F=null}A(ki,_o),ki.prototype[fn]=!0,ki.prototype.removeEventListener=function(G,ce,_e,Ne){bh(this,G,ce,_e,Ne)};function Va(G,ce){var _e,Ne=G.F;if(Ne)for(_e=[];Ne;Ne=Ne.F)_e.push(Ne);if(G=G.M,Ne=ce.type||ce,typeof ce=="string")ce=new Zn(ce,G);else if(ce instanceof Zn)ce.target=ce.target||G;else{var rt=ce;ce=new Zn(Ne,G),Re(ce,rt)}if(rt=!0,_e)for(var Ct=_e.length-1;0<=Ct;Ct--){var qt=ce.g=_e[Ct];rt=Sh(qt,Ne,!0,ce)&&rt}if(qt=ce.g=G,rt=Sh(qt,Ne,!0,ce)&&rt,rt=Sh(qt,Ne,!1,ce)&&rt,_e)for(Ct=0;Ct<_e.length;Ct++)qt=ce.g=_e[Ct],rt=Sh(qt,Ne,!1,ce)&&rt}ki.prototype.N=function(){if(ki.aa.N.call(this),this.i){var G=this.i,ce;for(ce in G.g){for(var _e=G.g[ce],Ne=0;Ne<_e.length;Ne++)aa(_e[Ne]);delete G.g[ce],G.h--}}this.F=null},ki.prototype.K=function(G,ce,_e,Ne){return this.i.add(String(G),ce,!1,_e,Ne)},ki.prototype.L=function(G,ce,_e,Ne){return this.i.add(String(G),ce,!0,_e,Ne)};function Sh(G,ce,_e,Ne){if(ce=G.i.g[String(ce)],!ce)return!0;ce=ce.concat();for(var rt=!0,Ct=0;Ct<ce.length;++Ct){var qt=ce[Ct];if(qt&&!qt.da&&qt.capture==_e){var Go=qt.listener,ml=qt.ha||qt.src;qt.fa&&UC(G.i,qt),rt=Go.call(ml,Ne)!==!1&&rt}}return rt&&!Ne.defaultPrevented}function X2(G,ce,_e){if(typeof G=="function")_e&&(G=_(G,_e));else if(G&&typeof G.handleEvent=="function")G=_(G.handleEvent,G);else throw Error("Invalid listener argument");return 2147483647<Number(ce)?-1:l.setTimeout(G,ce||0)}function $C(G){G.g=X2(()=>{G.g=null,G.i&&(G.i=!1,$C(G))},G.l);let ce=G.h;G.h=null,G.m.apply(null,ce)}class M5 extends _o{constructor(ce,_e){super(),this.m=ce,this.l=_e,this.h=null,this.i=!1,this.g=null}j(ce){this.h=arguments,this.g?this.i=!0:$C(this)}N(){super.N(),this.g&&(l.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function hm(G){_o.call(this),this.h=G,this.g={}}A(hm,_o);var yh=[];function Ac(G){Ie(G.g,function(ce,_e){this.g.hasOwnProperty(_e)&&jC(ce)},G),G.g={}}hm.prototype.N=function(){hm.aa.N.call(this),Ac(this)},hm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fm=l.JSON.stringify,J2=l.JSON.parse,Q2=class{stringify(G){return l.JSON.stringify(G,void 0)}parse(G){return l.JSON.parse(G,void 0)}};function eT(){}eT.prototype.h=null;function kh(G){return G.h||(G.h=G.i())}function xh(){}var Ih={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function wv(){Zn.call(this,"d")}A(wv,Zn);function tT(){Zn.call(this,"c")}A(tT,Zn);var Dv={},zi=null;function gd(){return zi=zi||new ki}Dv.La="serverreachability";function P5(G){Zn.call(this,Dv.La,G)}A(P5,Zn);function Bg(G){let ce=gd();Va(ce,new P5(ce))}Dv.STAT_EVENT="statevent";function HC(G,ce){Zn.call(this,Dv.STAT_EVENT,G),this.stat=ce}A(HC,Zn);function Ba(G){let ce=gd();Va(ce,new HC(ce,G))}Dv.Ma="timingevent";function nT(G,ce){Zn.call(this,Dv.Ma,G),this.size=ce}A(nT,Zn);function Eh(G,ce){if(typeof G!="function")throw Error("Fn must not be null and must be a function");return l.setTimeout(function(){G()},ce)}function wl(){this.g=!0}wl.prototype.xa=function(){this.g=!1};function Ov(G,ce,_e,Ne,rt,Ct){G.info(function(){if(G.g)if(Ct)for(var qt="",Go=Ct.split("&"),ml=0;ml<Go.length;ml++){var ao=Go[ml].split("=");if(1<ao.length){var Dl=ao[0];ao=ao[1];var Ol=Dl.split("_");qt=2<=Ol.length&&Ol[1]=="type"?qt+(Dl+"="+ao+"&"):qt+(Dl+"=redacted&")}}else qt=null;else qt=Ct;return"XMLHTTP REQ ("+Ne+") [attempt "+rt+"]: "+ce+`
196
+ `||e===" "||[",",":",";"].includes(e))}catch(e){return it.catch("Error in utils isHotkeyDisabledForAutocomplete: ",e),!1}},TN=(n,o,r)=>{try{return!!n.substring(o+1,r).startsWith(" ")}catch(e){return it.catch("Error in utils isHotkeyFollowedBySpace: ",e),!1}},s3=(n,o,r=["@"])=>{try{let e=cGe(n),t=null;try{e&&typeof e.getSelection=="function"&&(t=e.getSelection())}catch{}if(t||(t=window.getSelection()),t?.rangeCount){let i=t.getRangeAt(0),a=i.startOffset,l=i?.commonAncestorContainer?.textContent;if(l){let s=-1;for(let d of r){let v=l.lastIndexOf(d,a),u=v>0?l.lastIndexOf(d,v-1):-1;if(v>s){let _=EN(l,v,a),I=TN(l,v,a);if(_||I){if(u!==-1){let A=EN(l,u,v),M=TN(l,u,v);!A&&!M&&(s=u)}}else s=v}}if(s!==-1){let d=l.substring(0,s),v=l.substring(i.endOffset),u=document.createElement("span");u.textContent=o,u.style.color="var(--velt-accent)";let _=o.startsWith("@")?o.substring(1):o;u.classList.add("velt-mention"),u.classList.add(_.includes("@")?"velt-mention--email":"velt-mention--name");let I=Date.now()+"_"+Math.random().toString(36).substr(2,9);u.setAttribute("data-recently-added",I),setTimeout(()=>{u.hasAttribute("data-recently-added")&&u.removeAttribute("data-recently-added")},5e3);let A=i.commonAncestorContainer;if(A.nodeType===Node.TEXT_NODE){let M=A.parentNode;if(M){let B=document.createTextNode(d),q=document.createTextNode(v);M.replaceChild(q,A),M.insertBefore(u,q),M.insertBefore(B,u);try{let ae=document.createRange();ae.setStartAfter(u),ae.collapse(!0),t?.removeAllRanges(),t?.addRange(ae)}catch(ae){it.catch("Error positioning cursor after span:",ae);try{let Ce=document.createRange();Ce.selectNodeContents(n),Ce.collapse(!1),t?.removeAllRanges(),t?.addRange(Ce)}catch(Ce){it.catch("Error with fallback cursor positioning:",Ce)}}}}}}}}catch(e){it.catch("Error in utils replaceWordAtCursor: ",e)}},c3=()=>{try{let o=window.getSelection()?.getRangeAt(0),r=o?.commonAncestorContainer,e=o?.startContainer,t=o?.endContainer,i=[];i.push(r),i.push(e),i.push(t);let a=!1;for(let l of i)if(l&&Co(l,[N.TAGS.SNIPPYLY_TEXT_HIGHLIGHT,N.TAGS.SNIPPYLY_COMMENT_TEXT_PORTAL,N.TAGS.SNIPPYLY_HIGHLIGHT_USER_TEXT,N.TAGS.SNIPPYLY_COMMENT_TEXT])){a=!0;break}return a}catch(n){return it.catch("Error in utils isTextSelectionIncludesSnippylyElement: ",n),!1}},ghe=(n,o,r)=>{try{let e=document.querySelector(`[id=${n}]`);if(e)e.name=o,e.content=r;else{let t=document.createElement("meta");t.id=n,t.name=o,t.content=r,document.getElementsByTagName("head")[0].appendChild(t)}}catch{}},uhe=n=>{try{if(n){let o=document.querySelector(`[id=${n}]`);o&&o.remove()}}catch{}},phe=()=>{try{let o=new Date().getTimezoneOffset(),r=Math.floor(Math.abs(o)/60),e=Math.abs(o)%60;return`UTC${o>0?"-":"+"}${r?.toString()?.padStart(2,"0")}:${e?.toString()?.padStart(2,"0")}`}catch(n){return it.catch("Error in utils getTimezone: ",n),""}},hhe=()=>{try{let n=[];return document.querySelectorAll("*").forEach(r=>{(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth||["auto","scroll"].includes(getComputedStyle(r).overflow))&&n.push(r)}),n}catch(n){return it.catch("Error in utils getScrollableElements: ",n),[]}},fhe=(n,o)=>Math.sqrt((n.x-o.x)**2+(n.y-o.y)**2),tZ=(n,o={x:window.innerWidth/2,y:window.innerHeight/2})=>{try{let r=n;for(;r.children.length>0;){let e=null,t=Number.MAX_SAFE_INTEGER;for(let i=0;i<r.children.length;i++){let a=r.children[i],l=a.getBoundingClientRect(),s={x:l.left+l.width/2,y:l.top+l.height/2},d=fhe(s,o);(l.top>=0||l.bottom<=window.innerHeight)&&l.width>0&&l.height>0&&d<=t&&(e=a,t=d)}if(e===null)break;r=e}return r}catch(r){return it.catch("Error in utils getInnermostElement: ",r),null}},Che=n=>{try{let{offsetWidth:o,offsetHeight:r,scrollTop:e}=n,t=n,i={x:o/2,y:e+r/2};for(;t.children.length>0;){let a=null,l=Number.MAX_SAFE_INTEGER;for(let s=0;s<t.children.length;s++){let d=t.children[s],v={x:d.offsetLeft+d.offsetWidth/2,y:d.offsetTop+d.offsetHeight/2},u=fhe(v,i);d.offsetTop>=0&&d.offsetWidth>0&&d.offsetHeight>0&&u<=l&&(a=d,l=u)}if(a===null)break;t=a}return t}catch(o){return it.catch("Error in utils getNestedInnermostElement: ",o),null}},bhe=()=>{try{let n=window.innerWidth/2,o=window.innerHeight/2,r=document.elementFromPoint(n,o);for(;r&&r.tagName==="BODY";)o+=2,r=document.elementFromPoint(n,o);return r}catch(n){return it.catch("Error in utils getCenteredBackgroundElement: ",n),null}},nZ=(n,o,r=!1)=>{try{let e=n.getBoundingClientRect(),t=o.getBoundingClientRect(),i=o.offsetTop;r&&(i=i-e.height/2+t.height/2),n.scrollTo({top:i,behavior:"smooth"})}catch(e){it.catch("Error in utils nestedScrollIntoView: ",e)}},UN=(n,o=!0)=>{try{let r=document.body.getBoundingClientRect(),e=n.getBoundingClientRect(),t=e.top-r.top,i=window.innerHeight,a=t;o&&(a=a-i/2+e.height/2),window.scrollTo({top:a,behavior:"smooth"})}catch(r){it.catch("Error in utils scrollIntoView: ",r)}},_he=(n=!1)=>{try{let o=!0;return n&&(o=/\sChrome\/[\d.]+ Mobile\s/.test(navigator.userAgent)),"ontouchstart"in window||navigator.maxTouchPoints>0||o}catch(o){return it.catch("Error in utils isTouchDevice: ",o),!1}},She=(n,o,r)=>{try{return(1-r)*n+r*o}catch(e){it.catch("Error in utils lerp: ",e)}return 0},yhe=(n,o)=>{try{if(n===void 0)return n;if(n=n.replace("#",""),n.length===6){let r=parseInt(n,16),e=(r>>16)+o;e>255&&(e=255),e<0&&(e=0);let t=(r&255)+o;t>255&&(t=255),t<0&&(t=0);let i=(r>>8&255)+o;return i>255&&(i=255),i<0&&(i=0),`#${(t|i<<8|e<<16).toString(16)}`}else return n}catch(r){it.catch("Error in utils multiplyColor: ",r)}return n},khe=n=>{try{return n in N.TEXT_COLOR_MAP?N.TEXT_COLOR_MAP[n]:"#141416"}catch(o){return it.catch("Error in generateUserColor:",o),"#141416"}},Qd=()=>{try{let n=localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_DEFAULT_MEDIA_SOURCE_OPTIONS);if(n)return JSON.parse(n)}catch(n){return it.catch("Error in getDefaultMediaStreamOptions:",n),{}}},VN=(n,o)=>{try{let r=o*(Math.PI/180),e=Math.cos(r);return e?n/e:n}catch(r){return it.catch("Error in calculateHypotenuse:",r),0}},rZ=(n,o,r=!0)=>{try{let e=[],t=r?n:n.parentNode;for(;t;)e.push(t),t=t.parentNode;let i=r?o:o.parentNode;for(;i;){if(e.indexOf(i)!==-1)return i;i=i.parentNode}return null}catch(e){return it.catch("Error in utils findCommonParent: ",e),null}},oZ=(n,o,r,e,t=!1)=>{try{let i,a;if(t){let l=r,s=e;if(l===s)i=n,a=o;else{let d=0,v=0,u=l;for(;u&&u!==s;)d+=u.offsetLeft,v+=u.offsetTop,u=u.parentElement;i=d+n,a=v+o}}else{let l=r.getBoundingClientRect(),s=e.getBoundingClientRect(),d=l.left+n,v=l.top+o;i=d-s.left,a=v-s.top}return{x:i,y:a}}catch(i){return it.catch("Error in utils calculateParentCoordinates: ",i),{x:n,y:o}}},Yu=n=>{try{let o={height:0,width:0};if(typeof n?.getBBox=="function"){let r=n?.getBBox(),e=n?.getBoundingClientRect();o.height=parseFloat(e?.height||r.height||0),o.width=parseFloat(e?.width||r.width||0)}else{let r=window.getComputedStyle(n);if(o.height=n?.clientHeight||parseFloat(r.getPropertyValue("height"))||0,o.width=n?.clientWidth||parseFloat(r.getPropertyValue("width"))||0,n?.getBoundingClientRect&&typeof n?.getBoundingClientRect=="function"){let e=n?.getBoundingClientRect();o?.height||(o.height=e?.height||n?.clientHeight||n?.offsetHeight||0),o?.width||(o.width=e?.width||n?.clientWidth||n?.offsetWidth||0)}}return o}catch(o){return it.catch("Error in utils getElementDimensions: ",o),{height:0,width:0}}},Qm=n=>{try{let o=n;for(;o;){if(window?.getComputedStyle(o)?.getPropertyValue("background-clip")=="text")return!0;o=o?.parentElement}return!1}catch(o){return it.catch("Error in utils hasParentWithBackgroundClip: ",o),!1}},cGe=n=>{try{let o=n;for(;o;){if(o.toString()==="[object ShadowRoot]")return o;o=o.parentNode}}catch(o){it.catch("Error in utils findShadowRoot: ",o)}return null},xhe=n=>{try{let o=["attachment","attachments","chunkUrls","transcription","color","position","positionX","positionY","resolved","inProgress","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource"],r=JSON.parse(JSON.stringify(n)),e={};return Object.keys(r).forEach(t=>{o.includes(t)||(e[t]=r[t])}),JSON.parse(JSON.stringify(e))}catch(o){return it.catch("Error in utils getRecorderAnnotationForClient: ",o),null}},r1=n=>n===null||typeof n>"u",o1=(n,o)=>{try{return!!n?.closest(`[${o}]`)}catch(r){return it.catch("Error in utils hasParentWithAttribute: ",r),!1}},iZ=(n,o=!0)=>{try{let r=[];if(!n||!(n instanceof HTMLElement))return[];o&&r.push(n);for(let e=0;e<n.children.length;e++){let t=n.children[e];r=r.concat(iZ(t))}return r}catch(r){return it.catch("Error in utils getAllNestedChildren: ",r),[]}},Ihe=()=>{try{return document.visibilityState==="hidden"?!1:document.hasFocus()}catch(n){return it.catch("Error in utils isTabActive: ",n),!1}},aZ=n=>{try{let o="",r=n?.getAttribute("src");if(r)o=`${Qn(r)}`;else{let e=n?.querySelectorAll("source");if(e&&e.length>0){let i=e[0]?.getAttribute("src");i&&(o=`${Qn(i)}`)}}return o}catch{return""}},He=n=>{try{return!(n&&(n?.children?.length>0||n?.textContent?.trim()?.length>0))}catch(o){return it.catch("Error in utils isTemplateEmpty: ",o),!0}},Cl=(n,o)=>{try{if(!n||!o)return;let r=[],e="",t=0;for(let s=0;s<o.length;s++){let d=o[s];d==="["?(t++,t===1&&e&&(r.push(e),e=""),e+=d):d==="]"?(t--,e+=d,t===0&&(r.push(e),e="")):d==="."&&t===0?e&&(r.push(e),e=""):e+=d}e&&r.push(e);let i,a=h({},n),l=r.reduce((s,d)=>{if(s==null)return;so(s)&&(i=s,s=s());let v=d.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(v){let _=v[1];if(/^\d+$/.test(_)){let I=parseInt(_,10);return Array.isArray(s)?s[I]:void 0}if(_.startsWith("'")&&_.endsWith("'")||_.startsWith('"')&&_.endsWith('"')){let I=_.slice(1,-1);return s[I]}if(_.includes(".")||_.includes("[")){let I=Cl(a,_);so(I)&&(I=I());let A=I?.toString()||"";return s[A]}if(a[_]!==void 0){let I=a[_];return so(I)&&(I=I()),s[I]}return s[_]}let u=d;return(d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))&&(u=d.slice(1,-1)),u==="length"&&Array.isArray(s)?s.length:s[u]},n);return i?ie(()=>{try{let s=h({},n);return r.reduce((d,v)=>{if(d==null)return;so(d)&&(d=d());let u=v.match(/^\[([^\[\]]+|(\[[^\[\]]*\]))\]$/);if(u){let I=u[1];if(/^\d+$/.test(I)){let A=parseInt(I,10);return Array.isArray(d)?d[A]:void 0}if(I.startsWith("'")&&I.endsWith("'")||I.startsWith('"')&&I.endsWith('"')){let A=I.slice(1,-1);return d[A]}if(I.includes(".")||I.includes("[")){let A=Cl(s,I);so(A)&&(A=A());let M=A?.toString()||"";return d[M]}if(s[I]!==void 0){let A=s[I];return so(A)&&(A=A()),d[A]}return d[I]}let _=v;return(v.startsWith("'")&&v.endsWith("'")||v.startsWith('"')&&v.endsWith('"'))&&(_=v.slice(1,-1)),d[_]},n)}catch{return""}}):l}catch{return""}},d0=(n,o)=>{try{return!!(n?.locationId&&(n.locationId===o?.locationId||o?.location?.id===String(n.locationId))||n?.location?.id&&(n.location.id===o?.location?.id||n.location.id===String(o?.locationId)))}catch(r){return it.catch("Error in utils isLocationSame: ",r),!1}},Ehe=()=>{try{let n=document.activeElement,o=new Set,r=10,e=0;for(;n&&n.shadowRoot&&!(o.has(n)||(o.add(n),n=n.shadowRoot.activeElement,e++,e>r)););return n}catch(n){return it.catch("Error in utils getActiveElement: ",n),null}},Jt=(n,o)=>{try{return typeof n=="object"&&typeof o=="object"?JSON.stringify(n)===JSON.stringify(o):n===o}catch{return!1}},ti=(n,o=0)=>{try{let r=JSON.parse(JSON.stringify(n));return n?.clientDocumentId&&(r.documentId=n.clientDocumentId),n?.clientOrganizationId&&(r.organizationId=n.clientOrganizationId),n?.documentMetadata&&o<5&&(r.documentMetadata=ti(n.documentMetadata,o+1)),delete r?.clientDocumentId,delete r?.clientOrganizationId,delete r?.veltFolderId,delete r?.parentVeltFolderId,delete r?.pageInfo,r}catch{return n}},Ra=n=>{try{if(!n.some(a=>a?.value?.data))return{};let o=null,r=n.reduce((a,l)=>Math.max(a,l.timestamp),0),e=n.find(a=>a.timestamp===r);if(!e)return{};e?.value?.operation?.type==="removed"&&(o=e?.value?.operation);let i=n.map(a=>a.value).reduce((a,l)=>({data:h(h({},a?.data??{}),l?.data??{})}),{});return i.operation=o,i}catch{return{}}},Ai=(n,o,r)=>J(null,null,function*(){try{let e=0;for(;e<=(r.retryCount||0);)try{let t=yield n();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>(r.retryCount||0))return{success:!1,statusCode:t.statusCode,message:`${o} failed after ${e} attempts with status code ${t.statusCode}`};r.retryDelay&&(yield new Promise(i=>setTimeout(i,r.retryDelay)));continue}return t}catch(t){if(e++,e>(r.retryCount||0))return{success:!1,statusCode:500,message:`${o} failed with error: ${t instanceof Error?t.message:"Unknown error"}`};r.retryDelay&&(yield new Promise(i=>setTimeout(i,r.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"}`}}}),ji=(n,o,r,e)=>J(null,null,function*(){try{let i=h(h({},{"Content-Type":"application/json"}),o||{}),a=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(r)});if(!a.ok)return it.catch(`Error in makeConfigBasedRequest: ${a.status} ${a.statusText}`),e?{data:{},success:!1,statusCode:a.status}:{success:!1,statusCode:a.status};let l=yield a.json();return e?{data:l?.data??{},success:!0,statusCode:200}:{success:!0,statusCode:200}}catch(t){return it.catch("Error in makeConfigBasedRequest:",t),e?{data:{},success:!1,statusCode:500}:{success:!1,statusCode:500}}}),The=n=>{try{return!n||!n?.access?[]:Object.keys(n.access).sort().map(t=>n.access?.[t]?.map(i=>`${t}:${i}`)??[]).reduce((t,i)=>t.flatMap(a=>i.map(l=>[...a,l])),[[]]).map(t=>t.join("_"))}catch(o){return it.catch("Error in utils generateProcessedContext: ",o),[]}},d3=n=>{try{if(!n||!n?.access)return[];let o=Object.keys(n.access).sort(),e=(i=>{let a=[],l=Math.pow(2,i.length);for(let s=1;s<l;s++){let d=[];for(let v=0;v<i.length;v++)s&1<<v&&d.push(i[v]);a.push(d)}return a})(o),t=[];for(let i of e){let a=i.map(l=>{let s=n.access?.[l];return s==null?null:`${l}:${s}`}).filter(l=>l!==null);a.length>0&&t.push(a.join("_"))}return[...new Set(t)]}catch(o){return it.catch("Error in utils generateAllContextCombos: ",o),[]}},BN=({input:n})=>{try{if(!n||!n?.access)return[];let o=n?.access,r=Object.keys(o).sort(),e=[];for(let i of r){let a=o[i];a!=null&&Array.isArray(a)&&a.length>0&&e.push({key:i,values:a})}return e.length===0?[]:e.reduce((i,{key:a,values:l})=>i.length===0?l.map(s=>[{key:a,value:s}]):i.flatMap(s=>l.map(d=>[...s,{key:a,value:d}])),[]).map(i=>{let a={};return i.forEach(({key:l,value:s})=>{a[l]=s}),{access:a}})}catch(o){return it.catch("Error in utils expandContextArraysToSingleValues: ",o),[]}},whe=({input:n})=>{try{if(!n||n.length===0)return{access:{}};let o=new Set;n.forEach(e=>{e?.access&&Object.keys(e.access).forEach(t=>o.add(t))});let r={};for(let e of Array.from(o).sort()){let t=new Set;n.forEach(i=>{if(i?.access){let a=i.access[e];a!=null&&t.add(a)}}),r[e]=t.size>0?Array.from(t).sort():null}return{access:r}}catch(o){return it.catch("Error in utils combineContextsToArrays: ",o),{access:{}}}},bl=t=>J(null,[t],function*({data:n,getSdkProxy:o,userId:r,methodName:e}){try{let i="sdkproxyencryptionanddecryptiononsdk"+(r??""),a=yield dGe({data:n,key:i}),l=(yield o({veltData:a}))?.data?.data?.veltData||{};return yield t1(l,i)}catch(i){return it.catch("Error in utils sdkProxyEncryptDecrypt: "+(e??""),i),n}}),dGe=r=>J(null,[r],function*({data:n,key:o}){try{return yield fc(n,o)}catch{return n}}),lZ=(n,o)=>J(null,null,function*(){try{let r=0;for(;r<=(o.retryCount||0);)try{let e=yield n();if(!e)throw new Error("No response received");return e}catch{if(r++,r>=(o.retryCount||0))return null;o.retryDelay&&(yield new Promise(t=>setTimeout(t,o.retryDelay)))}return null}catch{return null}}),Uo=n=>{try{if(n&&typeof n=="object"){let o=JSON.parse(JSON.stringify(n));return o?.clientOrganizationId&&(o.organizationId=o.clientOrganizationId,delete o.clientOrganizationId),o?.clientGroupId&&(o.groupId=o.clientGroupId,delete o.clientGroupId),o?.userSnippylyId&&delete o.userSnippylyId,delete o?.email_lowercase,delete o?.name_lowercase,o}else return null}catch(o){return it.catch("Error in utils getUserForClient: ",o),null}},Wr=({url:n,apiProxyDomain:o})=>{try{if(o){let r=new URL(n);r.origin&&(n=n.replace(r.origin,o))}return n}catch(r){return it.catch("Error in utils getResolvedApiUrl: ",r),n}},Dhe=(n,o)=>{try{if(!n||!(n instanceof Element))return!1;let r,e;if(o&&typeof o.x=="number"&&typeof o.y=="number")r=o.x,e=o.y;else{let i=n.getBoundingClientRect();r=i.left+i.width/2,e=i.top+i.height/2}let t=document.elementFromPoint(r,e);return!(!t||t===n||n.contains(t))}catch{return!1}};var st=(()=>{let o=class o{constructor(e){this.functions=e,this.sf=!1,this.defaultProperties={},this.draftEvents=[],this.liveStateSyncEvents=Object.values(Y.Events.LiveStateSync||{}),this.eventRateLimitCache={},this.EVENT_LIMIT=50,this.TIME_WINDOW_MS=60*1e3,this.analyticsQueue=[],this.batchTimer=null,this.BATCH_WINDOW_MS=5*1e3,this.MAX_BATCH_SIZE=50;try{this.updateDefaultProperties({sdkVersion:fa()}),window?.location?.href&&(this.defaultProperties.pageUrl=window.location.href)}catch(t){it.catch("Error in AnalyticsService constructor: ",t)}}updateDefaultProperties(e={}){this.defaultProperties=h(h({},this.defaultProperties),e)}setInstalledFeature(e){try{this.defaultProperties?.installedFeatures||(this.defaultProperties.installedFeatures=[]),this.defaultProperties.installedFeatures.includes(e)||this.defaultProperties.installedFeatures.push(e)}catch(t){it.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]=h(h({},this.defaultProperties.featureConfigs[e]),t)}catch(i){it.catch("Error in AnalyticsService setFeatureConfig: ",i)}}setSF(e){try{this.sf=e}catch(t){it.catch("Error in AnalyticsService setSF: ",t)}}setAuthService(e){try{this.authService=e}catch(t){it.catch("Error in AnalyticsService setAuthService: ",t)}}setCommentService(e){try{this.commentService=e}catch(t){it.catch("Error in AnalyticsService setCommentService: ",t)}}setConfigService(e){try{this.configService=e}catch(t){it.catch("Error in AnalyticsService setConfigService: ",t)}}setDomService(e){try{this.domService=e}catch(t){it.catch("Error in AnalyticsService setDomService: ",t)}}setLiveStateService(e){try{this.liveStateService=e}catch(t){it.catch("Error in AnalyticsService setLiveStateService: ",t)}}setAreaService(e){try{this.areaService=e}catch(t){it.catch("Error in AnalyticsService setAreaService: ",t)}}setRecorderAnnotationService(e){try{this.recorderAnnotationService=e}catch(t){it.catch("Error in AnalyticsService setRecorderAnnotationService: ",t)}}setReactionService(e){try{this.reactionService=e}catch(t){it.catch("Error in AnalyticsService setReactionService: ",t)}}setUserService(e){try{this.userService=e}catch(t){it.catch("Error in AnalyticsService setUserService: ",t)}}identifyUser(e,t,i={}){try{this.userId=e;let a=typeof t=="object"?JSON.parse(JSON.stringify(t)):t;this.userService?.externalUserDataProviderAvailable()&&a?.userId&&(a={userId:a.userId}),this.user=a;let l=this.defaultProperties?this.defaultProperties.apiKey:null;if(En.production||En.staging){let s=Date.now(),d={userId:e,clientUserId:this.user?.userId,traits:y(h({},a),{apiKey:l,forceReset:i?.forceReset,eventTimestamp:s}),properties:y(h({},this.defaultProperties),{eventTimestamp:s}),sf:this.sf,context:this.getContext(),eventTimestamp:s};this.setAnalytics("identify",d)}if(this.userId&&this.draftEvents?.length){let s=this.draftEvents?.slice();this.draftEvents=[],s?.forEach(d=>{switch(d.type){case"track":d?.data?.eventName&&this.trackEvent(d.data.eventName,d.data.properties,d.data.mergeDefaultProperties,d.data.userId,d.data.clientUserId);break;default:break}})}}catch(a){it.catch("Error in AnalyticsService identifyUser: ",a)}}trackPage(e,t="",i={}){try{if((En.production||En.staging)&&this.userId){let a={userId:this.userId,clientUserId:this.user?.userId,name:e,properties:i,sf:this.sf,context:this.getContext()};this.setAnalytics("page",a)}}catch(a){it.catch("Error in AnalyticsService trackPage: ",a)}}trackEvent(s){return J(this,arguments,function*(e,t={},i=!0,a,l){try{if(this.sf&&Xpe.includes(e))return Promise.resolve();if(En.production||En.staging)if(this.userId||a){if(this.eventRateLimitCache[e]?.blockedForSession)return Promise.resolve();let d=Date.now();if(this.eventRateLimitCache[e]&&d-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 v=h({eventName:e},t||{});this.triggerTrackEvent(Y.Events.Core.SDK_EVENT_RATE_LIMIT_EXCEEDED,v,i,a,l)}return Promise.resolve()}this.eventRateLimitCache[e].count++}else this.eventRateLimitCache[e]={count:1,timestamp:d,rateLimitExceededEventTriggered:!1,blockedForSession:!1};return this.triggerTrackEvent(e,t,i,a,l)}else return t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.draftEvents.push({type:"track",data:{eventName:e,properties:t,mergeDefaultProperties:i,userId:a,clientUserId:l}}),Promise.resolve();return Promise.resolve()}catch(d){return it.catch("Error in AnalyticsService trackEvent: ",d),Promise.resolve()}})}triggerTrackEvent(s){return J(this,arguments,function*(e,t={},i=!0,a,l){try{i&&(t||(t={}),t=h(h({},t),this.defaultProperties));let d;if(t?.annotationId){let u=t.annotationId;if(!d&&this.commentService){let _=this.commentService.getAnnotationById(u);_?.metadata&&(d=_.metadata),_?.targetElementId&&(t.targetElementId=_.targetElementId);let I=this.commentService.getMultiThreadAnnotationById(u);I?.metadata&&(d=I.metadata),I?.targetElementId&&(t.targetElementId=I.targetElementId)}if(!d&&this.recorderAnnotationService){let _=this.recorderAnnotationService.getAnnotationById(u);_?.metadata&&(d=_.metadata)}if(!d&&this.reactionService){let _=this.reactionService.getAnnotationById(u);_?.metadata&&(d=_.metadata),_?.targetElementId&&(t.targetElementId=_.targetElementId)}if(!d&&this.areaService){let _=this.areaService.getAnnotationById(u);_?.metadata&&(d=_.metadata)}}if(d&&typeof d=="object"&&(t=h(h({},t),d)),t&&typeof t=="object"&&(t=y(h({},t),{userId:this.userId||a,clientUserId:this.user?.userId||l}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),t?.sessionTabId||(t.sessionTabId=this.domService?.getTabId()),this.liveStateSyncEvents.includes(e))){let u=this.liveStateService?.getSemStats();u&&!t?.semStats&&(t.semStats=u)}let v={userId:this.userId||a,clientUserId:this.user?.userId||l,event:e,properties:t,sf:this.sf,context:this.getContext(),eventTimestamp:t?.eventTimestamp};return this.setAnalytics("track",v)}catch(d){return it.catch("Error in AnalyticsService triggerTrackEvent: ",d),Promise.resolve()}})}setAnalytics(e,t){return J(this,null,function*(){try{return navigator.onLine?new Promise((i,a)=>{this.analyticsQueue.push({type:e,body:t,resolve:i,reject:a}),this.analyticsQueue.length>=this.MAX_BATCH_SIZE?this.flushAnalyticsQueue():this.scheduleBatchFlush()}):void 0}catch(i){return it.catch("Error in AnalyticsService setAnalytics: ",i),Promise.resolve()}})}scheduleBatchFlush(){try{this.batchTimer||(this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushAnalyticsQueue()},this.BATCH_WINDOW_MS))}catch(e){it.catch("Error in AnalyticsService scheduleBatchFlush: ",e)}}flushAnalyticsQueue(){return J(this,null,function*(){try{if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.analyticsQueue.length===0||!navigator.onLine)return;let e=[...this.analyticsQueue];this.analyticsQueue=[];try{let t=Gr(this.functions,Wr({url:En.cloudFunction.sa,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),i=e.map(a=>({type:a.type,data:a.body}));try{yield t({type:"batch",data:i}),e.forEach(a=>{try{a.resolve&&a.resolve()}catch(l){it.warn("Error resolving analytics promise: ",l)}})}catch(a){it.warn("Error in AnalyticsService batch flush: ",a),e.forEach(l=>{try{l.reject&&l.reject(a)}catch(s){it.warn("Error rejecting analytics promise: ",s)}})}}catch(t){it.catch("Error in AnalyticsService flushAnalyticsQueue: ",t),e.forEach(i=>{try{i.reject&&i.reject(t)}catch(a){it.warn("Error rejecting analytics promise: ",a)}})}}catch(e){it.catch("Error in AnalyticsService flushAnalyticsQueue: ",e)}})}trackAuthenticatedEvent(e,t={},i=!0){try{this.authService?.getUser$&&typeof this.authService?.getUser$()?.subscribe=="function"&&(this.authService.getUser()?this.trackEvent(e,t,i):((!t||typeof t!="object")&&(t={}),t?.eventTimestamp||(t.eventTimestamp=Date.now()),this.authService?.getUser$()?.pipe($e(a=>!!a),ut(1))?.subscribe(()=>{this.trackEvent(e,t,i)})))}catch(a){it.catch("Error in AnalyticsService trackAuthenticatedEvent: ",a)}}getContext(){try{let e={},t=no();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=phe(),e.userAgent=t?.deviceInfo?.userAgent,e}catch(e){it.catch("Error in AnalyticsService getContext: ",e)}}};o.\u0275fac=function(t){return new(t||o)(X(Do))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var k=(()=>{let o=class o{get debugMode(){return the()}get debugContextMode(){return nhe()}get logsEnabled(){return this.logsEnabled$.value}constructor(e){this.analyticsService=e,this.logsEnabled$=new Se(!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)}}log(e,...t){this.debugMode&&console.log(e,...t)}logContext(e,...t){this.debugContextMode&&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,i,a=!1){try{let l=t?.message;this.logsEnabled$.value&&(l?.toLowerCase()?.includes("permission denied")||l?.toLowerCase()?.includes("permission_denied")||(t!==void 0?console.warn("Velt: ",e,t):console.warn("Velt: ",e))),a||this.analyticsService.trackEvent(Y.Events.Core.SDK_ERROR,h({sourceMethod:e,message:(t?.message?t?.message:t)||e,clientUserId:this.analyticsService?.user?.userId,snippylyUserId:this.analyticsService?.user?.userSnippylyId,source:"sdk"},i||{}))}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ohe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ahe={};var Cg,sZ;(function(){var n;function o(xe,ye){function Oe(){}Oe.prototype=ye.prototype,xe.D=ye.prototype,xe.prototype=new Oe,xe.prototype.constructor=xe,xe.C=function(Re,Ue,ze){for(var Ge=Array(arguments.length-2),$r=2;$r<arguments.length;$r++)Ge[$r-2]=arguments[$r];return ye.prototype[Ue].apply(Re,Ge)}}function r(){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,r),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(xe,ye,Oe){Oe||(Oe=0);var Re=Array(16);if(typeof ye=="string")for(var Ue=0;16>Ue;++Ue)Re[Ue]=ye.charCodeAt(Oe++)|ye.charCodeAt(Oe++)<<8|ye.charCodeAt(Oe++)<<16|ye.charCodeAt(Oe++)<<24;else for(Ue=0;16>Ue;++Ue)Re[Ue]=ye[Oe++]|ye[Oe++]<<8|ye[Oe++]<<16|ye[Oe++]<<24;ye=xe.g[0],Oe=xe.g[1],Ue=xe.g[2];var ze=xe.g[3],Ge=ye+(ze^Oe&(Ue^ze))+Re[0]+3614090360&4294967295;ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[1]+3905402710&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[2]+606105819&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[3]+3250441966&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[4]+4118548399&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[5]+1200080426&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[6]+2821735955&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[7]+4249261313&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[8]+1770035416&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[9]+2336552879&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[10]+4294925233&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[11]+2304563134&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(ze^Oe&(Ue^ze))+Re[12]+1804603682&4294967295,ye=Oe+(Ge<<7&4294967295|Ge>>>25),Ge=ze+(Ue^ye&(Oe^Ue))+Re[13]+4254626195&4294967295,ze=ye+(Ge<<12&4294967295|Ge>>>20),Ge=Ue+(Oe^ze&(ye^Oe))+Re[14]+2792965006&4294967295,Ue=ze+(Ge<<17&4294967295|Ge>>>15),Ge=Oe+(ye^Ue&(ze^ye))+Re[15]+1236535329&4294967295,Oe=Ue+(Ge<<22&4294967295|Ge>>>10),Ge=ye+(Ue^ze&(Oe^Ue))+Re[1]+4129170786&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[6]+3225465664&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[11]+643717713&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[0]+3921069994&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[5]+3593408605&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[10]+38016083&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[15]+3634488961&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[4]+3889429448&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[9]+568446438&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[14]+3275163606&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[3]+4107603335&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[8]+1163531501&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Ue^ze&(Oe^Ue))+Re[13]+2850285829&4294967295,ye=Oe+(Ge<<5&4294967295|Ge>>>27),Ge=ze+(Oe^Ue&(ye^Oe))+Re[2]+4243563512&4294967295,ze=ye+(Ge<<9&4294967295|Ge>>>23),Ge=Ue+(ye^Oe&(ze^ye))+Re[7]+1735328473&4294967295,Ue=ze+(Ge<<14&4294967295|Ge>>>18),Ge=Oe+(ze^ye&(Ue^ze))+Re[12]+2368359562&4294967295,Oe=Ue+(Ge<<20&4294967295|Ge>>>12),Ge=ye+(Oe^Ue^ze)+Re[5]+4294588738&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[8]+2272392833&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[11]+1839030562&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[14]+4259657740&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[1]+2763975236&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[4]+1272893353&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[7]+4139469664&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[10]+3200236656&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[13]+681279174&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[0]+3936430074&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[3]+3572445317&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[6]+76029189&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Oe^Ue^ze)+Re[9]+3654602809&4294967295,ye=Oe+(Ge<<4&4294967295|Ge>>>28),Ge=ze+(ye^Oe^Ue)+Re[12]+3873151461&4294967295,ze=ye+(Ge<<11&4294967295|Ge>>>21),Ge=Ue+(ze^ye^Oe)+Re[15]+530742520&4294967295,Ue=ze+(Ge<<16&4294967295|Ge>>>16),Ge=Oe+(Ue^ze^ye)+Re[2]+3299628645&4294967295,Oe=Ue+(Ge<<23&4294967295|Ge>>>9),Ge=ye+(Ue^(Oe|~ze))+Re[0]+4096336452&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[7]+1126891415&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[14]+2878612391&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[5]+4237533241&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[12]+1700485571&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[3]+2399980690&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[10]+4293915773&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[1]+2240044497&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[8]+1873313359&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[15]+4264355552&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[6]+2734768916&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[13]+1309151649&4294967295,Oe=Ue+(Ge<<21&4294967295|Ge>>>11),Ge=ye+(Ue^(Oe|~ze))+Re[4]+4149444226&4294967295,ye=Oe+(Ge<<6&4294967295|Ge>>>26),Ge=ze+(Oe^(ye|~Ue))+Re[11]+3174756917&4294967295,ze=ye+(Ge<<10&4294967295|Ge>>>22),Ge=Ue+(ye^(ze|~Oe))+Re[2]+718787259&4294967295,Ue=ze+(Ge<<15&4294967295|Ge>>>17),Ge=Oe+(ze^(Ue|~ye))+Re[9]+3951481745&4294967295,xe.g[0]=xe.g[0]+ye&4294967295,xe.g[1]=xe.g[1]+(Ue+(Ge<<21&4294967295|Ge>>>11))&4294967295,xe.g[2]=xe.g[2]+Ue&4294967295,xe.g[3]=xe.g[3]+ze&4294967295}e.prototype.u=function(xe,ye){ye===void 0&&(ye=xe.length);for(var Oe=ye-this.blockSize,Re=this.B,Ue=this.h,ze=0;ze<ye;){if(Ue==0)for(;ze<=Oe;)t(this,xe,ze),ze+=this.blockSize;if(typeof xe=="string"){for(;ze<ye;)if(Re[Ue++]=xe.charCodeAt(ze++),Ue==this.blockSize){t(this,Re),Ue=0;break}}else for(;ze<ye;)if(Re[Ue++]=xe[ze++],Ue==this.blockSize){t(this,Re),Ue=0;break}}this.h=Ue,this.o+=ye},e.prototype.v=function(){var xe=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);xe[0]=128;for(var ye=1;ye<xe.length-8;++ye)xe[ye]=0;var Oe=8*this.o;for(ye=xe.length-8;ye<xe.length;++ye)xe[ye]=Oe&255,Oe/=256;for(this.u(xe),xe=Array(16),ye=Oe=0;4>ye;++ye)for(var Re=0;32>Re;Re+=8)xe[Oe++]=this.g[ye]>>>Re&255;return xe};function i(xe,ye){var Oe=l;return Object.prototype.hasOwnProperty.call(Oe,xe)?Oe[xe]:Oe[xe]=ye(xe)}function a(xe,ye){this.h=ye;for(var Oe=[],Re=!0,Ue=xe.length-1;0<=Ue;Ue--){var ze=xe[Ue]|0;Re&&ze==ye||(Oe[Ue]=ze,Re=!1)}this.g=Oe}var l={};function s(xe){return-128<=xe&&128>xe?i(xe,function(ye){return new a([ye|0],0>ye?-1:0)}):new a([xe|0],0>xe?-1:0)}function d(xe){if(isNaN(xe)||!isFinite(xe))return u;if(0>xe)return B(d(-xe));for(var ye=[],Oe=1,Re=0;xe>=Oe;Re++)ye[Re]=xe/Oe|0,Oe*=4294967296;return new a(ye,0)}function v(xe,ye){if(xe.length==0)throw Error("number format error: empty string");if(ye=ye||10,2>ye||36<ye)throw Error("radix out of range: "+ye);if(xe.charAt(0)=="-")return B(v(xe.substring(1),ye));if(0<=xe.indexOf("-"))throw Error('number format error: interior "-" character');for(var Oe=d(Math.pow(ye,8)),Re=u,Ue=0;Ue<xe.length;Ue+=8){var ze=Math.min(8,xe.length-Ue),Ge=parseInt(xe.substring(Ue,Ue+ze),ye);8>ze?(ze=d(Math.pow(ye,ze)),Re=Re.j(ze).add(d(Ge))):(Re=Re.j(Oe),Re=Re.add(d(Ge)))}return Re}var u=s(0),_=s(1),I=s(16777216);n=a.prototype,n.m=function(){if(M(this))return-B(this).m();for(var xe=0,ye=1,Oe=0;Oe<this.g.length;Oe++){var Re=this.i(Oe);xe+=(0<=Re?Re:4294967296+Re)*ye,ye*=4294967296}return xe},n.toString=function(xe){if(xe=xe||10,2>xe||36<xe)throw Error("radix out of range: "+xe);if(A(this))return"0";if(M(this))return"-"+B(this).toString(xe);for(var ye=d(Math.pow(xe,6)),Oe=this,Re="";;){var Ue=oe(Oe,ye).g;Oe=q(Oe,Ue.j(ye));var ze=((0<Oe.g.length?Oe.g[0]:Oe.h)>>>0).toString(xe);if(Oe=Ue,A(Oe))return ze+Re;for(;6>ze.length;)ze="0"+ze;Re=ze+Re}},n.i=function(xe){return 0>xe?0:xe<this.g.length?this.g[xe]:this.h};function A(xe){if(xe.h!=0)return!1;for(var ye=0;ye<xe.g.length;ye++)if(xe.g[ye]!=0)return!1;return!0}function M(xe){return xe.h==-1}n.l=function(xe){return xe=q(this,xe),M(xe)?-1:A(xe)?0:1};function B(xe){for(var ye=xe.g.length,Oe=[],Re=0;Re<ye;Re++)Oe[Re]=~xe.g[Re];return new a(Oe,~xe.h).add(_)}n.abs=function(){return M(this)?B(this):this},n.add=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0,Ue=0;Ue<=ye;Ue++){var ze=Re+(this.i(Ue)&65535)+(xe.i(Ue)&65535),Ge=(ze>>>16)+(this.i(Ue)>>>16)+(xe.i(Ue)>>>16);Re=Ge>>>16,ze&=65535,Ge&=65535,Oe[Ue]=Ge<<16|ze}return new a(Oe,Oe[Oe.length-1]&-2147483648?-1:0)};function q(xe,ye){return xe.add(B(ye))}n.j=function(xe){if(A(this)||A(xe))return u;if(M(this))return M(xe)?B(this).j(B(xe)):B(B(this).j(xe));if(M(xe))return B(this.j(B(xe)));if(0>this.l(I)&&0>xe.l(I))return d(this.m()*xe.m());for(var ye=this.g.length+xe.g.length,Oe=[],Re=0;Re<2*ye;Re++)Oe[Re]=0;for(Re=0;Re<this.g.length;Re++)for(var Ue=0;Ue<xe.g.length;Ue++){var ze=this.i(Re)>>>16,Ge=this.i(Re)&65535,$r=xe.i(Ue)>>>16,nt=xe.i(Ue)&65535;Oe[2*Re+2*Ue]+=Ge*nt,ae(Oe,2*Re+2*Ue),Oe[2*Re+2*Ue+1]+=ze*nt,ae(Oe,2*Re+2*Ue+1),Oe[2*Re+2*Ue+1]+=Ge*$r,ae(Oe,2*Re+2*Ue+1),Oe[2*Re+2*Ue+2]+=ze*$r,ae(Oe,2*Re+2*Ue+2)}for(Re=0;Re<ye;Re++)Oe[Re]=Oe[2*Re+1]<<16|Oe[2*Re];for(Re=ye;Re<2*ye;Re++)Oe[Re]=0;return new a(Oe,0)};function ae(xe,ye){for(;(xe[ye]&65535)!=xe[ye];)xe[ye+1]+=xe[ye]>>>16,xe[ye]&=65535,ye++}function Ce(xe,ye){this.g=xe,this.h=ye}function oe(xe,ye){if(A(ye))throw Error("division by zero");if(A(xe))return new Ce(u,u);if(M(xe))return ye=oe(B(xe),ye),new Ce(B(ye.g),B(ye.h));if(M(ye))return ye=oe(xe,B(ye)),new Ce(B(ye.g),ye.h);if(30<xe.g.length){if(M(xe)||M(ye))throw Error("slowDivide_ only works with positive integers.");for(var Oe=_,Re=ye;0>=Re.l(xe);)Oe=fe(Oe),Re=fe(Re);var Ue=Ie(Oe,1),ze=Ie(Re,1);for(Re=Ie(Re,2),Oe=Ie(Oe,2);!A(Re);){var Ge=ze.add(Re);0>=Ge.l(xe)&&(Ue=Ue.add(Oe),ze=Ge),Re=Ie(Re,1),Oe=Ie(Oe,1)}return ye=q(xe,Ue.j(ye)),new Ce(Ue,ye)}for(Ue=u;0<=xe.l(ye);){for(Oe=Math.max(1,Math.floor(xe.m()/ye.m())),Re=Math.ceil(Math.log(Oe)/Math.LN2),Re=48>=Re?1:Math.pow(2,Re-48),ze=d(Oe),Ge=ze.j(ye);M(Ge)||0<Ge.l(xe);)Oe-=Re,ze=d(Oe),Ge=ze.j(ye);A(ze)&&(ze=_),Ue=Ue.add(ze),xe=q(xe,Ge)}return new Ce(Ue,xe)}n.A=function(xe){return oe(this,xe).h},n.and=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)&xe.i(Re);return new a(Oe,this.h&xe.h)},n.or=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)|xe.i(Re);return new a(Oe,this.h|xe.h)},n.xor=function(xe){for(var ye=Math.max(this.g.length,xe.g.length),Oe=[],Re=0;Re<ye;Re++)Oe[Re]=this.i(Re)^xe.i(Re);return new a(Oe,this.h^xe.h)};function fe(xe){for(var ye=xe.g.length+1,Oe=[],Re=0;Re<ye;Re++)Oe[Re]=xe.i(Re)<<1|xe.i(Re-1)>>>31;return new a(Oe,xe.h)}function Ie(xe,ye){var Oe=ye>>5;ye%=32;for(var Re=xe.g.length-Oe,Ue=[],ze=0;ze<Re;ze++)Ue[ze]=0<ye?xe.i(ze+Oe)>>>ye|xe.i(ze+Oe+1)<<32-ye:xe.i(ze+Oe);return new a(Ue,xe.h)}e.prototype.digest=e.prototype.v,e.prototype.reset=e.prototype.s,e.prototype.update=e.prototype.u,sZ=Ahe.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=d,a.fromString=v,Cg=Ahe.Integer=a}).apply(typeof Ohe<"u"?Ohe:typeof self<"u"?self:typeof window<"u"?window:{});var jN=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bg={};var cZ,mGe,i1,dZ,m3,$N,mZ,vZ,gZ;(function(){var n,o=typeof Object.defineProperties=="function"?Object.defineProperty:function(G,ce,_e){return G==Array.prototype||G==Object.prototype||(G[ce]=_e.value),G};function r(G){G=[typeof globalThis=="object"&&globalThis,G,typeof window=="object"&&window,typeof self=="object"&&self,typeof jN=="object"&&jN];for(var ce=0;ce<G.length;++ce){var _e=G[ce];if(_e&&_e.Math==Math)return _e}throw Error("Cannot find global object")}var e=r(this);function t(G,ce){if(ce)e:{var _e=e;G=G.split(".");for(var Ne=0;Ne<G.length-1;Ne++){var rt=G[Ne];if(!(rt in _e))break e;_e=_e[rt]}G=G[G.length-1],Ne=_e[G],ce=ce(Ne),ce!=Ne&&ce!=null&&o(_e,G,{configurable:!0,writable:!0,value:ce})}}function i(G,ce){G instanceof String&&(G+="");var _e=0,Ne=!1,rt={next:function(){if(!Ne&&_e<G.length){var Ct=_e++;return{value:ce(Ct,G[Ct]),done:!1}}return Ne=!0,{done:!0,value:void 0}}};return rt[Symbol.iterator]=function(){return rt},rt}t("Array.prototype.values",function(G){return G||function(){return i(this,function(ce,_e){return _e})}});var a=a||{},l=this||self;function s(G){var ce=typeof G;return ce=ce!="object"?ce:G?Array.isArray(G)?"array":ce:"null",ce=="array"||ce=="object"&&typeof G.length=="number"}function d(G){var ce=typeof G;return ce=="object"&&G!=null||ce=="function"}function v(G,ce,_e){return G.call.apply(G.bind,arguments)}function u(G,ce,_e){if(!G)throw Error();if(2<arguments.length){var Ne=Array.prototype.slice.call(arguments,2);return function(){var rt=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(rt,Ne),G.apply(ce,rt)}}return function(){return G.apply(ce,arguments)}}function _(G,ce,_e){return _=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?v:u,_.apply(null,arguments)}function I(G,ce){var _e=Array.prototype.slice.call(arguments,1);return function(){var Ne=_e.slice();return Ne.push.apply(Ne,arguments),G.apply(this,Ne)}}function A(G,ce){function _e(){}_e.prototype=ce.prototype,G.aa=ce.prototype,G.prototype=new _e,G.prototype.constructor=G,G.Qb=function(Ne,rt,Ct){for(var qt=Array(arguments.length-2),Go=2;Go<arguments.length;Go++)qt[Go-2]=arguments[Go];return ce.prototype[rt].apply(Ne,qt)}}function M(G){let ce=G.length;if(0<ce){let _e=Array(ce);for(let Ne=0;Ne<ce;Ne++)_e[Ne]=G[Ne];return _e}return[]}function B(G,ce){for(let _e=1;_e<arguments.length;_e++){let Ne=arguments[_e];if(s(Ne)){let rt=G.length||0,Ct=Ne.length||0;G.length=rt+Ct;for(let qt=0;qt<Ct;qt++)G[rt+qt]=Ne[qt]}else G.push(Ne)}}class q{constructor(ce,_e){this.i=ce,this.j=_e,this.h=0,this.g=null}get(){let ce;return 0<this.h?(this.h--,ce=this.g,this.g=ce.next,ce.next=null):ce=this.i(),ce}}function ae(G){return/^[\s\xa0]*$/.test(G)}function Ce(){var G=l.navigator;return G&&(G=G.userAgent)?G:""}function oe(G){return oe[" "](G),G}oe[" "]=function(){};var fe=Ce().indexOf("Gecko")!=-1&&!(Ce().toLowerCase().indexOf("webkit")!=-1&&Ce().indexOf("Edge")==-1)&&!(Ce().indexOf("Trident")!=-1||Ce().indexOf("MSIE")!=-1)&&Ce().indexOf("Edge")==-1;function Ie(G,ce,_e){for(let Ne in G)ce.call(_e,G[Ne],Ne,G)}function xe(G,ce){for(let _e in G)ce.call(void 0,G[_e],_e,G)}function ye(G){let ce={};for(let _e in G)ce[_e]=G[_e];return ce}let Oe="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Re(G,ce){let _e,Ne;for(let rt=1;rt<arguments.length;rt++){Ne=arguments[rt];for(_e in Ne)G[_e]=Ne[_e];for(let Ct=0;Ct<Oe.length;Ct++)_e=Oe[Ct],Object.prototype.hasOwnProperty.call(Ne,_e)&&(G[_e]=Ne[_e])}}function Ue(G){var ce=1;G=G.split(":");let _e=[];for(;0<ce&&G.length;)_e.push(G.shift()),ce--;return G.length&&_e.push(G.join(":")),_e}function ze(G){l.setTimeout(()=>{throw G},0)}function Ge(){var G=an;let ce=null;return G.g&&(ce=G.g,G.g=G.g.next,G.g||(G.h=null),ce.next=null),ce}class $r{constructor(){this.h=this.g=null}add(ce,_e){let Ne=nt.get();Ne.set(ce,_e),this.h?this.h.next=Ne:this.g=Ne,this.h=Ne}}var nt=new q(()=>new Et,G=>G.reset());class Et{constructor(){this.next=this.g=this.h=null}set(ce,_e){this.h=ce,this.g=_e,this.next=null}reset(){this.next=this.g=this.h=null}}let et,$t=!1,an=new $r,lr=()=>{let G=l.Promise.resolve(void 0);et=()=>{G.then(Hr)}};var Hr=()=>{for(var G;G=Ge();){try{G.h.call(G.g)}catch(_e){ze(_e)}var ce=nt;ce.j(G),100>ce.h&&(ce.h++,G.next=ce.g,ce.g=G)}$t=!1};function _o(){this.s=this.s,this.C=this.C}_o.prototype.s=!1,_o.prototype.ma=function(){this.s||(this.s=!0,this.N())},_o.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Zn(G,ce){this.type=G,this.g=this.target=ce,this.defaultPrevented=!1}Zn.prototype.h=function(){this.defaultPrevented=!0};var So=(function(){if(!l.addEventListener||!Object.defineProperty)return!1;var G=!1,ce=Object.defineProperty({},"passive",{get:function(){G=!0}});try{let _e=()=>{};l.addEventListener("test",_e,ce),l.removeEventListener("test",_e,ce)}catch{}return G})();function Jr(G,ce){if(Zn.call(this,G?G.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,G){var _e=this.type=G.type,Ne=G.changedTouches&&G.changedTouches.length?G.changedTouches[0]:null;if(this.target=G.target||G.srcElement,this.g=ce,ce=G.relatedTarget){if(fe){e:{try{oe(ce.nodeName);var rt=!0;break e}catch{}rt=!1}rt||(ce=null)}}else _e=="mouseover"?ce=G.fromElement:_e=="mouseout"&&(ce=G.toElement);this.relatedTarget=ce,Ne?(this.clientX=Ne.clientX!==void 0?Ne.clientX:Ne.pageX,this.clientY=Ne.clientY!==void 0?Ne.clientY:Ne.pageY,this.screenX=Ne.screenX||0,this.screenY=Ne.screenY||0):(this.clientX=G.clientX!==void 0?G.clientX:G.pageX,this.clientY=G.clientY!==void 0?G.clientY:G.pageY,this.screenX=G.screenX||0,this.screenY=G.screenY||0),this.button=G.button,this.key=G.key||"",this.ctrlKey=G.ctrlKey,this.altKey=G.altKey,this.shiftKey=G.shiftKey,this.metaKey=G.metaKey,this.pointerId=G.pointerId||0,this.pointerType=typeof G.pointerType=="string"?G.pointerType:Mn[G.pointerType]||"",this.state=G.state,this.i=G,G.defaultPrevented&&Jr.aa.h.call(this)}}A(Jr,Zn);var Mn={2:"touch",3:"pen",4:"mouse"};Jr.prototype.h=function(){Jr.aa.h.call(this);var G=this.i;G.preventDefault?G.preventDefault():G.returnValue=!1};var fn="closure_listenable_"+(1e6*Math.random()|0),hi=0;function Po(G,ce,_e,Ne,rt){this.listener=G,this.proxy=null,this.src=ce,this.type=_e,this.capture=!!Ne,this.ha=rt,this.key=++hi,this.da=this.fa=!1}function aa(G){G.da=!0,G.listener=null,G.proxy=null,G.src=null,G.ha=null}function md(G){this.src=G,this.g={},this.h=0}md.prototype.add=function(G,ce,_e,Ne,rt){var Ct=G.toString();G=this.g[Ct],G||(G=this.g[Ct]=[],this.h++);var qt=um(G,ce,Ne,rt);return-1<qt?(ce=G[qt],_e||(ce.fa=!1)):(ce=new Po(ce,this.src,Ct,!!Ne,rt),ce.fa=_e,G.push(ce)),ce};function UC(G,ce){var _e=ce.type;if(_e in G.g){var Ne=G.g[_e],rt=Array.prototype.indexOf.call(Ne,ce,void 0),Ct;(Ct=0<=rt)&&Array.prototype.splice.call(Ne,rt,1),Ct&&(aa(ce),G.g[_e].length==0&&(delete G.g[_e],G.h--))}}function um(G,ce,_e,Ne){for(var rt=0;rt<G.length;++rt){var Ct=G[rt];if(!Ct.da&&Ct.listener==ce&&Ct.capture==!!_e&&Ct.ha==Ne)return rt}return-1}var Ug="closure_lm_"+(1e6*Math.random()|0),vd={};function VC(G,ce,_e,Ne,rt){if(Ne&&Ne.once)return Ch(G,ce,_e,Ne,rt);if(Array.isArray(ce)){for(var Ct=0;Ct<ce.length;Ct++)VC(G,ce[Ct],_e,Ne,rt);return null}return _e=pm(_e),G&&G[fn]?G.K(ce,_e,d(Ne)?!!Ne.capture:!!Ne,rt):BC(G,ce,_e,!1,Ne,rt)}function BC(G,ce,_e,Ne,rt,Ct){if(!ce)throw Error("Invalid event type");var qt=d(rt)?!!rt.capture:!!rt,Go=_h(G);if(Go||(G[Ug]=Go=new md(G)),_e=Go.add(ce,_e,Ne,qt,Ct),_e.proxy)return _e;if(Ne=Vg(),_e.proxy=Ne,Ne.src=G,Ne.listener=_e,G.addEventListener)So||(rt=qt),rt===void 0&&(rt=!1),G.addEventListener(ce.toString(),Ne,rt);else if(G.attachEvent)G.attachEvent(Z2(ce.toString()),Ne);else if(G.addListener&&G.removeListener)G.addListener(Ne);else throw Error("addEventListener and attachEvent are unavailable.");return _e}function Vg(){function G(_e){return ce.call(G.src,G.listener,_e)}let ce=oB;return G}function Ch(G,ce,_e,Ne,rt){if(Array.isArray(ce)){for(var Ct=0;Ct<ce.length;Ct++)Ch(G,ce[Ct],_e,Ne,rt);return null}return _e=pm(_e),G&&G[fn]?G.L(ce,_e,d(Ne)?!!Ne.capture:!!Ne,rt):BC(G,ce,_e,!0,Ne,rt)}function bh(G,ce,_e,Ne,rt){if(Array.isArray(ce))for(var Ct=0;Ct<ce.length;Ct++)bh(G,ce[Ct],_e,Ne,rt);else Ne=d(Ne)?!!Ne.capture:!!Ne,_e=pm(_e),G&&G[fn]?(G=G.i,ce=String(ce).toString(),ce in G.g&&(Ct=G.g[ce],_e=um(Ct,_e,Ne,rt),-1<_e&&(aa(Ct[_e]),Array.prototype.splice.call(Ct,_e,1),Ct.length==0&&(delete G.g[ce],G.h--)))):G&&(G=_h(G))&&(ce=G.g[ce.toString()],G=-1,ce&&(G=um(ce,_e,Ne,rt)),(_e=-1<G?ce[G]:null)&&jC(_e))}function jC(G){if(typeof G!="number"&&G&&!G.da){var ce=G.src;if(ce&&ce[fn])UC(ce.i,G);else{var _e=G.type,Ne=G.proxy;ce.removeEventListener?ce.removeEventListener(_e,Ne,G.capture):ce.detachEvent?ce.detachEvent(Z2(_e),Ne):ce.addListener&&ce.removeListener&&ce.removeListener(Ne),(_e=_h(ce))?(UC(_e,G),_e.h==0&&(_e.src=null,ce[Ug]=null)):aa(G)}}}function Z2(G){return G in vd?vd[G]:vd[G]="on"+G}function oB(G,ce){if(G.da)G=!0;else{ce=new Jr(ce,this);var _e=G.listener,Ne=G.ha||G.src;G.fa&&jC(G),G=_e.call(Ne,ce)}return G}function _h(G){return G=G[Ug],G instanceof md?G:null}var Tv="__closure_events_fn_"+(1e9*Math.random()>>>0);function pm(G){return typeof G=="function"?G:(G[Tv]||(G[Tv]=function(ce){return G.handleEvent(ce)}),G[Tv])}function ki(){_o.call(this),this.i=new md(this),this.M=this,this.F=null}A(ki,_o),ki.prototype[fn]=!0,ki.prototype.removeEventListener=function(G,ce,_e,Ne){bh(this,G,ce,_e,Ne)};function Va(G,ce){var _e,Ne=G.F;if(Ne)for(_e=[];Ne;Ne=Ne.F)_e.push(Ne);if(G=G.M,Ne=ce.type||ce,typeof ce=="string")ce=new Zn(ce,G);else if(ce instanceof Zn)ce.target=ce.target||G;else{var rt=ce;ce=new Zn(Ne,G),Re(ce,rt)}if(rt=!0,_e)for(var Ct=_e.length-1;0<=Ct;Ct--){var qt=ce.g=_e[Ct];rt=Sh(qt,Ne,!0,ce)&&rt}if(qt=ce.g=G,rt=Sh(qt,Ne,!0,ce)&&rt,rt=Sh(qt,Ne,!1,ce)&&rt,_e)for(Ct=0;Ct<_e.length;Ct++)qt=ce.g=_e[Ct],rt=Sh(qt,Ne,!1,ce)&&rt}ki.prototype.N=function(){if(ki.aa.N.call(this),this.i){var G=this.i,ce;for(ce in G.g){for(var _e=G.g[ce],Ne=0;Ne<_e.length;Ne++)aa(_e[Ne]);delete G.g[ce],G.h--}}this.F=null},ki.prototype.K=function(G,ce,_e,Ne){return this.i.add(String(G),ce,!1,_e,Ne)},ki.prototype.L=function(G,ce,_e,Ne){return this.i.add(String(G),ce,!0,_e,Ne)};function Sh(G,ce,_e,Ne){if(ce=G.i.g[String(ce)],!ce)return!0;ce=ce.concat();for(var rt=!0,Ct=0;Ct<ce.length;++Ct){var qt=ce[Ct];if(qt&&!qt.da&&qt.capture==_e){var Go=qt.listener,ml=qt.ha||qt.src;qt.fa&&UC(G.i,qt),rt=Go.call(ml,Ne)!==!1&&rt}}return rt&&!Ne.defaultPrevented}function X2(G,ce,_e){if(typeof G=="function")_e&&(G=_(G,_e));else if(G&&typeof G.handleEvent=="function")G=_(G.handleEvent,G);else throw Error("Invalid listener argument");return 2147483647<Number(ce)?-1:l.setTimeout(G,ce||0)}function $C(G){G.g=X2(()=>{G.g=null,G.i&&(G.i=!1,$C(G))},G.l);let ce=G.h;G.h=null,G.m.apply(null,ce)}class M5 extends _o{constructor(ce,_e){super(),this.m=ce,this.l=_e,this.h=null,this.i=!1,this.g=null}j(ce){this.h=arguments,this.g?this.i=!0:$C(this)}N(){super.N(),this.g&&(l.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function hm(G){_o.call(this),this.h=G,this.g={}}A(hm,_o);var yh=[];function Ac(G){Ie(G.g,function(ce,_e){this.g.hasOwnProperty(_e)&&jC(ce)},G),G.g={}}hm.prototype.N=function(){hm.aa.N.call(this),Ac(this)},hm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fm=l.JSON.stringify,J2=l.JSON.parse,Q2=class{stringify(G){return l.JSON.stringify(G,void 0)}parse(G){return l.JSON.parse(G,void 0)}};function eT(){}eT.prototype.h=null;function kh(G){return G.h||(G.h=G.i())}function xh(){}var Ih={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function wv(){Zn.call(this,"d")}A(wv,Zn);function tT(){Zn.call(this,"c")}A(tT,Zn);var Dv={},zi=null;function gd(){return zi=zi||new ki}Dv.La="serverreachability";function P5(G){Zn.call(this,Dv.La,G)}A(P5,Zn);function Bg(G){let ce=gd();Va(ce,new P5(ce))}Dv.STAT_EVENT="statevent";function HC(G,ce){Zn.call(this,Dv.STAT_EVENT,G),this.stat=ce}A(HC,Zn);function Ba(G){let ce=gd();Va(ce,new HC(ce,G))}Dv.Ma="timingevent";function nT(G,ce){Zn.call(this,Dv.Ma,G),this.size=ce}A(nT,Zn);function Eh(G,ce){if(typeof G!="function")throw Error("Fn must not be null and must be a function");return l.setTimeout(function(){G()},ce)}function wl(){this.g=!0}wl.prototype.xa=function(){this.g=!1};function Ov(G,ce,_e,Ne,rt,Ct){G.info(function(){if(G.g)if(Ct)for(var qt="",Go=Ct.split("&"),ml=0;ml<Go.length;ml++){var ao=Go[ml].split("=");if(1<ao.length){var Dl=ao[0];ao=ao[1];var Ol=Dl.split("_");qt=2<=Ol.length&&Ol[1]=="type"?qt+(Dl+"="+ao+"&"):qt+(Dl+"=redacted&")}}else qt=null;else qt=Ct;return"XMLHTTP REQ ("+Ne+") [attempt "+rt+"]: "+ce+`
197
197
  `+_e+`
198
198
  `+qt})}function R5(G,ce,_e,Ne,rt,Ct,qt){G.info(function(){return"XMLHTTP RESP ("+Ne+") [ attempt "+rt+"]: "+ce+`
199
199
  `+_e+`
@@ -219,7 +219,7 @@ This typically indicates that your device does not have a healthy Internet conne
219
219
  <img src="${o||this.thumbnailWithPlayIconUrl||this.thumbnailUrl}" />
220
220
  </a>
221
221
  `}};var Cp=class{constructor(){this.type="recorder",this.recordingType="audio",this.mode="floating",this.attachment=null,this.attachments=[],this.pageInfo=new Oo}};var EL=class{constructor(){this.type="rewriter",this.rewriterType="copywriter",this.pageInfo=new Oo}};var hO=class{constructor(){this.screenWidth=0,this.screenHeight=0,this.screenScrollHeight=0}};var bp=class{constructor(){this.pageInfo=new Oo}},fO=(function(n){return n.Start="start",n.End="end",n})(fO||{}),lS=(function(n){return n.Avatar="avatar",n.Label="label",n})(lS||{});var TL=class{constructor(){this.sources=[],this.playerState=new CO}},CO=class{constructor(){this.volume=1}};var bO=class{constructor(){this.to=[],this.resolved=!1,this.type="tag",this.pageInfo=new Oo}};var im=class{constructor(){this.visibility="private"}};var wL=class{};var Hs=(function(n){return n.EDITOR="editor",n.VIEWER="viewer",n})(Hs||{}),bo=(function(n){return n.DOES_NOT_EXIST="does_not_exist",n.PERMISSION_DENIED="permission_denied",n.SOMETHING_WENT_WRONG="something_went_wrong",n})(bo||{});var DL=(function(n){return n.INTERNAL="internal",n.EXTERNAL="external",n})(DL||{}),OL=(function(n){return n.UPDATE_DATA="updateData",n})(OL||{});var Nt=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new Se(null),this.disableLogsConfig$=new Se({warnings:!0,suppressAll:!1}),this.apiKey$=new Se(""),this.baseFeatureAllowList=[],this.sf$=new Se(!1),this.sdkType$=new Se("core"),this.logsEnabled$=new Se(!0),this.safeEval$=new Se(!1),this.firestorePersistentCacheEnabled$=new Se(!1),this.encryptionProvider$=new Se(null);try{this.analyticsService.setConfigService(this),this.sdkType$.subscribe(i=>{this.analyticsService.updateDefaultProperties({sdkType:i})},i=>{this.loggingService.catch("Error in ConfigService sdkType$: ",i)}),this.logsEnabled$.subscribe(i=>{i?this.loggingService.enableLogs():this.loggingService.disableLogs(),it.logsEnabled=i},i=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",i)})}catch(i){this.loggingService.catch("Error in ConfigService constructor: ",i)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values(je)),this.baseFeatureAllowList=e.featureAllowList?.slice();try{e.proxyConfig?.authHost?localStorage.setItem(N.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST,btoa(e.proxyConfig.authHost)):localStorage.removeItem(N.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST)}catch{}this.config$.next(e)}catch(t){this.loggingService.catch("Error in ConfigService initConfig: ",t)}}setApiKey(e){this.apiKey$.next(e)}getApiKey(){return this.apiKey$.value}getApiKey$(){return this.apiKey$.asObservable()}getConfig(){return this.config$.value}getConfig$(){return this.config$.asObservable()}disableFeatures(e){try{let t=this.config$.value;t&&(e?.length?t.featureAllowList=this.baseFeatureAllowList.filter(i=>!e.includes(i)):t.featureAllowList=this.baseFeatureAllowList.slice()),this.config$.next(t)}catch(t){this.loggingService.catch("Error in ConfigService disableFeatures: ",t)}}setSF(e){try{this.sf$.next(e),this.analyticsService.setSF(e)}catch(t){this.loggingService.catch("Error in ConfigService setSF: ",t)}}getSF(){try{return this.sf$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSF: ",e),!1}}getSF$(){try{return this.sf$.asObservable().pipe(kt(Jt))}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()}getProxyConfig(){try{return this.config$.value?.proxyConfig}catch(e){this.loggingService.catch("Error in ConfigService getProxyConfig: ",e);return}}getAuthProxyHost(){try{let e=this.config$.value?.proxyConfig?.authHost;if(e)return e;let t=localStorage.getItem(N.LOCAL_STORAGE.VELT_AUTH_PROXY_HOST);return t?atob(t):void 0}catch(e){this.loggingService.catch("Error in ConfigService getAuthProxyHost: ",e);return}}getApiHost(){try{return this.getProxyConfig()?.apiHost||this.config$.value?.apiProxyDomain}catch(e){this.loggingService.catch("Error in ConfigService getApiHost: ",e);return}}getApiProxyDomain(){return this.getApiHost()}enableSafeEval(){try{this.safeEval$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableSafeEval: ",e)}}disableSafeEval(){try{this.safeEval$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableSafeEval: ",e)}}getSafeEval(){try{return this.safeEval$.value}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval: ",e),!1}}getSafeEval$(){try{return this.safeEval$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getSafeEval$: ",e),se(!1)}}enableFirestorePersistentCache(){try{this.firestorePersistentCacheEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ConfigService enableFirestorePersistentCache: ",e)}}disableFirestorePersistentCache(){try{this.firestorePersistentCacheEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ConfigService disableFirestorePersistentCache: ",e)}}isFirestorePersistentCacheEnabled(){try{return this.firestorePersistentCacheEnabled$.value}catch(e){return this.loggingService.catch("Error in ConfigService isFirestorePersistentCacheEnabled: ",e),!1}}getFirestorePersistentCacheEnabled$(){try{return this.firestorePersistentCacheEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in ConfigService getFirestorePersistentCacheEnabled$: ",e),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)(X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bbe=(()=>{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(N.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new U0;return this.setLocalStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getLocalStorageData:",e),new U0}}setLocalStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setLocalStorageData","color: green;");try{if(e){let t=JSON.stringify(e);localStorage?.setItem(N.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(N.LOCALSTORAGE_DATA_ID)}getSessionStorageData(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionStorageData","color: green;");try{let e=sessionStorage?.getItem(N.LOCALSTORAGE_DATA_ID);if(e)return JSON.parse(e);{let t=new U0;return this.setSessionStorageData(t),t}}catch(e){return this.loggingService.catch("Error in getSessionStorageData:",e),new U0}}setSessionStorageData(e){this.loggingService.log("%c[WB] Calling FUNCTION: setSessionStorageData","color: green;");try{if(e){let t=JSON.stringify(e);sessionStorage?.setItem(N.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(N.LOCALSTORAGE_DATA_ID)}catch(e){this.loggingService.catch("Error in deleteSessionStorageData:",e)}}};o.\u0275fac=function(t){return new(t||o)(X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var sv=(()=>{let o=class o{constructor(e,t){this.localStorageService=e,this.loggingService=t,this.avatarList=[{userId:"1",name:"Bear",photoUrl:"https://snippyly.com/assets/avatars/avatar-bear.svg",type:"anonymous"},{userId:"2",name:"Beaver",photoUrl:"https://snippyly.com/assets/avatars/avatar-beaver.svg",type:"anonymous"},{userId:"3",name:"Bunny",photoUrl:"https://snippyly.com/assets/avatars/avatar-bunny.svg",type:"anonymous"},{userId:"4",name:"Cat",photoUrl:"https://snippyly.com/assets/avatars/avatar-cat.svg",type:"anonymous"},{userId:"5",name:"Cow",photoUrl:"https://snippyly.com/assets/avatars/avatar-cow.svg",type:"anonymous"},{userId:"6",name:"Dinosaur",photoUrl:"https://snippyly.com/assets/avatars/avatar-dinosaur.svg",type:"anonymous"},{userId:"7",name:"Elephant",photoUrl:"https://snippyly.com/assets/avatars/avatar-elephant.svg",type:"anonymous"},{userId:"8",name:"Monkey",photoUrl:"https://snippyly.com/assets/avatars/avatar-monkey.svg",type:"anonymous"},{userId:"9",name:"Hedgehog",photoUrl:"https://snippyly.com/assets/avatars/avatar-hedgehog.svg",type:"anonymous"},{userId:"10",name:"Hippo",photoUrl:"https://snippyly.com/assets/avatars/avatar-hippo.svg",type:"anonymous"},{userId:"11",name:"Horse",photoUrl:"https://snippyly.com/assets/avatars/avatar-horse.svg",type:"anonymous"},{userId:"12",name:"Kitten",photoUrl:"https://snippyly.com/assets/avatars/avatar-kitten.svg",type:"anonymous"},{userId:"13",name:"Octopus",photoUrl:"https://snippyly.com/assets/avatars/avatar-octopus.svg",type:"anonymous"},{userId:"14",name:"Oink",photoUrl:"https://snippyly.com/assets/avatars/avatar-oink.svg",type:"anonymous"},{userId:"15",name:"Panda",photoUrl:"https://snippyly.com/assets/avatars/avatar-panda.svg",type:"anonymous"},{userId:"16",name:"Penguin",photoUrl:"https://snippyly.com/assets/avatars/avatar-penguin.svg",type:"anonymous"},{userId:"17",name:"Rabbit",photoUrl:"https://snippyly.com/assets/avatars/avatar-rabbit.svg",type:"anonymous"},{userId:"18",name:"Tiger",photoUrl:"https://snippyly.com/assets/avatars/avatar-tiger.svg",type:"anonymous"}],this.loggingService.log("%c[WB] Creating SERVICE AvatarService","color: blue;")}getSessionAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: getSessionAvatar","color: green;");try{let e=new ra,t=this.localStorageService.getSessionStorageData();if(t.snippylyAvatar)e=t.snippylyAvatar;else{let i=this.generateUserAvatar();t.snippylyAvatar=i,this.localStorageService.setSessionStorageData(t)}return e}catch(e){return this.loggingService.catch("Error in getSessionAvatar:",e),new ra}}generateUserAvatar(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserAvatar","color: green;");try{let e=Math.floor(Math.random()*this.avatarList.length),t=this.avatarList[e];return t.color=this.generateUserColor(),t}catch(e){return this.loggingService.catch("Error in generateUserAvatar:",e),this.avatarList[0]}}generateUserColor(e){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserColor","color: green;");try{if(e)return N.AVATAR_COLOR_LIST[e%N.AVATAR_COLOR_LIST.length];let t=Math.floor(Math.random()*N.AVATAR_COLOR_LIST.length);return N.AVATAR_COLOR_LIST[t]}catch(t){return this.loggingService.catch("Error in generateUserColor:",t),""}}generateUserImage(){this.loggingService.log("%c[WB] Calling FUNCTION: generateUserImage","color: green;");try{return this.getSessionAvatar().photoUrl}catch(e){return this.loggingService.catch("Error in generateUserImage:",e),""}}};o.\u0275fac=function(t){return new(t||o)(X(bbe),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var tr=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new lt),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CoreActionsService triggerAction: ",i)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new lt);let t=this.actionSubjects.get(e);return t?t.asObservable():se(null)}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),se(null)}}};o.\u0275fac=function(t){return new(t||o)(X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:wbe,setPrototypeOf:_be,isFrozen:kWe,getPrototypeOf:xWe,getOwnPropertyDescriptor:IWe}=Object,{freeze:hs,seal:rd,create:IQ}=Object,{apply:EQ,construct:TQ}=typeof Reflect<"u"&&Reflect;hs||(hs=function(o){return o});rd||(rd=function(o){return o});EQ||(EQ=function(o,r){for(var e=arguments.length,t=new Array(e>2?e-2:0),i=2;i<e;i++)t[i-2]=arguments[i];return o.apply(r,t)});TQ||(TQ=function(o){for(var r=arguments.length,e=new Array(r>1?r-1:0),t=1;t<r;t++)e[t-1]=arguments[t];return new o(...e)});var AL=fs(Array.prototype.forEach),EWe=fs(Array.prototype.lastIndexOf),Sbe=fs(Array.prototype.pop),SO=fs(Array.prototype.push),TWe=fs(Array.prototype.splice),PL=fs(String.prototype.toLowerCase),bQ=fs(String.prototype.toString),_Q=fs(String.prototype.match),yO=fs(String.prototype.replace),wWe=fs(String.prototype.indexOf),DWe=fs(String.prototype.trim),am=fs(Object.prototype.hasOwnProperty),ps=fs(RegExp.prototype.test),kO=OWe(TypeError);function fs(n){return function(o){o instanceof RegExp&&(o.lastIndex=0);for(var r=arguments.length,e=new Array(r>1?r-1:0),t=1;t<r;t++)e[t-1]=arguments[t];return EQ(n,o,e)}}function OWe(n){return function(){for(var o=arguments.length,r=new Array(o),e=0;e<o;e++)r[e]=arguments[e];return TQ(n,r)}}function Rr(n,o){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:PL;_be&&_be(n,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let i=r(t);i!==t&&(kWe(o)||(o[e]=i),t=i)}n[t]=!0}return n}function AWe(n){for(let o=0;o<n.length;o++)am(n,o)||(n[o]=null);return n}function Eg(n){let o=IQ(null);for(let[r,e]of wbe(n))am(n,r)&&(Array.isArray(e)?o[r]=AWe(e):e&&typeof e=="object"&&e.constructor===Object?o[r]=Eg(e):o[r]=e);return o}function xO(n,o){for(;n!==null;){let e=IWe(n,o);if(e){if(e.get)return fs(e.get);if(typeof e.value=="function")return fs(e.value)}n=xWe(n)}function r(){return null}return r}var ybe=hs(["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"]),SQ=hs(["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"]),yQ=hs(["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"]),MWe=hs(["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"]),kQ=hs(["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"]),PWe=hs(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),kbe=hs(["#text"]),xbe=hs(["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"]),xQ=hs(["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"]),Ibe=hs(["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"]),ML=hs(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),RWe=rd(/\{\{[\w\W]*|[\w\W]*\}\}/gm),NWe=rd(/<%[\w\W]*|[\w\W]*%>/gm),FWe=rd(/\$\{[\w\W]*/gm),LWe=rd(/^data-[\-\w.\u00B7-\uFFFF]+$/),UWe=rd(/^aria-[\-\w]+$/),Dbe=rd(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),VWe=rd(/^(?:\w+script|data):/i),BWe=rd(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Obe=rd(/^html$/i),jWe=rd(/^[a-z][.\w]*(-[.\w]+)+$/i),Ebe=Object.freeze({__proto__:null,ARIA_ATTR:UWe,ATTR_WHITESPACE:BWe,CUSTOM_ELEMENT:jWe,DATA_ATTR:LWe,DOCTYPE_NAME:Obe,ERB_EXPR:NWe,IS_ALLOWED_URI:Dbe,IS_SCRIPT_OR_DATA:VWe,MUSTACHE_EXPR:RWe,TMPLIT_EXPR:FWe}),IO={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},$We=function(){return typeof window>"u"?null:window},HWe=function(o,r){if(typeof o!="object"||typeof o.createPolicy!="function")return null;let e=null,t="data-tt-policy-suffix";r&&r.hasAttribute(t)&&(e=r.getAttribute(t));let i="dompurify"+(e?"#"+e:"");try{return o.createPolicy(i,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Tbe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Abe(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$We(),o=yn=>Abe(yn);if(o.version="3.3.0",o.removed=[],!n||!n.document||n.document.nodeType!==IO.document||!n.Element)return o.isSupported=!1,o;let{document:r}=n,e=r,t=e.currentScript,{DocumentFragment:i,HTMLTemplateElement:a,Node:l,Element:s,NodeFilter:d,NamedNodeMap:v=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:u,DOMParser:_,trustedTypes:I}=n,A=s.prototype,M=xO(A,"cloneNode"),B=xO(A,"remove"),q=xO(A,"nextSibling"),ae=xO(A,"childNodes"),Ce=xO(A,"parentNode");if(typeof a=="function"){let yn=r.createElement("template");yn.content&&yn.content.ownerDocument&&(r=yn.content.ownerDocument)}let oe,fe="",{implementation:Ie,createNodeIterator:xe,createDocumentFragment:ye,getElementsByTagName:Oe}=r,{importNode:Re}=e,Ue=Tbe();o.isSupported=typeof wbe=="function"&&typeof Ce=="function"&&Ie&&Ie.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:ze,ERB_EXPR:Ge,TMPLIT_EXPR:$r,DATA_ATTR:nt,ARIA_ATTR:Et,IS_SCRIPT_OR_DATA:et,ATTR_WHITESPACE:$t,CUSTOM_ELEMENT:an}=Ebe,{IS_ALLOWED_URI:lr}=Ebe,Hr=null,_o=Rr({},[...ybe,...SQ,...yQ,...kQ,...kbe]),Zn=null,So=Rr({},[...xbe,...xQ,...Ibe,...ML]),Jr=Object.seal(IQ(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Mn=null,fn=null,hi=Object.seal(IQ(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Po=!0,aa=!0,md=!1,UC=!0,um=!1,Ug=!0,vd=!1,VC=!1,BC=!1,Vg=!1,Ch=!1,bh=!1,jC=!0,Z2=!1,oB="user-content-",_h=!0,Tv=!1,pm={},ki=null,Va=Rr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Sh=null,X2=Rr({},["audio","video","img","source","image","track"]),$C=null,M5=Rr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),hm="http://www.w3.org/1998/Math/MathML",yh="http://www.w3.org/2000/svg",Ac="http://www.w3.org/1999/xhtml",fm=Ac,J2=!1,Q2=null,eT=Rr({},[hm,yh,Ac],bQ),kh=Rr({},["mi","mo","mn","ms","mtext"]),xh=Rr({},["annotation-xml"]),Ih=Rr({},["title","style","font","a","script"]),wv=null,tT=["application/xhtml+xml","text/html"],Dv="text/html",zi=null,gd=null,P5=r.createElement("form"),Bg=function(Ke){return Ke instanceof RegExp||Ke instanceof Function},HC=function(){let Ke=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(gd&&gd===Ke)){if((!Ke||typeof Ke!="object")&&(Ke={}),Ke=Eg(Ke),wv=tT.indexOf(Ke.PARSER_MEDIA_TYPE)===-1?Dv:Ke.PARSER_MEDIA_TYPE,zi=wv==="application/xhtml+xml"?bQ:PL,Hr=am(Ke,"ALLOWED_TAGS")?Rr({},Ke.ALLOWED_TAGS,zi):_o,Zn=am(Ke,"ALLOWED_ATTR")?Rr({},Ke.ALLOWED_ATTR,zi):So,Q2=am(Ke,"ALLOWED_NAMESPACES")?Rr({},Ke.ALLOWED_NAMESPACES,bQ):eT,$C=am(Ke,"ADD_URI_SAFE_ATTR")?Rr(Eg(M5),Ke.ADD_URI_SAFE_ATTR,zi):M5,Sh=am(Ke,"ADD_DATA_URI_TAGS")?Rr(Eg(X2),Ke.ADD_DATA_URI_TAGS,zi):X2,ki=am(Ke,"FORBID_CONTENTS")?Rr({},Ke.FORBID_CONTENTS,zi):Va,Mn=am(Ke,"FORBID_TAGS")?Rr({},Ke.FORBID_TAGS,zi):Eg({}),fn=am(Ke,"FORBID_ATTR")?Rr({},Ke.FORBID_ATTR,zi):Eg({}),pm=am(Ke,"USE_PROFILES")?Ke.USE_PROFILES:!1,Po=Ke.ALLOW_ARIA_ATTR!==!1,aa=Ke.ALLOW_DATA_ATTR!==!1,md=Ke.ALLOW_UNKNOWN_PROTOCOLS||!1,UC=Ke.ALLOW_SELF_CLOSE_IN_ATTR!==!1,um=Ke.SAFE_FOR_TEMPLATES||!1,Ug=Ke.SAFE_FOR_XML!==!1,vd=Ke.WHOLE_DOCUMENT||!1,Vg=Ke.RETURN_DOM||!1,Ch=Ke.RETURN_DOM_FRAGMENT||!1,bh=Ke.RETURN_TRUSTED_TYPE||!1,BC=Ke.FORCE_BODY||!1,jC=Ke.SANITIZE_DOM!==!1,Z2=Ke.SANITIZE_NAMED_PROPS||!1,_h=Ke.KEEP_CONTENT!==!1,Tv=Ke.IN_PLACE||!1,lr=Ke.ALLOWED_URI_REGEXP||Dbe,fm=Ke.NAMESPACE||Ac,kh=Ke.MATHML_TEXT_INTEGRATION_POINTS||kh,xh=Ke.HTML_INTEGRATION_POINTS||xh,Jr=Ke.CUSTOM_ELEMENT_HANDLING||{},Ke.CUSTOM_ELEMENT_HANDLING&&Bg(Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Jr.tagNameCheck=Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ke.CUSTOM_ELEMENT_HANDLING&&Bg(Ke.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Jr.attributeNameCheck=Ke.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ke.CUSTOM_ELEMENT_HANDLING&&typeof Ke.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Jr.allowCustomizedBuiltInElements=Ke.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),um&&(aa=!1),Ch&&(Vg=!0),pm&&(Hr=Rr({},kbe),Zn=[],pm.html===!0&&(Rr(Hr,ybe),Rr(Zn,xbe)),pm.svg===!0&&(Rr(Hr,SQ),Rr(Zn,xQ),Rr(Zn,ML)),pm.svgFilters===!0&&(Rr(Hr,yQ),Rr(Zn,xQ),Rr(Zn,ML)),pm.mathMl===!0&&(Rr(Hr,kQ),Rr(Zn,Ibe),Rr(Zn,ML))),Ke.ADD_TAGS&&(typeof Ke.ADD_TAGS=="function"?hi.tagCheck=Ke.ADD_TAGS:(Hr===_o&&(Hr=Eg(Hr)),Rr(Hr,Ke.ADD_TAGS,zi))),Ke.ADD_ATTR&&(typeof Ke.ADD_ATTR=="function"?hi.attributeCheck=Ke.ADD_ATTR:(Zn===So&&(Zn=Eg(Zn)),Rr(Zn,Ke.ADD_ATTR,zi))),Ke.ADD_URI_SAFE_ATTR&&Rr($C,Ke.ADD_URI_SAFE_ATTR,zi),Ke.FORBID_CONTENTS&&(ki===Va&&(ki=Eg(ki)),Rr(ki,Ke.FORBID_CONTENTS,zi)),_h&&(Hr["#text"]=!0),vd&&Rr(Hr,["html","head","body"]),Hr.table&&(Rr(Hr,["tbody"]),delete Mn.tbody),Ke.TRUSTED_TYPES_POLICY){if(typeof Ke.TRUSTED_TYPES_POLICY.createHTML!="function")throw kO('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ke.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kO('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');oe=Ke.TRUSTED_TYPES_POLICY,fe=oe.createHTML("")}else oe===void 0&&(oe=HWe(I,t)),oe!==null&&typeof fe=="string"&&(fe=oe.createHTML(""));hs&&hs(Ke),gd=Ke}},Ba=Rr({},[...SQ,...yQ,...MWe]),nT=Rr({},[...kQ,...PWe]),Eh=function(Ke){let Ut=Ce(Ke);(!Ut||!Ut.tagName)&&(Ut={namespaceURI:fm,tagName:"template"});let cn=PL(Ke.tagName),Ho=PL(Ut.tagName);return Q2[Ke.namespaceURI]?Ke.namespaceURI===yh?Ut.namespaceURI===Ac?cn==="svg":Ut.namespaceURI===hm?cn==="svg"&&(Ho==="annotation-xml"||kh[Ho]):!!Ba[cn]:Ke.namespaceURI===hm?Ut.namespaceURI===Ac?cn==="math":Ut.namespaceURI===yh?cn==="math"&&xh[Ho]:!!nT[cn]:Ke.namespaceURI===Ac?Ut.namespaceURI===yh&&!xh[Ho]||Ut.namespaceURI===hm&&!kh[Ho]?!1:!nT[cn]&&(Ih[cn]||!Ba[cn]):!!(wv==="application/xhtml+xml"&&Q2[Ke.namespaceURI]):!1},wl=function(Ke){SO(o.removed,{element:Ke});try{Ce(Ke).removeChild(Ke)}catch{B(Ke)}},Ov=function(Ke,Ut){try{SO(o.removed,{attribute:Ut.getAttributeNode(Ke),from:Ut})}catch{SO(o.removed,{attribute:null,from:Ut})}if(Ut.removeAttribute(Ke),Ke==="is")if(Vg||Ch)try{wl(Ut)}catch{}else try{Ut.setAttribute(Ke,"")}catch{}},R5=function(Ke){let Ut=null,cn=null;if(BC)Ke="<remove></remove>"+Ke;else{let ii=_Q(Ke,/^[\r\n\t ]+/);cn=ii&&ii[0]}wv==="application/xhtml+xml"&&fm===Ac&&(Ke='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ke+"</body></html>");let Ho=oe?oe.createHTML(Ke):Ke;if(fm===Ac)try{Ut=new _().parseFromString(Ho,wv)}catch{}if(!Ut||!Ut.documentElement){Ut=Ie.createDocument(fm,"template",null);try{Ut.documentElement.innerHTML=J2?fe:Ho}catch{}}let ja=Ut.body||Ut.documentElement;return Ke&&cn&&ja.insertBefore(r.createTextNode(cn),ja.childNodes[0]||null),fm===Ac?Oe.call(Ut,vd?"html":"body")[0]:vd?Ut.documentElement:ja},Av=function(Ke){return xe.call(Ke.ownerDocument||Ke,Ke,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},rT=function(Ke){return Ke instanceof u&&(typeof Ke.nodeName!="string"||typeof Ke.textContent!="string"||typeof Ke.removeChild!="function"||!(Ke.attributes instanceof v)||typeof Ke.removeAttribute!="function"||typeof Ke.setAttribute!="function"||typeof Ke.namespaceURI!="string"||typeof Ke.insertBefore!="function"||typeof Ke.hasChildNodes!="function")},N5=function(Ke){return typeof l=="function"&&Ke instanceof l};function xs(yn,Ke,Ut){AL(yn,cn=>{cn.call(o,Ke,Ut,gd)})}let oT=function(Ke){let Ut=null;if(xs(Ue.beforeSanitizeElements,Ke,null),rT(Ke))return wl(Ke),!0;let cn=zi(Ke.nodeName);if(xs(Ue.uponSanitizeElement,Ke,{tagName:cn,allowedTags:Hr}),Ug&&Ke.hasChildNodes()&&!N5(Ke.firstElementChild)&&ps(/<[/\w!]/g,Ke.innerHTML)&&ps(/<[/\w!]/g,Ke.textContent)||Ke.nodeType===IO.progressingInstruction||Ug&&Ke.nodeType===IO.comment&&ps(/<[/\w]/g,Ke.data))return wl(Ke),!0;if(!(hi.tagCheck instanceof Function&&hi.tagCheck(cn))&&(!Hr[cn]||Mn[cn])){if(!Mn[cn]&&Th(cn)&&(Jr.tagNameCheck instanceof RegExp&&ps(Jr.tagNameCheck,cn)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(cn)))return!1;if(_h&&!ki[cn]){let Ho=Ce(Ke)||Ke.parentNode,ja=ae(Ke)||Ke.childNodes;if(ja&&Ho){let ii=ja.length;for(let dl=ii-1;dl>=0;--dl){let Zs=M(ja[dl],!0);Zs.__removalCount=(Ke.__removalCount||0)+1,Ho.insertBefore(Zs,q(Ke))}}}return wl(Ke),!0}return Ke instanceof s&&!Eh(Ke)||(cn==="noscript"||cn==="noembed"||cn==="noframes")&&ps(/<\/no(script|embed|frames)/i,Ke.innerHTML)?(wl(Ke),!0):(um&&Ke.nodeType===IO.text&&(Ut=Ke.textContent,AL([ze,Ge,$r],Ho=>{Ut=yO(Ut,Ho," ")}),Ke.textContent!==Ut&&(SO(o.removed,{element:Ke.cloneNode()}),Ke.textContent=Ut)),xs(Ue.afterSanitizeElements,Ke,null),!1)},GC=function(Ke,Ut,cn){if(jC&&(Ut==="id"||Ut==="name")&&(cn in r||cn in P5))return!1;if(!(aa&&!fn[Ut]&&ps(nt,Ut))){if(!(Po&&ps(Et,Ut))){if(!(hi.attributeCheck instanceof Function&&hi.attributeCheck(Ut,Ke))){if(!Zn[Ut]||fn[Ut]){if(!(Th(Ke)&&(Jr.tagNameCheck instanceof RegExp&&ps(Jr.tagNameCheck,Ke)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(Ke))&&(Jr.attributeNameCheck instanceof RegExp&&ps(Jr.attributeNameCheck,Ut)||Jr.attributeNameCheck instanceof Function&&Jr.attributeNameCheck(Ut,Ke))||Ut==="is"&&Jr.allowCustomizedBuiltInElements&&(Jr.tagNameCheck instanceof RegExp&&ps(Jr.tagNameCheck,cn)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(cn))))return!1}else if(!$C[Ut]){if(!ps(lr,yO(cn,$t,""))){if(!((Ut==="src"||Ut==="xlink:href"||Ut==="href")&&Ke!=="script"&&wWe(cn,"data:")===0&&Sh[Ke])){if(!(md&&!ps(et,yO(cn,$t,"")))){if(cn)return!1}}}}}}}return!0},Th=function(Ke){return Ke!=="annotation-xml"&&_Q(Ke,an)},ud=function(Ke){xs(Ue.beforeSanitizeAttributes,Ke,null);let{attributes:Ut}=Ke;if(!Ut||rT(Ke))return;let cn={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Zn,forceKeepAttr:void 0},Ho=Ut.length;for(;Ho--;){let ja=Ut[Ho],{name:ii,namespaceURI:dl,value:Zs}=ja,Mc=zi(ii),pd=Zs,Wi=ii==="value"?pd:DWe(pd);if(cn.attrName=Mc,cn.attrValue=Wi,cn.keepAttr=!0,cn.forceKeepAttr=void 0,xs(Ue.uponSanitizeAttribute,Ke,cn),Wi=cn.attrValue,Z2&&(Mc==="id"||Mc==="name")&&(Ov(ii,Ke),Wi=oB+Wi),Ug&&ps(/((--!?|])>)|<\/(style|title|textarea)/i,Wi)){Ov(ii,Ke);continue}if(Mc==="attributename"&&_Q(Wi,"href")){Ov(ii,Ke);continue}if(cn.forceKeepAttr)continue;if(!cn.keepAttr){Ov(ii,Ke);continue}if(!UC&&ps(/\/>/i,Wi)){Ov(ii,Ke);continue}um&&AL([ze,Ge,$r],iT=>{Wi=yO(Wi,iT," ")});let L5=zi(Ke.nodeName);if(!GC(L5,Mc,Wi)){Ov(ii,Ke);continue}if(oe&&typeof I=="object"&&typeof I.getAttributeType=="function"&&!dl)switch(I.getAttributeType(L5,Mc)){case"TrustedHTML":{Wi=oe.createHTML(Wi);break}case"TrustedScriptURL":{Wi=oe.createScriptURL(Wi);break}}if(Wi!==pd)try{dl?Ke.setAttributeNS(dl,ii,Wi):Ke.setAttribute(ii,Wi),rT(Ke)?wl(Ke):Sbe(o.removed)}catch{Ov(ii,Ke)}}xs(Ue.afterSanitizeAttributes,Ke,null)},F5=function yn(Ke){let Ut=null,cn=Av(Ke);for(xs(Ue.beforeSanitizeShadowDOM,Ke,null);Ut=cn.nextNode();)xs(Ue.uponSanitizeShadowNode,Ut,null),oT(Ut),ud(Ut),Ut.content instanceof i&&yn(Ut.content);xs(Ue.afterSanitizeShadowDOM,Ke,null)};return o.sanitize=function(yn){let Ke=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ut=null,cn=null,Ho=null,ja=null;if(J2=!yn,J2&&(yn="<!-->"),typeof yn!="string"&&!N5(yn))if(typeof yn.toString=="function"){if(yn=yn.toString(),typeof yn!="string")throw kO("dirty is not a string, aborting")}else throw kO("toString is not a function");if(!o.isSupported)return yn;if(VC||HC(Ke),o.removed=[],typeof yn=="string"&&(Tv=!1),Tv){if(yn.nodeName){let Zs=zi(yn.nodeName);if(!Hr[Zs]||Mn[Zs])throw kO("root node is forbidden and cannot be sanitized in-place")}}else if(yn instanceof l)Ut=R5("<!---->"),cn=Ut.ownerDocument.importNode(yn,!0),cn.nodeType===IO.element&&cn.nodeName==="BODY"||cn.nodeName==="HTML"?Ut=cn:Ut.appendChild(cn);else{if(!Vg&&!um&&!vd&&yn.indexOf("<")===-1)return oe&&bh?oe.createHTML(yn):yn;if(Ut=R5(yn),!Ut)return Vg?null:bh?fe:""}Ut&&BC&&wl(Ut.firstChild);let ii=Av(Tv?yn:Ut);for(;Ho=ii.nextNode();)oT(Ho),ud(Ho),Ho.content instanceof i&&F5(Ho.content);if(Tv)return yn;if(Vg){if(Ch)for(ja=ye.call(Ut.ownerDocument);Ut.firstChild;)ja.appendChild(Ut.firstChild);else ja=Ut;return(Zn.shadowroot||Zn.shadowrootmode)&&(ja=Re.call(e,ja,!0)),ja}let dl=vd?Ut.outerHTML:Ut.innerHTML;return vd&&Hr["!doctype"]&&Ut.ownerDocument&&Ut.ownerDocument.doctype&&Ut.ownerDocument.doctype.name&&ps(Obe,Ut.ownerDocument.doctype.name)&&(dl="<!DOCTYPE "+Ut.ownerDocument.doctype.name+`>
222
- `+dl),um&&AL([ze,Ge,$r],Zs=>{dl=yO(dl,Zs," ")}),oe&&bh?oe.createHTML(dl):dl},o.setConfig=function(){let yn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};HC(yn),VC=!0},o.clearConfig=function(){gd=null,VC=!1},o.isValidAttribute=function(yn,Ke,Ut){gd||HC({});let cn=zi(yn),Ho=zi(Ke);return GC(cn,Ho,Ut)},o.addHook=function(yn,Ke){typeof Ke=="function"&&SO(Ue[yn],Ke)},o.removeHook=function(yn,Ke){if(Ke!==void 0){let Ut=EWe(Ue[yn],Ke);return Ut===-1?void 0:TWe(Ue[yn],Ut,1)[0]}return Sbe(Ue[yn])},o.removeHooks=function(yn){Ue[yn]=[]},o.removeAllHooks=function(){Ue=Tbe()},o}var sS=Abe();var Mbe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Be=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new lt,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new lt,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new pr),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let s=[];return l.forEach(d=>{if(!Co(d))if(d instanceof HTMLElement){if(d.className.includes("cdk-overlay-container")||d.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(d.className.includes("cdk-overlay")){let v=!1;d.childNodes.forEach(u=>{Co(u)&&(v=!0)}),v||s.push(d)}else s.push(d)}else s.push(d)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Nr(),ln(([s,d])=>{try{let v=d.filter(_=>!s.includes(_)),u=s.filter(_=>!d.includes(_));u.length&&u.map(I=>document.getElementById(I)).filter(I=>I).forEach(I=>{this.unlistenElementScroll&&this.unlistenElementScroll[I.id]&&this.unlistenElementScroll[I.id]()}),v.length&&v.map(I=>document.getElementById(I)).filter(I=>I).forEach(I=>{this.unlistenElementScroll[I.id]=this.renderer.listen(I,"scroll",A=>{let M=this.calculateScreenSize();this.currentScreenSize$.next(M)})})}catch(v){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",v)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?ghe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):uhe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(l){this.loggingService.catch("Error in DomService constructor: ",l)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}setDynamicIdPatterns(e){try{let t=e.map(i=>typeof i=="string"?new RegExp(i):i).filter(Boolean);t.length&&(this.dynamicIdPatterns=t)}catch(t){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",t)}}isLikelyDynamicId(e){try{return e?this.dynamicIdPatterns.some(t=>t.test(e)):!1}catch{return!1}}getStableAttributes(e){try{let t={};if(!e.getAttributeNames)return t;let i=new Set(["id","class","style"]);return e.getAttributeNames().forEach(l=>{if(i.has(l)||l.includes("snippyly")||l.includes("velt"))return;let s=e.getAttribute(l);s&&s.length<=256&&(t[l]=s)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],l=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((d,v)=>{let u=l.findIndex(I=>d.startsWith(I)),_=l.findIndex(I=>v.startsWith(I));return(u===-1?99:u)-(_===-1?99:_)}).slice(0,4).forEach(d=>{let v=CSS.escape(t[d]);a.push(`[${d}="${v}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,s=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),s++,s>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return ehe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],s=e,d=0;for(;s&&s!==document.documentElement&&d<i;){let I=this.buildRobustXPathSegment(s);if(I&&(l.unshift(I),this.isStrongAnchorSegment(I)))break;s=s.parentElement,d++}if(l.length===0)return;let u=(a?"/":"//")+l.join("/");return l.some(I=>I.includes("[@")||I.includes("[contains(@class"))?u:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),i=e.id;if(i&&!this.isLikelyDynamicId(i)&&document.querySelectorAll(`[id="${CSS.escape(i)}"]`).length===1)return`*[@id=${this.escapeXPathValue(i)}]`;let a=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let I of a){let A=e.getAttribute(I);if(A)return`${t}[@${I}=${this.escapeXPathValue(A)}]`}let l=Array.from(e.attributes).filter(I=>I.name.startsWith("data-")&&!I.name.includes("snippyly")&&!I.name.includes("velt")&&I.value.length<100).sort((I,A)=>I.value.length-A.value.length);if(l.length>0){let I=l[0];return`${t}[@${I.name}=${this.escapeXPathValue(I.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let v=e.getAttribute("name");if(v)return`${t}[@name=${this.escapeXPathValue(v)}]`;let u=e.getAttribute("type");if(u)return`${t}[@type=${this.escapeXPathValue(u)}]`;let _=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(_.length>0){let I=_.map(A=>`contains(@class, ${this.escapeXPathValue(A)})`).join(" and ");return`${t}[${I}]`}if(e.parentElement){let I=Array.from(e.parentElement.children).filter(A=>A.tagName===e.tagName);if(I.length>1){let A=I.indexOf(e)+1;return`${t}[${A}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(e.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(a=>e.includes(`[@role='${a}']`))||["data-region","data-instanceid","data-activityid"].some(a=>e.includes(`[@${a}=`)))}catch{return!1}}escapeXPathValue(e,t=!0){try{return e.includes("'")?e.includes('"')?`concat(${e.split("'").map(l=>`'${l}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(s=>`'${s}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(e){try{let t=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),i=[];for(let a=0;a<t.snapshotLength;a++){let l=t.snapshotItem(a);l instanceof Element&&i.push(l)}return i}catch{return[]}}generateAnchorRecord(e,t){try{let i=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Zr(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),i&&a){let l=this.generateAnchorRecordForElement(a,t);l&&(i.parent=l)}return i}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",i),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let i=e,a=i.tagName?.toUpperCase();if(!a)return null;let l=i.id&&!this.isLikelyDynamicId(i.id)?i.id:void 0,s=this.getStableAttributes(i),d=this.buildStableElementSelector(i,s),v=this.getVisibleText(i),u=this.hashText(v||""),_=this.generateRobustXPath(i),I=this.getXPath(i),A=this.getXPath(i,!0),M=this.getXPath(i,!0,!0);return{version:"1.0",id:l,tagName:a,elementSelector:d,robustXPath:_||void 0,xPath:I||void 0,fXPath:A||void 0,cfXPath:M||void 0,contentHash:u?{value:u,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",i),null}}resolveAnchorRecord(e){try{let t=[],i=null,a=(u,_,I=0)=>{let A=[],M=I;if(A.push({method:_,score:I}),e.tagName&&u.tagName?.toUpperCase()===e.tagName&&(M+=10,A.push({method:"tagName-match",score:10})),e.contentHash?.value){let B=this.getVisibleText(u);this.hashText(B)===e.contentHash.value&&(M+=30,A.push({method:"contentHash-match",score:30}))}t.push({el:u,score:M,by:_,scoreBreakdown:A})};if(e.id){let u=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(u.length===1)return{element:u[0],matchedBy:"id",score:90};u.length>1&&u.forEach(_=>a(_,"id-duplicate",70))}if(e.elementSelector){let u=document.querySelectorAll(e.elementSelector);if(u.length===1)return{element:u[0],matchedBy:"element-selector",score:80};u.forEach(_=>a(_,"element-selector-duplicate",60))}e.robustXPath&&this.getAllElementsFromRobustXPath(e.robustXPath).slice(0,20).forEach(A=>a(A,"robustXPath",50)),e?.parent&&(i=this.resolveAnchorRecord(e.parent),i.element&&i.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(_=>a(_,"parent+tag",40)));let l=(u,_,I)=>{if(!u)return;let A=this.getElementFromXPath(u);A&&a(A,_||"xpath",I||30)};if(l(e.xPath,"xPath",30),l(e.cfXPath,"cfXPath",30),l(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let _=I=>{let A=0;for(let M=0;M<I.length&&A<400;M++){let B=I[M];if(A++,!this.isElementVisible(B))continue;let q=this.getVisibleText(B),ae=this.hashText(q);ae&&ae===e.contentHash?.value&&a(B,"contentHash",15)}};if(i?.element&&i?.element instanceof Element){let I=i?.element?.querySelectorAll("*");_(I)}}if(!t.length)return{element:null};t.sort((u,_)=>_.score-u.score);let s=t[0].score,d=t.filter(u=>u.score===s);if(d.length>1){let u=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let _ of u)if(_.path){let I=this.getElementFromXPath(_.path);if(I){let A=d.find(M=>M.el===I);if(A)return{element:A.el,matchedBy:`${A.by}+position`,score:A.score,scoreBreakdown:A.scoreBreakdown}}}}let v=t[0];return{element:v.el,matchedBy:v.by,score:v.score,scoreBreakdown:v.scoreBreakdown}}catch(t){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",t),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ge(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),this.onDocumentClick()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===N.VELT_IGNORE_CHANGE_DETECTION))return;let i=t.filter(a=>a.type==="childList").filter(a=>{let l=a.target;return a.removedNodes.forEach(s=>{let d=s;if(typeof d.getAttribute=="function"){let v=d.getAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(v!==null&&v!==""){let u=this.xpathCacheId.get(v);u!==void 0&&(this.xpathCacheId.delete(v),this.xpathCache.delete(u))}}}),Co(l)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(i.filter(a=>!this.isAnimatingElement(a.target))):this.childListMutation$.next(i),i.push(...t.filter(a=>a.type==="attributes").filter(a=>!Co(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let l=a.target;return l?.classList?.contains("snippyly-sidebar-panel")?!1:l?!l.getAttribute(N.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),i=i.filter(a=>{let l=!0;return Object.keys(N.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(s=>{a.target?.closest(s)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Zr(a.target)),this.animationFilterEnabled&&(i=i.filter(a=>!this.isAnimatingElement(a.target))),i.length&&this.mutation$.next(i)}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let e=window;return e.gsap||e.TweenMax||e.TweenLite||e.TimelineMax||e.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):e.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):e.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):e.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):e.lottie||e.Lottie||e.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(e){try{if(!e||typeof e.closest!="function")return!1;let t=window;if(t.gsap&&typeof t.gsap.isTweening=="function"){if(t.gsap.isTweening(e))return!0;if(typeof t.gsap.getTweensOf=="function")try{if(t.gsap.getTweensOf(e).length>0)return!0}catch{}}else if(t.TweenMax&&typeof t.TweenMax.isTweening=="function"){if(t.TweenMax.isTweening(e))return!0;if(typeof t.TweenMax.getTweensOf=="function")try{if(t.TweenMax.getTweensOf(e).length>0)return!0}catch{}}let i=e.style?.cssText||"";if(i){let d=i.includes("transform")||i.includes("translate3d")||i.includes("translate(")||i.includes("scale3d")||i.includes("rotate"),v=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(v||u))return!0}if(e.style&&(e.style.animation!==""&&e.style.animation!=="none"||e.style.transition!==""&&e.style.transition!=="none")||e.classList?.contains("animate")||e.classList?.contains("animating")||e.classList?.contains("animated")||e.classList?.contains("animation"))return!0;let a=this.staticAnimationCache.get(e);if(a!==void 0)return a;let l=!1,s=e.className||"";return typeof s=="string"&&(s.includes("slider")&&(s.includes("bullet")||s.includes("pagination"))&&(l=!0),s.includes("swiper-pagination")&&(l=!0)),!l&&(e.hasAttribute("data-aos")||e.hasAttribute("data-motion"))&&(l=!0),!l&&e.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(l=!0),this.staticAnimationCache.set(e,l),l}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{Ro(Or(window,"offline").pipe(ge(()=>!1)),Or(window,"online").pipe(ge(()=>!0)),new Ht(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 pr),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()!==N.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return Or(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Pc}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let t=this.getXPath(e.target),i=e.target;if(t?.includes("name()='svg'")){let u=this.getXPath(t);u&&(i=u.iterateNext()||e.target)}let a=i.getBoundingClientRect(),l=e.clientX-a.x,s=e.clientY-a.y,d=l*100/(a.width||1),v=s*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:v,leftPercentage:d}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,i=!1,a=!0,l,s=!0,d){try{let v=e,u=v?.touches?.length?v.touches[0]?.clientX:v?.clientX,_=v?.touches?.length?v.touches[0]?.clientY:v?.clientY;d&&(u=d.clientX,_=d.clientY);let I=this.getBackgroundElement(u,_,t,i);if(I&&l&&typeof l=="function"&&(I=l(I)),I){let A=this.getXPath(I),M=this.getXPath(I,!0),B=I.getBoundingClientRect(),q=u-B.x,ae=_-B.y,Ce=q*100/(B.width||1),oe=ae*100/(B.height||1),fe={xpath:A,fXpath:M,leftPercentage:Ce,topPercentage:oe};if(a){let Ie=this.getXPath(I,!0,!0);fe.cfXpath=Ie}if(s){let Ie=this.generateAnchorRecord(I);Ie&&(fe.anchor=Ie)}return fe}else return null}catch(v){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",v),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),s=[];l.forEach(v=>{Co(v)?s=[]:Zr(v)&&s.push(v)}),a&&(s=s.filter(v=>this.isElementVisibleOnScreen(v)));let d=0;return i||s?.forEach((v,u)=>{v.tagName.toLowerCase()==="svg"&&(d=u)}),s[d]}catch(l){return this.loggingService.catch("Error in DomService getBackgroundElement: ",l),null}}getBackgroundVeltElement(e,t){try{let i=document.elementsFromPoint(e,t),a=[];return i.forEach(l=>{Co(l)&&Zr(l)&&a.push(l)}),a[0]}catch(i){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",i),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),t=this.currentMousePosition?.pageX||e.x+200,i=Math.min(t,e.width/2),a=Math.abs(e.y),l=e.y-20;return a>50&&(l=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(i),this.loggingService.log(l),{topPositionX:i,topPositionY:l}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,t,i){if(e){if(!i&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,N.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),l=e.style.getPropertyPriority("cursor"),s=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(N.ATTRIBUTES.DEFAULT_CURSOR,s?JSON.stringify(s):""),e.style.setProperty("cursor",t,"important")}e.setAttribute(N.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(N.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)){let t=JSON.parse(e.getAttribute(N.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,i,a=!1){try{e&&(this.addClassToElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(N.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(N.VELT_SELECTION_COLOR)&&e.style.setProperty(N.VELT_SELECTION_COLOR,t),i&&e.setAttribute(N.SNIPPYLY_HIGHLIGHT_USER_NAME,i))}catch(l){this.loggingService.catch("Error in DomService highlightUserElement: ",l)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(N.VELT_SELECTION_COLOR),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(N.VELT_SELECTION_COLOR))}catch(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(N.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(N.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,i=!1,a){try{let l=this.calculateXPath(e,t,i,a);if(l&&typeof l=="string"&&l.includes("/svg")){let s=l.split("/"),d=!1;s.forEach((v,u)=>{v.includes("svg")&&(d=!0),d&&(s[u]="svg:"+v)}),l=s.join("/")}return l}catch(l){this.loggingService.catch("Error in DomService getXPath:",l)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,i,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!t)return"//*[@id='"+e.id+"']";if(i&&e.className&&e.className.split){let s=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(s){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),v=Array.from(e.parentNode?.children||[]).filter(u=>u.nodeType===1&&u.tagName===e.tagName?u.className?.split(" ")?.filter(I=>I?.includes("snippyly")||I?.includes("velt")||["show-pin-cursor"].includes(I))[0]===s:!1);if(v.length>1){let u=v.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(s){return s.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,i)+"/"+e.tagName.toLowerCase()+(l.length>1?"["+([].indexOf.call(l,e)+1)+"]":"")}}catch(l){this.loggingService.catch("Error in DomService calculateXPath:",l)}}getElementFromXPath(e,t=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let i=this.getXPath(e,!1,!1,t);if(i){let a=i?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let l=at();a.setAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,l),this.xpathCacheId.set(l,e)}return this.xpathCache.set(e,a),a}return null}catch(i){return this.loggingService.catch("Error in DomService getElementFromXPath:",i),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let i=this.resolveAnchorRecord(e.anchor);i?.element&&(t=i.element)}else e?.xpath?t=this.getElementFromXPath(e.xpath):e?.cfXpath?t=this.getElementFromXPath(e.cfXpath):e?.fXpath&&(t=this.getElementFromXPath(e.fXpath));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",t),null}}getElementFromTargetTextRange(e){try{let t=null;if(e?.commonAncestorContainerAnchor){let i=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);i?.element&&(t=i.element)}else e?.commonAncestorContainer&&(t=this.getElementFromXPath(e.commonAncestorContainer));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",t),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],t=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let i=new hO;return i.screenWidth=Math.max(...t),i.screenHeight=Math.max(...e),i.screenScrollHeight=this.pageScrollHeight,i}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new hO}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let i=new DOMParser().parseFromString(e,"text/html");i.querySelectorAll("[data-snippyly-cache-id]").forEach(_=>{_.removeAttribute("data-snippyly-cache-id")}),i.querySelectorAll("[data-velt-cache-id]").forEach(_=>{_.removeAttribute("data-velt-cache-id")}),i.querySelectorAll(".comment-text-highlight").forEach(_=>{_?.parentNode?.insertBefore(document.createTextNode(_?.textContent),_),_.remove()});let d=document.createNodeIterator(i,NodeFilter.SHOW_COMMENT),v;for(;v=d.nextNode();)v?.remove();return this.mergeAdjacentTextNodes(i.body),this.sanitizeHtml(i.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let i=t.nextSibling;for(;i&&i.nodeType===Node.TEXT_NODE;)t.textContent+=i.textContent,i.remove(),i=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let i=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(i,this.pageScrollHeight),this.nodeMap[i]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let i=Array.from(document.querySelectorAll(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];i.push(...a),i=Array.from(new Set(i));let l=i.map(u=>u.classList.contains("velt-annotation-draft-checked")?(u.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(u,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(u,"velt-comment-dialog-shake"),u.getAttribute(N.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||u.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(u,"velt-annotation-draft-checked")},100),u.getAttribute(N.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(u=>u),s=Object.keys(this.getRecordingInProgress()||{});l=[...l,...s];let d=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let u=[];Object.keys(d).forEach(_=>{if(d[_]?.type==="tag"){let I=d[_];I?.to?.length||l.includes(_)||u.push(I)}else d[_]?.comments?.length||l.includes(_)||u.push(d[_])}),this.deleteAnnotations$.next(u),this.deleteAnnotations$.next([])}let v={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(v[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(v[u]=d[u]);break;default:d[u]?.type!==t&&(v[u]=d[u]);break}}),Object.keys(v).forEach(u=>{let _=v[u]?.multiThreadAnnotationId;_&&!v[_]&&(v[_]={annotationId:_,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(v)&&this.selectedAnnotationsMap$.next(v),this.setDialogOpenedInSidebar(!1)}catch(i){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",i)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(y(h({},this.recordingInProgress$.value),{[e]:t}));else{let i=this.recordingInProgress$.value;delete i[e],this.recordingInProgress$.next(i)}}catch(i){this.loggingService.catch("Error in DomService setRecordingInProgress: ",i)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[],t=Array.from(document.querySelectorAll(`${N.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),i=Array.from(document.querySelectorAll(`${N.TAGS.VELT_COMMENT_DIALOG}`));return[...t,...i].forEach(l=>{if(l?.shadowRoot){let s=l.shadowRoot.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=l.querySelector(`${N.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(s?.shadowRoot){let d=s.shadowRoot?.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}else{let d=l.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let i={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(i[a]=t[a]);break;default:t[a].type===e&&(i[a]=t[a]);break}}),i}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ge(t=>{if(e){let i={};return Object.keys(t).forEach(a=>{t[a].type===e&&(i[a]=t[a])}),i}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ge(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,t,i,a=!1,l){try{i==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));s[e.annotationId]&&!a?delete s[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(s[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(s),Object.keys(d).forEach(v=>{s[v]||delete d[v]}),this.selectedAnnotationsLocationMap$.next(d)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,t){try{let i=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));i?.[e]!==t&&(i[e]=t,this.selectedAnnotationsLocationMap$.next(i))}catch(i){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",i)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(i=>{t[i.annotationId]&&(t[i.annotationId]=i)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),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 i={offsetTop:0,offsetLeft:0},a=e;if(a===t){let l=window.getComputedStyle(e);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(i.offsetLeft=e?.offsetLeft||0,i.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let s=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let v=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-v.left,i.offsetTop+=u.top-v.top}}else s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let d=window.getComputedStyle(a);d.position==="static"&&d.transformStyle!="preserve-3d"&&d.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0)}}else{let s=window.getComputedStyle(a);s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop)}return i}catch(i){return this.loggingService.catch("Error in DomService getElementOffset: ",i),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:i,top:a,bottom:l}=e?.getBoundingClientRect();return t>0||i>0||a<window.innerHeight&&l>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,i=window.getComputedStyle(t);return!(i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ht(e=>{let t=Or(document,"mousedown").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=Or(document,"mousemove").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=Or(document,"mouseup").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),s=t.pipe(be(d=>i.pipe(Nr(),ge(([v,u])=>({startPoint:d,prevPoint:v,curPoint:u})),zo(a)))).subscribe(e);return()=>s.unsubscribe()})}drawRectangle(e,t){let i=document.querySelector(".rectangle");i||(i=document.createElement("div"),this.addClassToElement(i,"rectangle"),i.setAttribute(N.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),i.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(i));let a=Math.abs(t.x-e.x),l=Math.abs(t.y-e.y),s=Math.min(e.x,t.x),d=Math.min(e.y,t.y);return i.style.width=`${a}px`,i.style.height=`${l}px`,i.style.left=`${s}px`,i.style.top=`${d}px`,i.style.position="absolute",i.style.border="2px dashed #f00",i.style.pointerEvents="none",i.style.zIndex="2147483577",i}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let t={},i=e.commonAncestorContainer;i?.nodeType===Node.TEXT_NODE&&(i=i.parentElement);let a=document.body;if(i){let s=this.getTextXPath(i);this.isXpathWithId(s)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let s=this.getElementFromXPath(t.commonAncestorContainer);if(s){t.commonAncestorContainerFXpath=this.getXPath(s,!0),t.commonAncestorContainerCFXpath=this.getXPath(s,!0,!0);let d=this.generateAnchorRecord(s);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=s0(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,i=e.previousSibling;for(;i;)i.nodeType===Node.TEXT_NODE&&t++,i=i.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(N.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let i=e?.closest("picture");return i?i?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,elementQuerySelectors:i}){try{let a=[];if(e?.length)for(let l=0;l<e.length;l++){let s=document.getElementById(e[l]);s&&a.push(s)}if(t?.length)for(let l=0;l<t.length;l++){let s=document.getElementsByClassName(t[l]);for(let d=0;d<s.length;d++){let v=s[d];v&&v instanceof HTMLElement&&a.push(v)}}if(i?.length)for(let l=0;l<i.length;l++){let s=document.querySelectorAll(i[l]);for(let d=0;d<s.length;d++){let v=s[d];v&&v instanceof HTMLElement&&a.push(v)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementById(t[i]);if(a&&a.contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",i),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementsByClassName(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",i),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.querySelectorAll(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",i),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(i){this.loggingService.catch("Error in DomService addClassToElement: ",i)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(i){this.loggingService.catch("Error in DomService removeClassFromElement: ",i)}}isElementInsideParentWithAttribute(e,t,i){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===i)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let i=e?.shadowRoot?.querySelector(`[${N.VELT_CUSTOM_CSS}]`);if(i&&i.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.value,a.rel="stylesheet",a.setAttribute(N.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(t?.value),a.setAttribute(N.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let i=t.innerHTML;return i=i.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),i}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(l){return i.test(l.innerHTML)};var t=a;let i=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(i){this.loggingService.catch("Error in DomService removeEmptyElements: ",i)}}normalizeWhitespace(e){try{e.childNodes.forEach(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),sS.sanitize(e,Mbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeHtmlForPaste(e){try{let t=this.convertStylesToTags(e);return sS.sanitize(t,{ALLOWED_TAGS:["b","strong","i","em","u","a","br"],ALLOWED_ATTR:["href","target","rel"]})}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtmlForPaste: ",t),""}}convertStylesToTags(e){try{let t=document.createElement("div");return t.innerHTML=e,this.processNodeStyles(t),t.innerHTML}catch(t){return this.loggingService.catch("Error in DomService convertStylesToTags: ",t),e}}processNodeStyles(e){try{let t=Array.from(e.childNodes);for(let i of t)if(i.nodeType===Node.ELEMENT_NODE){this.processNodeStyles(i);let a=i,l=a.style,s=i,d=l?.fontWeight;if(d==="bold"||d==="700"||d==="800"||d==="900"){let v=a.tagName?.toLowerCase();if(v!=="b"&&v!=="strong"){let u=document.createElement("b");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}if(l?.fontStyle==="italic"){let v=(s.nodeType===Node.ELEMENT_NODE?s.tagName:"")?.toLowerCase();if(v!=="i"&&v!=="em"){let u=document.createElement("i");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}if((l?.textDecorationLine?.includes("underline")||l?.textDecoration?.includes("underline"))&&(s.nodeType===Node.ELEMENT_NODE?s.tagName:"")?.toLowerCase()!=="u"){let u=document.createElement("u");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}}catch(t){this.loggingService.catch("Error in DomService processNodeStyles: ",t)}}sanitizeSvg(e){try{return sS.sanitize(e,Mbe)}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 pr;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 pr)}}getTabId(){try{let e=sessionStorage.getItem(N.SESSION_STORAGE.VELT_TAB_ID);!e&&this.tabId&&(e=this.tabId,sessionStorage.setItem(N.SESSION_STORAGE.VELT_TAB_ID,e)),!this.tabId&&e&&(this.tabId=e);let t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=at(),this.tabId=e,sessionStorage.setItem(N.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 pr}}isMobileDevice(){try{return new pr().getDeviceType()===Bi.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new pr().getDeviceType()===Bi.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new pr().getDeviceType()===Bi.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(i=>{t.setAttribute(i.nodeName,i.nodeValue)}),e.childNodes.forEach(i=>{i.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(i)):i.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(i.nodeValue))}),t}catch(i){return this.loggingService.catch("Error in DomService deepCloneElement: ",i),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(i=>{if(this.removeWireframeSuffixFromTags(i),i.tagName.toLowerCase().endsWith("-wireframe")){let a=i.tagName.toLowerCase().replace("-wireframe",""),l=document.createElement(a);for(Array.from(i.attributes).forEach(s=>{l.setAttribute(s.name,s.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new pr().getDeviceType()===Bi.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}isElementOriginallyStatic(e){try{return window.getComputedStyle(e).position==="static"||e.hasAttribute(N.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_AREA_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_TAG_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_RECORDER_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_ARROW_PIN_HOST_STATIC)}catch(t){return this.loggingService.catch("Error in DomService isElementOriginallyStatic: ",t),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(X(st),X(xi),X(k),X(Rd))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qe=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=s,this.analyticsService=d,this.loggingService=v,this.user$=new Se(null),this.userOptions$=new Se(null),this.userContacts$=new Se(null),this.userOrganization$=new Se(null),this.isPrivateCommentsEnabled$=new Se(!1),this.providedUser=new ra,this.firebaseConfig$=new Se(null),this.advancedQueries$=new Se(null),this.planDetails$=new Se(null),this.signOutPreviousUser$=new Se(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.onRetrySubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{try{let u=this.configService.getAuthProxyHost();if(u){let _=this.afAuth?.config;_&&(_.apiHost=u,_.tokenApiHost=u)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(u=>{this.config=u}),this.forceReLoggedIn=localStorage.getItem(N.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Cr(this.afAuth).pipe(yo(this.afAuth.currentUser),Nr(),be(([u,_])=>this.domService.onNetworkStatusChange$().pipe($e(I=>I),ut(1),ge(()=>({previousUser:u,currentUser:_}))))).subscribe(I=>J(this,[I],function*({previousUser:u,currentUser:_}){if(!_&&u){let A=u?.stsTokenManager?.expirationTime,M=new Date().getTime(),B=A-M;M>A&&(this.analyticsService.trackEvent(Y.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&u?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Y.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Y.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:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),u=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",u)}),this.getUser$().pipe(kt(Jt)).subscribe(u=>{let _=Uo(u);this.coreActionsService.triggerAction(tt.USER_UPDATE,_),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:tt.USER_UPDATE,payload:{user:_}})})}catch(u){this.loggingService.catch("Error in AuthService constructor: ",u)}}setApiKey(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),t||(t=new fL),this.configService.initConfig(t);let i=this.configService.getProxyConfig();if(i?.authHost)try{let a=this.afAuth?.config;a&&(a.apiHost=i.authHost,a.tokenApiHost=i.authHost)}catch(a){this.loggingService.catch("Error setting auth proxy config: ",a)}t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Cr(this.afAuth).pipe(ut(1)).subscribe(a=>J(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Hm(a,!0).catch(s=>null);if(l){let{user:s}=l?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?y(h({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(i){this.loggingService.catch("Error in setApiKey: ",i)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setActivityService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setActivityService","color: green;"),this.activityService=e}catch(t){this.loggingService.catch("Error in setActivityService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}setCrdtService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCrdtService","color: green;"),this.crdtService=e}catch(t){this.loggingService.catch("Error in setCrdtService: ",t)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(Y.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 J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;if(!e.user)return null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let i=yield lZ(()=>window.Velt.identify(e.user,h(h({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}).catch(a=>(e.onError&&typeof e.onError=="function"&&e.onError(a),Promise.reject(a))),e.retryConfig||{retryCount:0,retryDelay:0});return i&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(tt.ERROR).pipe($e(a=>a.code==="token_expired"),ut(10)).subscribe(a=>J(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],s=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],v=this.docService?.getLocation();v&&d.push(v.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(I=>{d.push(I.location)}),(yield lZ(()=>J(this,null,function*(){try{let I=yield e.generateToken?.();return I?window.Velt.identify(e.user,h(h({},e.options||{}),I&&{authToken:I}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:l,options:s,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!v}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return J(this,null,function*(){try{if(e){let t=yield fc(e,e?.userId??"");localStorage.setItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return J(this,null,function*(){try{let t=localStorage.getItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield t1(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}setIsPrivateCommentsEnabled(e){try{this.isPrivateCommentsEnabled$.next(e)}catch(t){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",t)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(e){return J(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),i=yield this.getUserFromStorage(t);return!i||Object.keys(i).length===0?(delete t?.color,delete t?.textColor,t):(i?.color&&(t.color=i?.color),i?.textColor&&(t.textColor=i?.textColor),t)}catch(t){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",t),e}})}updateUserIfRequired(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let t=yield this.getUserFromStorage(e),i={};e.color&&e.color!==t?.color&&(i.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(i.textColor=e.textColor),Object.keys(i).length>0&&e.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:e.clientOrganizationId,user:y(h({},i),{userId:e.userId})})}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,i,a,l){return J(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=ed(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let s=yield Cr(this.afAuth).pipe(ut(1)).toPromise().catch(v=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),s){let v=yield Hm(s,!0).catch(A=>null);if(!v)return;let{user:u,firebaseConfig:_,advancedQueries:I}=v.claims;s?.uid!==e?.userSnippylyId||e?.groupId!==u?.groupId||e?.organizationId!==u?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,_)||this.forceReLoginRequiredForCommentViews(e)?(localStorage.setItem(N.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(N.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal")):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(_),this.setAdvancedQueries(I),u&&(this.providedUser.isAdmin=!!u.isAdmin),this.initializeSignedInUser(s,a,e),d=!1,this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l}))}if(d){this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l},!0,e.userSnippylyId,e.userId);let v=Gr(this.functions,Wr({url:En.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=fa(),_=(yield v({apiKey:this.apiKey,user:e,version:u,authToken:t?.authToken}))?.data;if(_.error){if(this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_FAILED,y(h({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:_.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},_),{source:l}),!0,e.userSnippylyId,e.userId),_.error&&typeof _.error=="string")if(_.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let I={code:"token_expired",message:"Token expired",error:_?.error,source:_?.source};this.coreActionsService.triggerAction(tt.ERROR,I)}else{let I={code:"too_many_retries",message:"Token expired. Too many retries.",error:_?.error,source:_?.source};this.coreActionsService.triggerAction(tt.ERROR,I),this.analyticsService.trackEvent(Y.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:l},!0,e.userSnippylyId,e.userId)}else{let I=_;this.coreActionsService.triggerAction(tt.ERROR,I)}throw _}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),_.firebaseConfig){this.setFirebaseConfig(_.firebaseConfig),yield this.signInWithCustomToken(e,_.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let I=yield Hm(this.afAuth.currentUser,!0).catch(B=>null);if(!I)return;let{user:A,advancedQueries:M}=I.claims;this.setAdvancedQueries(M),this.providedUser.isAdmin=!!A?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:i,autoLogin:a},this.checkForPendingLogin()}return e}catch(s){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",s),t?.throwError?Promise.reject(s):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=fa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=fa();if(e){let t=e.split("."),i=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),l=parseInt(t[2]||"0");if(i>=4&&a>=5)return i===4&&a===5&&l===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),i=!1;try{let a=localStorage.getItem(N.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(i=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),i=!1;try{let a=localStorage.getItem(N.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(i=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",i),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:h(h({},En.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(N.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 Cn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ge(()=>this.getAdvancedQueriesEnabled()),Xn(()=>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;"),Cr(this.afAuth).pipe(be(e=>e?this.user$.asObservable():se(null)),kt(Jt))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=h(h({},this.providedUser),e),t){let i=h(h({},t),e);this.updateUserInternally(i)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,i="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return Dde(this.afAuth,t).then(a=>(this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.setIsPrivateCommentsEnabled(!1),this.activityService?.setActivityFeatureConfig({immutable:!1,isEnabled:!1})}catch(e){this.loggingService.catch("Error in clearCache: ",e)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new ra;a.userSnippylyId=e.uid,a.type="signedIn",i&&(a=h(h({},a),i)),this.setUserToStorage(a),this.mergeUserWithProvidedUserData(a,t)}catch(a){this.loggingService.catch("Error in initializeSignedInUser: ",a)}}mergeUserWithProvidedUserData(e,t){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let i=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=at(),l=xc.IDENTIFY;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:gi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let s=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});s&&s[e.userId]&&(i=JSON.parse(JSON.stringify(s[e.userId]||{}))),e=h(h({},e),i||{})}e.name=i?i?.name:this.providedUser?.name||e.name,e.clientUserName=i?i?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=i?i?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=i?i?.email:this.providedUser?.email||e.email,e.color=i?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=i?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=i?.initial||this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(i){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",i)}})}updateUserInternally(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||this.getPlanDetailsFromDb();let i=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=bl({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let v=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:oo.IDENTIFY,organizationId:e.clientOrganizationId}}],u=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:v}}),l=this.userPermissionService?.onResourceAccessRequired({requests:v,uniqueId:u,userId:e.userId,methodName:oo.IDENTIFY,fromCache:!1})??Promise.resolve()}let[s,d]=yield Promise.allSettled([a,l]);s.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!s.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(s.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",s.reason),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),i=y(h({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return J(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield Gr(this.functions,Wr({url:En.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:fa(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Y.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe($e(e=>!!e),ge(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreSignOutFuction: ",i)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(be(e=>e?this.userOrganization$.asObservable().pipe(ge(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return J(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(Y.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 Cr(this.afAuth).pipe(ut(1)).toPromise().catch(i=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[i,a]of this.preSignOutFunctions)try{yield a(t)}catch(l){this.loggingService.catch(`Error in signOutUser ${i} function: `,l)}return this.user$.next(null),yield qu(1e3),Ode(this.afAuth).catch(i=>{this.loggingService.catch("Error in signOutUser:",i)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return Ao(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return Uo(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Qn(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(Nt),X(sv),X(tr),X(Be),X(Do),X(st),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $n=(()=>{let o=class o{constructor(e,t,i){this.authService=e,this.configService=t,this.loggingService=i,this.db$=new Se(null);try{this.authService.getFirebaseConfig$().subscribe(a=>{if(a){let l=this.configService.getProxyConfig(),s=a.firebaseOptions.databaseURL;l?.v1DbHost&&s&&(s=wN(s,l.v1DbHost),l?.forceLongPolling&&Kq());let d=I_(void 0,s);l?.v1DbHost&&s&&this.lockDatabaseHost(d),this.db$.next(d)}},a=>{this.loggingService.catch("Error in DatabaseService constructor: ",a)})}catch(a){this.loggingService.catch("Error in DatabaseService constructor:",a)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(e){try{let i=e?._repo?.repoInfo_;if(i){let a=i.host;Object.defineProperty(i,"host",{get:()=>a,set:()=>{},configurable:!0}),i.internalHost=a}}catch(t){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",t)}}};o.\u0275fac=function(t){return new(t||o)(X(qe),X(Nt),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var RL=class{};var rl=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new Se(null),this.commentAnnotationById$=new Se({}),this.fieldsToRemove=[],this.additionalFields=[],this.getCommentAnnotationById=a=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",l);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]))})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",a)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:e}}),_(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],B=y(h({},e),{commentAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.commentAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.commentAnnotationById$.next(h(h({},this.commentAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=h(h({},l),e.commentAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let a=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let l=this.commentAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.commentAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:v,event:Io.COMMENT_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:v,event:Io.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:I,commentAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):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}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.commentAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new Se(null),this.reactionAnnotationById$=new Se({}),this.getReactionAnnotationById=a=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",l);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",a)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:e}}),_(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],B=y(h({},e),{reactionAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.reactionAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.reactionAnnotationById$.next(h(h({},this.reactionAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=h(h({},l),e);let s={reactionAnnotation:e,event:Io.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Ai(()=>i?.config?.saveConfig?.url?ji(i.config.saveConfig.url,i.config.saveConfig.headers,s,!1):i?.save?.(s)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return d&&d.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(d?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:d,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:s.event}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let a=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=t??l?.[e]?.metadata,d=s?ti(s):void 0,v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.reactionAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:v,event:Io.REACTION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:v,event:Io.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:I,reactionAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):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 t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(a){this.loggingService.catch("Error in AttachmentResolverService constructor:",a)}}getProvider(e){try{let t=e||"default";return this.providers.get(t)||void 0}catch(t){this.loggingService.catch("Error in AttachmentResolverService getProvider:",t);return}}getRetrySaveConfig(e){let t=e||"default";return this.retrySaveConfigs.get(t)||this.defaultRetryConfig}getRetryDeleteConfig(e){let t=e||"default";return this.retryDeleteConfigs.get(t)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(e,t,i,a){return J(this,null,function*(){try{let l=new FormData;l.append("file",i);let s={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(s));let d={};t&&Object.entries(t).forEach(([_,I])=>{_.toLowerCase()!=="content-type"&&(d[_]=I)});let v=yield fetch(e,{method:"POST",headers:d,body:l});return v.ok?{data:(yield v.json())?.data??{},success:!0,statusCode:200}:(it.catch(`Error in makeAttachmentConfigBasedRequest: ${v.status} ${v.statusText}`),{data:{},success:!1,statusCode:v.status})}catch(l){return it.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let a=this.getProvider(i);if(!this.attachmentDataProviderAvailable(i))throw new Error("Attachment save data provider not available");let l=this.getRetrySaveConfig(i),s=t||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Ai(()=>J(this,null,function*(){if(a?.config?.saveConfig?.url){let v=e.attachment,{file:u}=v,_=Oh(v,["file"]);return this.makeAttachmentConfigBasedRequest(a.config.saveConfig.url,a.config.saveConfig.headers,u,{attachment:_,event:e.eventType,metadata:e.attachment.metadata})}return a?.save?.({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",l);if(d?.statusCode!==200){this.loggingService.catch(d?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{error:d,request:e}});return}return this.analyticsService.trackEvent(Y.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,s,d){return J(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let v=this.getProvider(a);if(!this.attachmentDataProviderAvailable(a))throw new Error("Attachment delete data provider not available");let u=t?h({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0,_=this.getRetryDeleteConfig(a),I=i||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Ai(()=>{if(v?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE};return ji(v.config.deleteConfig.url,v.config.deleteConfig.headers,M,!1)}return v?.delete?.({attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",_);return A?.statusCode!==200?(this.loggingService.catch(A?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{error:A,attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:_.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!0})}catch(v){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",v);let u=this.getRetryDeleteConfig(a),_=i||at(),I=t?h({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0;return this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{error:v,attachmentId:e,metadata:I}}),{revertOnFailure:u.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e,t="default"){try{if(e){this.loggingService.log(`Setting attachment data provider for scope: ${t}`);let i=e.config,a=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],l=[];if(a.forEach(({method:s,configKey:d})=>{let v=i?.[d]?.url,u=s in e&&typeof e[s]=="function";!v&&!u&&l.push(s)}),l.length>0){let s=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(s);return}else this.providers.set(t,e),e.config?.saveRetryConfig&&this.retrySaveConfigs.set(t,e.config.saveRetryConfig),e.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(t,e.config.deleteRetryConfig)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(e){try{let t=e||"default";return this.providers.has(t)}catch(t){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",t),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ol=(()=>{let o=class o{constructor(e,t,i,a){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.attachmentResolverService=a,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.recorderAnnotationDataProvider$=new Se(null),this.recorderAnnotationById$=new Se({}),this.additionalFields=[],this.uploadChunks=!1,this.getRecorderAnnotationById=l=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[l]:void 0}catch(s){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",s);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(l=>{l&&(l.config?.resolveTimeout&&(this.resolveTimeout=l.config.resolveTimeout),l.config?.saveRetryConfig&&(this.retrySaveConfig=l.config.saveRetryConfig),l.config?.deleteRetryConfig&&(this.retryDeleteConfig=l.config.deleteRetryConfig),l.config?.getRetryConfig&&(this.retryGetConfig=l.config.getRetryConfig),l.config?.additionalFields&&(this.additionalFields=l.config.additionalFields||[]),this.uploadChunks=l.uploadChunks??!1)})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",l)}}getProvider(){try{let e=this.recorderAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",e)}}resolveRecorderAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:e}}),_(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],B=y(h({},e),{recorderAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.recorderAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.recorderAnnotationById$.next(h(h({},this.recorderAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let i=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=h(h({},l),e.recorderAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(e.recorderAnnotation),eventType:e.eventType}),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let a=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let l=this.recorderAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.recorderAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:v,event:Io.RECORDER_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:v,event:Io.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:I,recorderAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",t);return}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting recorder annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else e.storage&&this.attachmentResolverService.setAttachmentDataProvider(e.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",t)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st),X(zs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=s,this.commentResolverService=d,this.reactionResolverService=v,this.recorderResolverService=u,this.coreActionsService=_,this.functions=I,this.documentPaths$=new Se(null),this.docContext$=new Se(null),this.documentIds$=new Se([]),this.organizationConfig$=new Se(null),this.firestorePaths$=new Se(null),this.location$=new Se(null),this.excludedLocationIds$=new Se([]),this.organizationMetadata$=new Se(null),this.documentMetadata$=new Se(null),this.locationMetadata$=new Se(null),this.customerMetadata$=new Se(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Se({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Se({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new lt,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(VB(()=>Js(this.currentDebounceTime))).subscribe({next:A=>J(this,null,function*(){try{yield this.setDocumentIdImpl(A.documentId,A.clientOrganizationId,A.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:A=>{this.loggingService.catch("Error in setDocumentId subscription:",A),this.queueSize--}}),this.databaseService.getDb().pipe($e(A=>!!A),ut(1)).subscribe(A=>{A&&(this.db=A)}),this.configService.getApiKey$().subscribe(A=>{if(this.apiKey=A,this.apiKey){if(!this.isCustomDocId){let M=NN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>J(this,null,function*(){if(A&&(this.analyticsService.updateDefaultProperties({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&A?.organizationId&&this.documentPaths$.value?.organizationId!==A?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(M=>({id:M.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),A?.organizationId&&A?.clientOrganizationId)){let M={organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),yield this.updateOrganizationMetadata(M)}})),this.documentPaths$.subscribe(A=>{let M={documentId:A?.documentId,clientDocumentId:A?.clientDocumentId,folderId:A?.folderId,allDocuments:A?.allDocuments,veltFolderId:A?.veltFolderId};A?.organizationId&&(M.organizationId=A.organizationId,M.clientOrganizationId=A.clientOrganizationId),this.analyticsService.updateDefaultProperties(M),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(A=>{this.analyticsService.updateDefaultProperties({clientLocation:A?.location,locationId:A?.locationId})}),this.organizationMetadata$.subscribe(A=>{this.authService.setUserOrganization(A?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe($e(A=>!!A),ut(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(A){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}},A=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(A){this.loggingService.catch("Error in DocService constructor:",A)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(e=>({id:e.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setUsersService(e){try{this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService:",t)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=NN(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=NN(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(l){return J(this,arguments,function*({documentId:e,documentMetadata:t,options:i,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:a,payload:{documentId:e,documentMetadata:t,options:i}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:h({organizationId:t?.organizationId},i??{}),source:a})}catch(s){this.loggingService.catch("Error in DocService setDocument:",s)}})}shouldSetDocumentsAgain(e,t={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&e.length===this.pendingDocumentIds.length&&e.every(u=>this.pendingDocumentIds.includes(u.id))&&Mr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(v=>v.clientDocumentId),s=RN(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(v=>l.includes(v.id))||!Mr(s,t)||i!==a}catch(i){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",i),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let i=[];return e.forEach(a=>{let l=a.id,s=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:s,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return J(this,arguments,function*({documents:e,options:t,source:i="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(i){return J(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:yl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(s=>s.clientDocumentId);if(!l.includes(e.id)){let s=[...l.map(v=>({id:v})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:s,setClientDocumentMetadataMap:!0});this.documentIds$.next(d)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocContext(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let t=JSON.parse(JSON.stringify(e??null));this.docContext$.next(t)}catch(t){this.loggingService.catch("Error in setDocContext: ",t)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(kt(Jt))}getProcessedDocContext(){return The(this.getDocContext())}filterRelevantDocuments(a){return J(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:i=!1}){try{let l=this.authService.getUser();return!l||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,l),yield this.handlePermissionProvider(e,t,l),t=yield this.filterDocumentsByPermissions(e,t,l,i),t=t.slice(0,50)),t}catch(l){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",l),t}})}fetchDocumentsFromFolder(e,t,i){return J(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield bl({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(s=>{t.find(d=>d.clientDocumentId===s.id)||t.push({documentId:mi(s.id),clientDocumentId:s.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,i){try{let a=[];return e.organizationId&&e.organizationId!==i.clientOrganizationId&&a.push({userId:i.userId,resource:{id:e.organizationId,type:oa.ORGANIZATION,source:oo.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}}),t&&t.forEach(l=>{a.push({userId:i.userId,resource:{id:l.clientDocumentId,type:oa.DOCUMENT,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&BN({input:e?.context}).forEach(s=>{let d=JSON.stringify(s.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:s}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let i=e.data.filter(a=>a.type===oa.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(i??"nil"))),i?.length){let a=t.filter(s=>i.includes(s.resource.id)).map(s=>s.resource.context).filter(s=>!!s),l=whe({input:a});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(l??"nil"))),l?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(l??"nil"))),this.setDocContext(l))}}catch(i){this.loggingService.catch("Error in processAccessibleContexts:",i)}}handlePermissionProvider(e,t,i){return J(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil")));let a=this.buildPermissionRequests(e,t,i),l=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let s=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:oo.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(s??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(s,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return J(this,null,function*(){if(a)return t;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil"))),!(e?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(e,t,i);let s=this.currentValidationToken,d=[...t];return s&&this.validatePermissionsInBackground(e,t,i,s),d})}validateAndFilterPermissions(e,t,i){return J(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(v=>v.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),e?.folderId&&l?.[i.userId]?.folders?.[e?.folderId]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let s=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([v,u])=>{u?.errorCode===bo.PERMISSION_DENIED&&s.add(v)}),s.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...s].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...s],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(v=>!s.has(v.clientDocumentId));return d.length===0&&t.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),d}catch(a){return this.loggingService.catch("Error in validateAndFilterPermissions:",a),t}})}validatePermissionsInBackground(e,t,i,a){let l=e?.organizationId??i?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:l,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let d=[];Object.entries(s?.[i.userId]?.documents??{}).forEach(([v,u])=>{u?.errorCode===bo.PERMISSION_DENIED&&d.push(v)}),l&&s?.[i.userId]?.organization?.[l]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&s?.[i.userId]?.folders?.[e?.folderId]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0),d.length>0&&(this.loggingService.catch(`User does not have access to documents: ${d.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(d,i,a))}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,i){try{if(this.currentValidationToken!==i)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:e,userId:t.userId,timestamp:new Date().getTime()});let l=this.documentIds$.value||[],s=l.filter(d=>!e.includes(d.clientDocumentId));s.length!==l.length&&(s.length>0?this.setDocuments({documents:s.map(d=>({id:d.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:e,userId:t.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(a){this.loggingService.catch("Error in handleDeniedDocumentAccess:",a)}}addUserInfoToOrganization(l){return J(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let s=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield bl({data:h({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:s,userId:a??t?.userId??""})}catch(s){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",s)}})}setDocumentsImpl(l){return J(this,arguments,function*({documents:e,options:t,source:i,skipPermissionValidation:a=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(e??"nil")),"options:",JSON.parse(JSON.stringify(t??"nil"))),!this.shouldSetDocumentsAgain(e,RN(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let s=at();this.currentValidationToken=s;let d=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(d?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let v=this.authService.getUser();if(!v){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(_=>_.id),this.pendingOptions=RN(t)??{},this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let u=t?.organizationId??v?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:v}),d=yield this.filterRelevantDocuments({options:t,documentIds:d,skipPermissionValidation:a}),this.documentIds$.next(d),d?.length){let _=d[0]?.clientDocumentId;t?.rootDocumentId&&d.find(I=>I.clientDocumentId===t?.rootDocumentId)&&(_=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:_,clientOrganizationId:t?.organizationId,options:t})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(s){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return J(this,arguments,function*({documentId:e,clientOrganizationId:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENT_ID,source:i,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:i})}catch(l){this.loggingService.catch("Error in setDocumentId:",l);return}})}debounceSetDocuments(a){return J(this,arguments,function*({documentId:e,clientOrganizationId:t,options:i}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let l=i?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=l;let s=Date.now(),d=s-this.lastSetDocumentIdCallTime,v=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&v>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:i??void 0});return}catch(l){this.loggingService.catch("Error in debounceSetDocuments:",l)}})}setDocumentIdImpl(e,t,i){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let l=this.currentDocumentId;if(this.apiKey){let s=`${Qn(e)}`,d=i?.folderId,v=i?.folderId?Pr(i?.folderId):void 0,u=i?.locationId,_=i?.allDocuments,I=a?.organizationId?t?It(t):a?.organizationId:void 0,A=at(),M=Q1.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let B=at(),q=eS.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,moduleName:q,methodName:ri.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=at(),Ce=tS.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ae,moduleName:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:B,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:Ce})]),this.currentDocumentId!==s||this.documentPaths$.value?.organizationId!==I){this.loggingService.log("setting new docid"),this.currentDocumentId=s;let oe=new _L,fe=new RL;oe.clientDocumentId=e,fe.clientDocumentId=e,oe.folderId=d,fe.folderId=d,oe.locationId=u,fe.locationId=u,oe.allDocuments=_,fe.allDocuments=_,oe.veltFolderId=v,fe.veltFolderId=v,oe.documentId=s,fe.documentId=s,I&&(oe.organizationId=I,oe.clientOrganizationId=t??a?.clientOrganizationId,fe.organizationId=I,fe.clientOrganizationId=t??a?.clientOrganizationId);let Ie=`${this.apiKey}`,xe=`apiKey/${this.apiKey}`;I&&(Ie=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${oe.organizationId}`,xe=`${xe}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${oe.organizationId}`),fe.organization=`apiKey/${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,fe.document=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,oe.presence=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,oe.cursor=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,oe.comment=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,fe.comment=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,oe.multiThread=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,fe.multiThread=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,oe.tag=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,oe.area=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,fe.area=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AREA}`,oe.arrow=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,oe.selection=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,oe.audioHuddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,oe.huddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,oe.recorder=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,fe.recorder=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,oe.flock=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,oe.syncVideoPlayer=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,oe.liveState=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,oe.liveStateSingleEditorMode=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,oe.reaction=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,fe.reaction=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,oe.crdt=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,fe.crdt=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,oe.customerMetadata=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,oe.views=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,fe.notificationViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,fe.documentViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,fe.locationViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,oe.notifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,oe.metadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,oe.users=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,oe.documentIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.workspaceIam=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.groupContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,oe.globalContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,oe.logins=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,oe.userFeedback=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,oe.userReportBugs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,oe.userContactUs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,I&&(oe.organizationMetadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,oe.organizationIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.organizationGroups=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,oe.organizationNotifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,s&&(oe.organizationNotificationsWithDocumentId=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/`,oe.heartbeatByDocument=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${s}/`),oe.organizationNotificationsLastNotificationTimestamp=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,oe.organizationNotificationsUsers=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,oe.heartbeat=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),fe.organizationUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,fe.users=`${xe}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,fe.documentUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,fe.notificationDocs=`${xe}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,fe.notificationUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(oe),this.firestorePaths$.next(fe),oe?.clientOrganizationId&&oe?.organizationId&&!(oe?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&oe?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:oe?.organizationId,clientOrganizationId:oe?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),l&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:s,clientDocumentId:e}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:s,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:yl.UNSET_DOCUMENT_ID,source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let i=JSON.parse(JSON.stringify(this.documentIds$.value??[])),a=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),l=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:i,folderId:a,context:l}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(Y.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetDocumentImpl: ",i)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:yl.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",i)}}callPreDocumentIdChangeFunctions(e){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,i]of this.preDocumentIdChangeFunctions)try{yield i(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig()),this.db&&e?.organizationId){let t=e?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:t,field:"metadata"}}).then(i=>{i&&!i?.errorCode&&this.organizationMetadata$.next(y(h({},this.organizationMetadata$.value),{[t]:i}))}).catch(i=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)})}}catch(t){this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)}})}fetchDocumentMetadata(e){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentMetadata$.value;if(e=e.filter(a=>!i?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,l=[],s={organizationId:t?.clientOrganizationId,folderId:a},d=[],v=20;for(let _=0;_<e.length;_+=v)d.push(e.slice(_,_+v));d.forEach(_=>{let I=JSON.parse(JSON.stringify(s));I.documentIds=_.map(A=>A.clientDocumentId),l.push(this.fetchDocuments(I))});let u={};l.length>0&&(yield Promise.all(l).then(_=>{_?.forEach(I=>{I?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.setAllDocumentMetadata(h(h({},this.documentMetadata$.value),u))}).catch(_=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",_)}))}else i?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.setDocumentMetadata(a.documentId,a)}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,i=e?.folderId,a=e?.allDocuments,l=[],s={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],v=20;for(let _=0;_<t.length;_+=v)d.push(t.slice(_,_+v));d.forEach(_=>{let I=JSON.parse(JSON.stringify(s));I.documentIds=_.map(A=>A.clientDocumentId),l.push(this.fetchLocations(I))});let u=this.locationMetadata$.value??{};l.length>0&&Promise.all(l).then(_=>{_?.forEach(I=>{I?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=y(h({},u?.[A.metadata.documentId]??{}),{[A.location.id]:A}))})}),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}).catch(_=>{this.loggingService.catch("Error in fetchLocationMetadata: ",_)})}}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(Xn(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(ge(e=>e?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${Qn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${It(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(i){return J(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:yl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return J(this,arguments,function*({locations:e,options:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.SET_LOCATIONS,source:i,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(l){this.loggingService.catch("Error in setLocations: ",l)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(i=>{if(i&&typeof i=="object"){let a=!0;i?.version&&(!i?.version?.id||!i?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${i?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(i)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(i){return J(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:yl.SET_ROOT_LOCATION,source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(l=>l.location).filter(l=>String(l.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=y(h(h({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=h(h({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),l=[],s=[];this.location$.value?.location.id&&s.push(this.location$.value?.location.id),s=[...s,...Object.values(this.locations$.value).map(u=>u.location.id)].filter(u=>u!==void 0);let d;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(d=a.find(u=>u.id===t?.rootLocationId),!d)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(d){let u=Oi(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}}else{d||(d=a[0]);let u=Oi(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}let v=[];return a.slice(t?.appendLocation?0:1).forEach(u=>{if(u.id!==this.location$.value?.location.id){let _=h({},u),I=this.locations$.value;u?.id&&Object.keys(I).forEach(q=>{let ae=I[q];ae.location?.id===u.id&&(_=h(h({},ae.location),u),delete I?.[q])});let A=this.genarateLocationId(_),M={locationId:A,location:_};_.id&&l.push({locationId:A,location:_}),v.push(M);let B=y(h({},I),{[A]:M});this.locations$.next(B)}}),this.updateDocumentLocationMetadata(l),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:yl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),v}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.ADD_LOCATION,source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(i){this.loggingService.catch("Error in DocService addLocation:",i);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:yl.REMOVE_LOCATION,payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:yl.REMOVE_LOCATIONS,source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(i){this.loggingService.catch("Error in removeLocations: ",i)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(i=>{let a=this.genarateLocationId(i);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==i.id))),this.removeCustomLocation(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:yl.UNSET_LOCATION_IDS,source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(i=>{this.getLocation()?.location.id===i&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==i))),this.removeCustomLocationId(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:yl.REMOVE_LOCATIONS_SUCCESS,source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetLocationIds: ",i)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(e){return J(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,i=this.documentPaths$.value;if(this.db&&t&&i?.documentId){if(this.organizationMetadata$.value?.[t])return;let l=new wL;l.apiKey=this.configService?.getApiKey()??"",l.organizationId=t,l.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:t,documentId:i?.documentId??""}})),yield this.fetchOrganizationMetadata(e)}}catch(t){this.loggingService.catch("Error in updateOrganizationMetadata: ",t)}})}updateFolderMetadata(){return J(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let i={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield bl({methodName:"createFolder",data:{type:"createFolder",metadata:i},getSdkProxy:a,userId:this.authService.getUser()?.userId??""})}}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let i=t.map(a=>J(this,null,function*(){let l=new bL;this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(l=h(h({},this.clientDocumentMetadataMap[a.clientDocumentId]),l)),l.apiKey=this.configService?.getApiKey()??"",l.documentId=a.documentId,l.clientDocumentId=a.clientDocumentId,l.organizationId=e.organizationId,l.clientOrganizationId=e.clientOrganizationId,l.pageInfo=no();let s=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let v=!0,u=this.documentMetadata$.value?.[a.documentId];if(s&&d){let _=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));_?.clientDocumentId&&!_?.errorCode?_?.folderId&&(_?.folderId!==s||_?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),v=!1):_?.folderId===s?(s&&(l.folderId=s),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${s??""}`),v=!1):(s&&(l.folderId=s),d&&(l.veltFolderId=d))}if(u){let _={};Object.entries(l).forEach(([I,A])=>{_[I]=A}),Mr(_,u)&&(v=!1)}v&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(i),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(a=>a.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of i){let l=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});l?.errorCode&&(l={});let s=[];for(let d of e){let v=new xL;v.locationId=d?.locationId,v.veltLocationId=YK(d?.location?.id??""),v.location=d?.location,v.pageInfo=no(),v?.pageInfo?.deviceInfo&&delete v?.pageInfo?.deviceInfo;let u=y(h({},l),{[N.FIREBASE_PARTIAL_PATH_LOCATIONS]:y(h({},l[N.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:v})});this.commonDbService?.shouldUseFirestore()||s.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let _=this.locationMetadata$.value;if(_||(_={}),d?.location?.id){let I=_?.[a.documentId],A=I?.[d?.location?.id??""];_&&(I||(_[a.documentId]={}),A||(_[a.documentId][d?.location?.id??""]={}),_[a.documentId][d?.location?.id??""]=y(h({},A),{location:d?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}yield Promise.allSettled(s)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Oi(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let i=this.genarateLocationId(e),a=this.locations$.value;a[i]&&(delete a[i],this.locations$.next(h({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==e.id)))}catch(i){this.loggingService.catch("Error in DocService removeLocation:",i)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let i=this.locations$.value;Object.entries(i).forEach(([a,l])=>{l.location.id===e&&(delete i[a],this.locations$.next(h({},i)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e)))})}catch(i){this.loggingService.catch("Error in DocService removeCustomLocationId:",i)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let i=this.getLocations();Object.keys(i).forEach(a=>{let l=i[a];l.location?.id===e&&(t=l.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${N.ATTRIBUTES.VELT_LOCATION}]`),i=[];t.forEach(a=>{let l=a.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(l){let s=JSON.parse(l),d=this.genarateLocationId(s);i.push(d)}}),Object.keys(e).forEach(a=>{let l=e[a];i.includes(l.locationId)||delete e[a]}),this.locations$.next(h({},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(N.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${N.ATTRIBUTES.VELT_LOCATION}]`),t){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(i){let a=JSON.parse(i);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(i=>{if(i.getAttribute(N.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(i);a?.locationId&&(e[a.locationId]={element:i,location:a})}else if(i.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID)){let a=i.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID);if(a){let l=this.getLocationByClientLocationId(a);l?.locationId&&(e[l.locationId]={element:i,location:l});let s={id:a},d=this.genarateLocationId(s);e[a]={element:i,location:{locationId:d,location:s}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION)){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(i)return JSON.parse(i)}else if(t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID)){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID);if(i)return{id:i}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${N.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(N.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(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),kt(Jt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(e=>e||{}),kt(Jt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},t={},i=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(i&&a)Object.values(e).forEach(l=>{l?.documentId&&l?.veltFolderId===i&&(t[l.documentId]=l)});else{let l=this.documentIds$.value;if(l?.length)l.forEach(s=>{let d=e?.[s.documentId];d&&(t[s.documentId]=d)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(t[this.documentPaths$.value?.documentId]=s)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),kt(Jt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let i=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));i[e]=t,this.documentMetadata$.next(i)}catch(i){this.loggingService.catch("Error in DocService setDocumentMetadata:",i)}}setAllDocumentMetadata(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(e)}catch(t){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",t)}}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ge(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ge(e=>e||{}),kt(Jt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(kt(Jt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(i){this.loggingService.catch("Error in DocService getMetadataFromType:",i);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let i=this.documentPaths$.value;if(!i)return;let a=e||i.clientDocumentId,l=t||i.documentId,s=this.getDocumentMetadata(l);if(!s)return;let d=s?.folderId,v=s?.veltFolderId;return h(h({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),v?{veltFolderId:v}:{})}catch(i){this.loggingService.catch("Error in DocService getDefaultMetadata:",i);return}}getBaseMetadata(e,t){try{let i,a;t?.element?i=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(i=t.clientDocumentId),i&&(a=this.generateDocumentId(i));let l=this.getMetadataFromType(e,t),s=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||s||{};return d.sdkVersion=fa(),d}catch(i){return this.loggingService.catch("Error in DocService getBaseMetadata:",i),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(i){return this.loggingService.catch("Error in DocService getServerId:",i),null}}fetchDocuments(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return J(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,documents:a,folderId:l}=e;if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let s=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],v=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=s,u.clientOrganizationId=i,u.clientDocumentId=u.documentId;let _=mi(u.documentId);u.documentId=_,u.apiKey=this.configService.getApiKey()??void 0,(l||this.documentPaths$.value?.folderId)&&(u.folderId=l||this.documentPaths$.value?.folderId,u.veltFolderId=Pr(l||this.documentPaths$.value?.folderId||""));let I=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=v?.[_];M?v[_]=h(h({},M),u):v[_]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:_,organizationId:s,field:"metadata"}});if(A?.errorCode&&(A={}),A&&A.apiKey&&A.folderId&&l&&A.folderId!=u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists with different folderId: ${A.folderId}`);continue}if(A&&A.apiKey&&!A.folderId&&u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists, move this document to folder with REST API`);continue}I(),u&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:u?.documentId??""})&&d.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{organizationId:s,documentId:_}}))}yield Promise.all(d),this.setAllDocumentMetadata(v)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,locations:a,documentIds:l}=e;if((!l||l.length===0)&&(l=this.documentIds$.value.map(u=>u.clientDocumentId)??[],l.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let s=l.map(u=>mi(u)),d=[],v=this.locationMetadata$.value;v||(v={}),s.forEach(u=>{a.forEach(_=>{let I=this.location$.value;if(_?.id===I?.location?.id&&this.location$.next({locationId:I?.locationId,location:_}),_?.id){delete _?.metadata;let A=YK(_.id),M=v?.[u],B=M?.[_.id];v&&(M||(v[u]={}),B||(v[u][_.id]={}),v[u][_.id]=y(h({},B),{location:_})),_&&this.commonDbService&&d.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:_})),properties:{organizationId:Pa(i),documentId:u,id:A}}))}})}),yield Promise.all(d),Object.keys(v||{}).length>0&&this.locationMetadata$.next(v)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],l=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let s=Pr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}}),i&&(i=[i]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ft("metadata.veltParentFolderId","==",s)],folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}})}else i=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}});return{data:i,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(be(e=>e?this.documentPaths$.pipe(be(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ge(i=>i?.data?.docIamConfig??i?.data),kt((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?zr.RESTRICTED:zr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:zr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),zr.PUBLIC}}changeDocumentAccessType(e){return J(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(i?.errorCode)return;switch(delete i.documentAccessType,i.features||(i.features={}),i.features.all||(i.features.all={}),e){case zr.PUBLIC:i.features.all.restricted=!1;break;case zr.RESTRICTED:i.features.all.restricted=!0,i.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(i)),properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(h(h({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(st),X(qe),X($n),X(Be),X(Nt),X(k),X(rl),X(Gs),X(ol),X(tr),X(Do))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var An=(()=>{let o=class o{constructor(e,t,i,a,l){this.analyticsService=e,this.authService=t,this.coreActionsService=i,this.docService=a,this.loggingService=l,this.resolveOrganizationUsers=new Se(!0),this.resolveFolderUsers=new Se(!0),this.resolveDocumentUsers=new Se(!0),this.unresolvedUsers=new Se([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Bn,this.userDataProvider$=new Se(null),this.anonymousUserDataProvider$=new Se(null),this.userIdByEmailCache={},this.userById$=new Se({}),this.userByIdCalled$=new Se({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(d){this.loggingService.catch("Error in UsersService getUserById:",d);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe($e(s=>!!s),be(()=>this.getUnresolvedUsers$().pipe($e(s=>s.length>0),Qr(300),ut(20),be(s=>{let d=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:d,isCollection:!0,useQuery:!0,firestoreQuery:[_r(ft("user.userId","in",s.slice(0,20)))]}}).pipe(ge(v=>v?.data),ln(v=>{if(v&&typeof v=="object"){delete v.undefined,delete v.null;let u=Object.values(v??{});this.setUserByIds(u.map(I=>I.user));let _=s.filter(I=>!u.some(A=>A.user.userId===I));_.length!==s.length&&this.setUnresolvedUsers(_)}})):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)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in UsersService setContactService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(v){return J(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:s,moduleName:d}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let u=!1;if(i&&(u=this.isResolverForFeatureDisabled(i)),u)return{};{let _={},I=[],A={};if(e?.forEach(M=>{let B=this.getUserById(M);B?_[M]=B:this.userByIdCalled$.getValue()[M]?t&&I.push(M):(I.push(M),this.userByIdCalled$.next(y(h({},this.userByIdCalled$.getValue()),{[M]:!0})))}),I.length>0){let M=s||at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:gi.RESOLVE_USERS,source:"internal",payload:{userIds:I,organizationId:a,feature:i,forceResolve:t,skipUserCheck:l,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let B={};try{let q,ae=new Promise((Ce,oe)=>{q=setTimeout(()=>{oe(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});B=yield Promise.race([this.getUsersFromDB({userIds:I,organizationId:a,skipUserCheck:l}).finally(()=>{clearTimeout(q)}),ae]),this.analyticsService.trackEvent(Y.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:I}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{result:B,userIds:I,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(q){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",q,{userIds:I}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:q,userIds:I,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{I?.forEach(q=>{if(!B[q]){let ae=new Set([...this.getUnresolvedUsers(),q]);this.unresolvedUsers.next(Array.from(ae)),B[q]={userId:q,name:`User ${q}`}}})}Object.entries(B).forEach(([q,ae])=>{ae&&(_[q]=B?.[q],A[q]=B?.[q])})}return Object.keys(A).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(A)),this.userById$.next(h(h({},this.userById$.getValue()),A))),_}}catch(u){this.loggingService.catch("Error in UsersService resolveUsers:",u);let _=s||at();return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:u,userIds:e,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(e){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",e),[]}}setUnresolvedUsers(e){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(e)){let t=JSON.parse(JSON.stringify(e));this.unresolvedUsers.next(t)}}catch(t){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",t)}}getUsersFromDB(a){return J(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let l=this.userDataProvider$.getValue();if(l){if(l.config?.getConfig?.url){if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let u={organizationId:t,userIds:e},_=yield ji(l.config.getConfig.url,l.config.getConfig.headers,u,!0);return _.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${_.statusCode}. Message: ${_.message||"Unknown error"}`),{}):_.data??{}}let v=yield l.get(e);if(v&&typeof v=="object"&&"success"in v&&"statusCode"in v&&typeof v.success=="boolean"&&typeof v.statusCode=="number"){let u=v;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return v}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let s=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(s.flat());let d={};return s.forEach(v=>{v.forEach(u=>{u?.user?.userId&&(d[u.user.userId]=u.user)})}),d}catch(l){return this.loggingService.catch("Error in UsersService getUsersFromDB:",l),{}}})}getUsersFromDBWithBatching(a){return J(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let v=0;v<e.length;v+=30)l.push(e.slice(v,v+30));let s=l.map((v,u)=>J(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",v)],skipUserCheck:i}}))||[]}catch(_){return this.loggingService.catch(`Error in batch ${u+1}:`,_),[]}}));return yield Promise.all(s)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return J(this,arguments,function*({userIds:e,organizationId:t,resourceIds:i}){try{if(!e?.length||!i?.length)return[];let l=[];for(let M=0;M<e.length;M+=30)l.push(e.slice(M,M+30));let s=[];for(let M=0;M<i.length;M+=30)s.push(i.slice(M,M+30));let d=[],v=0,u=(M,B)=>J(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_r(ft("userId","in",M),ft("veltResourceId","in",B))]}}))??[])||[]}catch(q){return this.loggingService.catch(`Error in batch ${v+1}:`,q),[]}});for(let M of l)for(let B of s)d.push(u(M,B)),v++;return(yield Promise.all(d)).flat().filter((M,B,q)=>B===q.findIndex(ae=>ae.userId===M.userId&&ae.resourceId===M.resourceId))}catch(l){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",l),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(kt(Jt))}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(i=>{t[i.userId]=h(h({},t?.[i.userId]??{}),i)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let t=e.config?.getConfig?.url,i="get"in e&&typeof e.get=="function";if(!t&&!i){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}setAnonymousUserDataProvider(e){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in e)||typeof e.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",t)}}resolveUserIdsByEmail(i){return J(this,arguments,function*({emails:e,uniqueId:t}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!e?.length)return{};let a=this.anonymousUserDataProvider$.getValue();if(!a||typeof a.resolveUserIdsByEmail!="function")return{};let l=[...new Set(e.filter(oe=>!!oe))];if(l.length===0)return{};let s={},d=[];if(l.forEach(oe=>{let fe=this.userIdByEmailCache[oe];fe?s[oe]=fe:d.push(oe)}),d.length===0)return s;let v=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",_=this.docService.getDocumentPaths()?.folderId||"",I={organizationId:v,documentId:u,folderId:_,emails:d},A=t||at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:v,documentId:u,folderId:_}});let M=a.config?.resolveTimeout||this.resolveTimeout,B,q=new Promise((oe,fe)=>{B=setTimeout(()=>{fe(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},Ce=J(this,null,function*(){try{let oe=yield Ai(()=>a.resolveUserIdsByEmail(I),"resolveUserIdsByEmail",ae);return oe?.statusCode===200&&oe?.data?oe.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${oe?.statusCode}. Message: ${oe?.message||"Unknown error"}`),{})}finally{clearTimeout(B)}});try{let oe=yield Promise.race([Ce,q]);return Object.entries(oe).forEach(([fe,Ie])=>{Ie&&(this.userIdByEmailCache[fe]=Ie,s[fe]=Ie,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:Ie,name:fe,email:fe},currentUserId:this.authService.getUser()?.userId??""}).catch(xe=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",xe)}))}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:oe,emails:d}}),s}catch(oe){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",oe),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:oe,emails:d}}),s}}catch(a){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",a),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",e),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(st),X(qe),X(tr),X(ct),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var yp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return it.error("Error in isTestingDb:",r),!1}}};var cv=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=s,this.attachmentResolverService=d,this.coreActionsService=v,this.notificationActionTypeMap={[At.NEWLY_ADDED]:Io.COMMENT_ANNOTATION_ADD,[At.ADDED]:Io.COMMENT_ADD,[At.UPDATED]:Io.COMMENT_UPDATE,[At.DELETED]:Io.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let i of e){if(i?.from?.userId&&t.add(i?.from?.userId),i?.comments)for(let a of i?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let l of a?.to)l?.userId&&t.add(l?.userId);if(a?.taggedUserContacts)for(let l of a?.taggedUserContacts)l?.userId&&t.add(l?.userId)}if(i?.assignedTo?.userId&&t.add(i?.assignedTo?.userId),i?.resolvedByUserId&&t.add(i?.resolvedByUserId),i?.subscribedUsers)for(let a of Object.values(i?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(i?.unsubscribedUsers)for(let a of Object.values(i?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let l=this.usersService.getUserById(a?.userId);if(l)return h(h({},a),l)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let l=this.usersService.getUserById(a?.contact?.userId);l&&(a.contact=l,(l?.name||l?.email)&&(a.text=`@${l?.name||l?.email}`))}return a}));let i=t?.taggedUserContacts?.filter((a,l,s)=>s.findIndex(d=>d.text===a.text)===l)||[];i.sort((a,l)=>(l.text?.length||0)-(a.text?.length||0)),i.forEach(a=>{if(a?.text){let l=new RegExp(Qc(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(Qc(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(l,a.text),t.commentHtml=t.commentHtml?.replaceAll(l,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.resolvedByUserId){let t=this.usersService.getUserById(e?.resolvedByUserId);t&&(e.resolvedByUser=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=i)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=i)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.isCommentTextAvailable=!0)}),e?.viewedBy&&delete e.viewedBy,e?.unread!==void 0&&delete e.unread,e?.resolvedByUser!==void 0&&delete e.resolvedByUser,e?.comments&&e.comments.forEach(t=>{t?.reactionAnnotations&&delete t.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(l=>{let s=t?.comments?.[l?.commentId];if(s){l.commentHtml=s?.commentHtml,l.commentText=s?.commentText;let d=s?.attachments;i&&d&&l.attachments?.forEach(v=>{let u=v?.attachmentId;d?.[u]&&(v.name=d?.[u]?.name,v.url=d?.[u]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(l=>{t?.[l]&&(e[l]=t[l])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let i=e?.location?.id,a=e?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.location=l?.location),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",i),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let i=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",i),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new kc;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(s=>(s.isAttachmentResolverUsed=!0,delete s?.name,delete s?.url,s));a.attachments=l}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}resolveTaggedUserEmails(e){return J(this,null,function*(){try{let t=new Set;if(e.comments?.forEach(i=>{i.taggedUserContacts?.forEach(a=>{a?.contact?.email&&!a?.userId&&t.add(a.contact.email)}),i.to?.forEach(a=>{a?.email&&!a?.userId&&t.add(a.email)})}),t.size>0){let i=at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(t)}});let a=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(t),uniqueId:i});Object.keys(a).length>0&&e.comments?.forEach(l=>{l.taggedUserContacts?.forEach(s=>{if(s?.contact?.email&&!s?.userId){let d=a[s.contact.email];if(d){let v=s.text;if(v){let u=Qc(v),_=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(_,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(_,`{{${d}}}`))}s.userId=d,s.contact.userId=d,delete s.contact?.email,delete s.contact?.visibility,s.text=""}}}),l.to=l.to?.map(s=>{if(s?.email&&!s?.userId){let d=a[s.email];if(d)return delete s?.email,delete s?.visibility,y(h({},s),{userId:d})}return s})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return J(this,arguments,function*({data:e,actionType:t,commentId:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),e=yield this.resolveTaggedUserEmails(e),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let l=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),v;t&&(v=this.notificationActionTypeMap?.[t]);let u={},_=null,I=!1;if(e&&e.annotationId){let M=e.annotationId;if(u[M]=h(h(h(h({annotationId:M,metadata:ti(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,s?.length>0&&s.forEach(q=>{e?.[q]&&(u[M][q]=e[q],delete e[q])}),d?.length)for(let q of d)e?.[q]!==void 0&&(u[M][q]=JSON.parse(JSON.stringify(e[q])));e.comments?.forEach(q=>{if(q.commentId){let ae;l&&(ae={},q.attachments?.forEach(Ce=>{ae[Ce.attachmentId]={attachmentId:Ce.attachmentId,name:Ce.name,url:Ce.url}})),u[M].comments[q.commentId]=h(h(h(h(h(h({commentId:q.commentId},q?.commentHtml&&{commentHtml:q?.commentHtml}),q?.commentText&&{commentText:q?.commentText}),ae&&{attachments:ae}),q?.from&&{from:q?.from}),q?.to&&{to:q?.to}),q?.taggedUserContacts&&{taggedUserContacts:q?.taggedUserContacts})}}),I=this.isCommentsDataChanged(u[M],M);let B=new Br;Object.assign(B,e),B.comments=e.comments?.map(q=>this.stripCommentsFromAnnotationData({comment:q}))||[],_=B}let A=_?.comments?.find(M=>M.commentId===i);return A?.isDraft&&(v=_?.comments?.length&&_?.comments?.length>0?Io.COMMENT_ADD:Io.COMMENT_ANNOTATION_ADD),{strippedData:I&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:_,eventType:v}}catch(l){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",l),{strippedData:null,originalData:null}}})}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(i=>i?.userId?{userId:i.userId}:i)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(i=>i?.contact?.userId?y(h({},i),{contact:{userId:i.contact.userId}}):i));let t=e?.taggedUserContacts?.filter((i,a,l)=>l.findIndex(s=>s.text===i.text)===a)||[];t.sort((i,a)=>(a.text?.length||0)-(i.text?.length||0)),t.forEach(i=>{if(i?.text&&i?.contact?.userId){let a=new RegExp(Qc(i.text),"g");e.commentText=e.commentText?.replaceAll(a,l=>`{{${i.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,l=>`{{${i.userId}}}`)}}),t.forEach(i=>{i?.text&&i?.contact?.userId&&(i.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}getDeniedForYouUsers(t){return J(this,arguments,function*({extraData:e}){try{let i=Object.values(e?.annotationData?.subscribedUsers||{}).map(l=>l.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&i.length){let l=e?.metadata?.clientDocumentId,s=e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?e?.annotationData?.context?.access:null,d=[];i.forEach(_=>{if(d.push({userId:_,resource:{id:l,type:oa.DOCUMENT,source:oo.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:s?{access:s}:void 0}}),s){let I=JSON.stringify(s);d.push({userId:_,resource:{id:I,type:oa.CONTEXT,source:oo.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:s}}})}});let v=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.SET_NOTIFICATIONS,uniqueId:v,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:v,methodName:oo.SET_NOTIFICATIONS});u?.success&&u?.data?.length&&u.data.forEach(_=>{_.hasAccess||a.push(_.userId)})}return a}catch(i){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",i),[]}})}handleCommentEncryption(s){return J(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let d=DN(this.authService.getFirebaseConfig()?.firebaseOptions),v=Gr(this.functions,Wr({url:En.cloudFunction?.[d]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(i){i=this.notificationService?.processNotificationData(i),i.annotationData=e;let M=i?.targetAnnotationData?.commentId;if(M){let B=e?.comments?.find(q=>q?.commentId===M);B&&(i.targetAnnotationData=B)}try{let B=yield this.stripCommentAnnotationData({data:i.annotationData,actionType:i?.actionType??At.NEWLY_ADDED});B?.originalData&&(i.annotationData=this.formatCommentData(B.originalData)),i?.targetAnnotationData&&(i.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:i.targetAnnotationData})))}catch(B){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",B)}}let u=yp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_=yield this.getDeniedForYouUsers({extraData:i}),I={path:t??"",data:e??{},dbId:u??"",notificationData:i||void 0,notificationURL:En.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:fa(),deniedForYouUsers:_,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield fc(I,this.authService.getUser()?.userId??"");yield v({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(qe),X(Do),X(Nt),X(rl),X(zs),X(tr))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var NL=(()=>{let o=class o{constructor(e,t,i,a,l,s){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=s}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i?.from?.userId),i?.reactions?.length)for(let a of i?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return J(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=DN(this.authService.getFirebaseConfig()?.firebaseOptions),s=Gr(this.functions,Wr({url:En.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=yp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),v=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:fa()},_=yield fc(u,v);yield s({veltData:_})}catch(l){this.loggingService.catch("Error in handleReactionEncryption:",l)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",i),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let t={};if(e&&e.annotationId){let i=e.annotationId;if(t[i]=h({annotationId:i,metadata:ti(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[i],i))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(qe),X(Do),X(Nt),X(Gs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kp=(()=>{let o=class o{constructor(e,t,i,a){this.authService=e,this.loggingService=t,this.usersService=i,this.recorderAnnotationsResolverService=a}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId),i?.transcription?.from?.userId&&t.add(i?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?y(h({},e.transcription),{lastUpdated:t}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",i),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return J(this,null,function*(){try{return yield fc(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}stripRecorderAnnotationData({data:e,actionType:t}){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())return{strippedData:null,originalData:e};let i=e?.annotationId;if(!i)return{strippedData:null,originalData:e};let a=this.recorderAnnotationsResolverService.getAdditionalFields(),l={annotationId:i,metadata:ti(e.metadata??{})};if(e?.from&&(l.from=JSON.parse(JSON.stringify(e.from))),e?.transcription&&(l.transcription=JSON.parse(JSON.stringify(e.transcription))),e?.attachment!==void 0&&(l.attachment=e.attachment?JSON.parse(JSON.stringify(e.attachment)):null),e?.attachments?.length&&(l.attachments=JSON.parse(JSON.stringify(e.attachments))),e?.chunkUrls&&Object.keys(e.chunkUrls).length>0&&(l.chunkUrls=JSON.parse(JSON.stringify(e.chunkUrls))),e?.recordingEditVersions){let d={};for(let[v,u]of Object.entries(e.recordingEditVersions)){let _=Number(v),I={};u?.from&&(I.from=JSON.parse(JSON.stringify(u.from))),u?.attachment!==void 0&&(I.attachment=u.attachment?JSON.parse(JSON.stringify(u.attachment)):null),u?.attachments?.length&&(I.attachments=JSON.parse(JSON.stringify(u.attachments))),u?.transcription&&(I.transcription=JSON.parse(JSON.stringify(u.transcription))),Object.keys(I).length>0&&(d[_]=I)}Object.keys(d).length>0&&(l.recordingEditVersions=d)}if(e?.isUrlAvailable!==void 0&&(l.isUrlAvailable=e.isUrlAvailable),a?.length)for(let d of a)e?.[d]!==void 0&&(l[d]=JSON.parse(JSON.stringify(e[d])));if(e?.from?.userId&&(e.from={userId:e.from.userId}),delete e.transcription,e?.attachments?.length&&(e.attachments=e.attachments.map(d=>({attachmentId:d?.attachmentId,name:d?.name,bucketPath:d?.bucketPath}))),e.attachment=null,e?.chunkUrls&&(e.chunkUrls={}),e?.recordingEditVersions)for(let[,d]of Object.entries(e.recordingEditVersions))d?.from?.userId&&(d.from={userId:d.from.userId}),d.attachment=null,d?.attachments?.length&&(d.attachments=d.attachments.map(v=>({attachmentId:v?.attachmentId,name:v?.name,bucketPath:v?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let s;return t===Hl.ADDED?s=Io.RECORDER_ANNOTATION_ADD:t===Hl.UPDATED?s=Io.RECORDER_ANNOTATION_UPDATE:t===Hl.DELETED&&(s=Io.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:s}}catch(i){return this.loggingService.catch("Error in RecorderUtilsService stripRecorderAnnotationData:",i),{strippedData:null,originalData:e}}}mergeStrippedDataWithRecorderAnnotation(e){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e?.annotationId)return e;let t=this.recorderAnnotationsResolverService.getAnnotationById(e.annotationId);if(!t)return e;if(t.from&&(e.from=t.from),t.transcription&&(e.transcription=t.transcription),t.attachments?.length&&(e.attachments=t.attachments),t.attachment!==void 0&&(e.attachment=t.attachment),t.chunkUrls&&Object.keys(t.chunkUrls).length>0&&(e.chunkUrls=t.chunkUrls),t.recordingEditVersions&&e.recordingEditVersions)for(let[i,a]of Object.entries(t.recordingEditVersions)){let l=Number(i);e.recordingEditVersions[l]&&(a.from&&(e.recordingEditVersions[l].from=a.from),a.attachment!==void 0&&(e.recordingEditVersions[l].attachment=a.attachment),a.attachments?.length&&(e.recordingEditVersions[l].attachments=a.attachments),a.transcription&&(e.recordingEditVersions[l].transcription=a.transcription))}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeStrippedDataWithRecorderAnnotation:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(qe),X(k),X(An),X(ol))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xp=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Se(null),this.activityById$=new Se({}),this.fieldsToRemove=[],this.getActivityById=a=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ActivityResolverService getActivityById:",l);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove))})}catch(a){this.loggingService.catch("Error in ActivityResolverService constructor:",a)}}getProvider(){try{let e=this.activityDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ActivityResolverService getProvider:",e);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(e){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",e)}}resolveActivities(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:e}}),_(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.activityIds||[])],B=y(h({},e),{activityIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in ActivityResolverService resolveActivities:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.activityById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.activityById$.next(h(h({},this.activityById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let i=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=h(h({},l),e.activity);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(s?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(e.activity),event:e.event}),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ActivityResolverService saveActivity:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),se(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",e),this.fieldsToRemove}}setActivityDataProvider(e){try{if(e){this.loggingService.log("Setting activity data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.activityDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",t)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mS=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=s,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=v,this.activityResolverService=u}getActivityDisplayMessage(e){try{switch(e.featureType){case"comment":return this.getCommentDisplayMessage(e);case"recorder":return this.getRecorderDisplayMessage(e);case"reaction":return this.getReactionDisplayMessage(e);case"crdt":return this.getCrdtDisplayMessage(e);case"custom":return e.displayMessageTemplate&&e.displayMessageTemplateData?this.resolveTemplate(e.displayMessageTemplate,e.displayMessageTemplateData):"";default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",t),""}}resolveTemplate(e,t){try{return e.replace(/\{\{([\w.]+)\}\}/g,(i,a)=>{let l=a.split(".").reduce((s,d)=>{if(s!=null&&typeof s=="object")return s[d]},t);return l!=null?String(l):""})}catch(i){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",i),e}}buildActivityDataFromExtraData(e){try{let{feature:t,extraData:i}=e;if(!i?.actionType)return null;switch(t){case"comment":return this.buildCommentActivityData({commentAnnotation:i.annotationData,targetComment:i.targetAnnotationData,actionType:i.actionType,otherFields:i});case"recorder":return this.buildRecorderActivityData(i);case"reaction":return this.buildReactionActivityData(i);default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",t),null}}stripActivityPII(e){return J(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e));if(delete t.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:t};t.actionUser?.userId&&(t.actionUser={userId:t.actionUser.userId}),t.changes&&this.stripUsersFromChanges(t.changes),t.displayMessageTemplateData&&this.stripUsersFromTemplateData(t.displayMessageTemplateData);let i=this.extractCommentChangesForResolver(t),a=this.extractFeatureEntityDataForResolver(t);yield this.stripFeatureSpecificPII(t);let l=this.extractActivityResolverData(t);return i&&(l?l.changes=h(h({},l.changes),i.changes):l=i),a&&(l?(a.entityData!==void 0&&(l.entityData=a.entityData),a.entityTargetData!==void 0&&(l.entityTargetData=a.entityTargetData)):l=a),l&&(t.isActivityResolverUsed=!0),{strippedActivity:t,activityResolverData:l}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",t),{strippedActivity:e}}})}mergeActivityWithUser(e){try{if(!this.usersService.userDataProviderAvailable())return e;if(e=JSON.parse(JSON.stringify(e)),e.actionUser?.userId){let t=this.usersService.getUserById(e.actionUser.userId);t&&(e.actionUser=t)}return e.changes&&this.rehydrateUsersInChanges(e.changes),e.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(e.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(e),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",t),e}}mergeActivityWithFeatureData(e){try{switch(e.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(e);case"reaction":return this.mergeActivityWithReactionData(e);case"recorder":return this.mergeActivityWithRecorderData(e);default:return e}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",t),e}}getUserIdsToResolveFromActivities(e){try{let t=new Set;for(let i of e){if(i.actionUser?.userId&&t.add(i.actionUser.userId),i.changes)for(let a of Object.values(i.changes))a&&(this.extractUserIdFromValue(a.from,t),this.extractUserIdFromValue(a.to,t));if(i.displayMessageTemplateData)for(let a of Object.values(i.displayMessageTemplateData))this.extractUserIdFromValue(a,t);this.extractFeatureSpecificUserIds(i,t)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",t),[]}}getEntityIdsToResolveFromActivities(e,t){try{let i=new Set;for(let a of e)if(!(t&&a.featureType!==t))switch(a.featureType){case"comment":case"reaction":case"recorder":a.targetEntityId&&i.add(a.targetEntityId);break}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",i),[]}}stripFeatureSpecificPII(e){return J(this,null,function*(){try{switch(e.featureType){case"comment":yield this.stripCommentPII(e);break;case"reaction":this.stripReactionPII(e);break;case"recorder":this.stripRecorderPII(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",t)}})}extractActivityResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let t={id:e.id},i=!1;if(e.featureType==="custom"){let a=this.activityResolverService.getFieldsToRemove();for(let l of a)l in e&&e[l]!==void 0&&(t[l]=e[l],delete e[l],i=!0)}return e.metadata&&(t.metadata=ti(e.metadata)),i?t:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",t);return}}extractCommentChangesForResolver(e){try{return!this.activityResolverService.activityDataProviderAvailable()||e.featureType!=="comment"||!e.changes?.commentText?void 0:{id:e.id,changes:{commentText:e.changes.commentText},metadata:e.metadata?ti(e.metadata):void 0}}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",t);return}}extractFeatureEntityDataForResolver(e){try{if(!this.activityResolverService.activityDataProviderAvailable()||!e.entityData)return;let t=e.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),i=e.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!t&&!i)return;let a={id:e.id,metadata:e.metadata?ti(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let s=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}if(i){let s=this.reactionUtilsService.stripReactionAnnotationData(l);if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}return a.entityData?a:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",t);return}}mergeActivityWithResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return e;let t=this.activityResolverService.getActivityById(e.id);if(!t)return e;t.changes&&(e.changes||(e.changes={}),Object.assign(e.changes,t.changes)),t.entityData!==void 0&&(e.entityData=t.entityData),t.entityTargetData!==void 0&&(e.entityTargetData=t.entityTargetData),t.displayMessageTemplateData&&(e.displayMessageTemplateData||(e.displayMessageTemplateData={}),Object.assign(e.displayMessageTemplateData,t.displayMessageTemplateData));let i=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[a,l]of Object.entries(t))!i.has(a)&&l!==void 0&&(e[a]=l);return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",t),e}}rehydrateFeatureSpecificUserData(e){try{switch(e.featureType){case"comment":this.rehydrateCommentUserData(e);break;case"reaction":this.rehydrateReactionUserData(e);break;case"recorder":this.rehydrateRecorderUserData(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",t)}}getCommentDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case qr.ANNOTATION_ADD:return`${t} added a comment`;case qr.COMMENT_ADD:return`${t} replied to a comment`;case qr.COMMENT_UPDATE:return`${t} edited a comment`;case qr.COMMENT_DELETE:return`${t} deleted a comment`;case qr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case qr.STATUS_CHANGE:{let i=e.changes?.status,a=i?.from?.name,l=i?.to?.name;return a&&l?`${t} changed status from ${a} to ${l}`:`${t} changed the status`}case qr.PRIORITY_CHANGE:{let i=e.changes?.priority,a=i?.to;if(!a)return`${t} removed the priority`;let l=typeof a=="object"?a?.name:String(a),s=i?.from,d=s&&typeof s=="object"?s?.name:s?String(s):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case qr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case qr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case qr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case qr.APPROVE:return`${t} approved the comment`;case qr.ACCEPT:return`${t} accepted a suggestion`;case qr.REJECT:return`${t} rejected a suggestion`;case qr.REACTION_ADD:return`${t} reacted to a comment`;case qr.REACTION_DELETE:return`${t} removed a reaction`;case qr.SUBSCRIBE:return`${t} subscribed to the thread`;case qr.UNSUBSCRIBE:return`${t} unsubscribed from the thread`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",t),""}}getRecorderDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case mO.RECORDING_ADD:return`${t} added a recording`;case mO.RECORDING_DELETE:return`${t} deleted a recording`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",t),""}}getReactionDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case vO.REACTION_ADD:return`${t} added a reaction`;case vO.REACTION_DELETE:return`${t} removed a reaction`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",t),""}}getCrdtDisplayMessage(e){try{let t=e.actionUser?.name??"Someone",a=e.entityData?.editCount??0,l=e.targetEntityId??"unknown";return`${t} made ${a} edit${a!==1?"s":""} to editor ${l}`}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",t),""}}stripCommentPII(e){return J(this,null,function*(){try{let t=yield this.commentUtilsService.stripCommentAnnotationData({data:e.entityData,actionType:e.eventType??At.NEWLY_ADDED});t?.originalData&&(e.entityData=this.commentUtilsService.formatCommentData(t.originalData)),e.entityTargetData&&(e.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:e.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&e.changes?.commentText&&delete e.changes.commentText}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",t)}})}rehydrateCommentUserData(e){try{e.entityData&&this.commentUtilsService.mergeCommentWithUser(e.entityData),e.entityTargetData&&(this.rehydrateUserInObject(e.entityTargetData,"from"),this.rehydrateUsersInArray(e.entityTargetData,"to"),this.rehydrateUsersInArray(e.entityTargetData,"taggedUserContacts"))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",t)}}stripReactionPII(e){try{if(!e.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(e.entityData),e.entityData=this.reactionUtilsService.formatReactionData(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",t)}}rehydrateReactionUserData(e){try{if(!e.entityData)return;this.reactionUtilsService.mergeReactionWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",t)}}stripRecorderPII(e){try{if(!e.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.recorderUtilsService.stripRecorderAnnotationData({data:e.entityData});return}let t=e.entityData;if(this.usersService.userDataProviderAvailable()){t.from&&typeof t.from=="object"&&"userId"in t.from&&(t.from={userId:t.from.userId});let i=t.transcription;i?.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",t)}}rehydrateRecorderUserData(e){try{if(!e.entityData)return;this.recorderUtilsService.mergeRecorderWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",t)}}mergeActivityWithCommentAnnotationData(e){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e.targetEntityId);if(!t)return e;let i=e.entityData?.comments;if(Array.isArray(i))for(let a of i){let l=a?.commentId;if(l==null)continue;let s=t.comments?.[String(l)];s&&(s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml))}if(e.targetSubEntityId&&e.entityTargetData){let a=t.comments?.[e.targetSubEntityId];if(a){let l=e.entityTargetData;a.commentText&&(l.commentText=a.commentText),a.commentHtml&&(l.commentHtml=a.commentHtml)}}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",t),e}}mergeActivityWithReactionData(e){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",t),e}}mergeActivityWithRecorderData(e){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",t),e}}buildCommentActivityData(e){try{let{commentAnnotation:t,targetComment:i,actionType:a,otherFields:l}=e,s=t,d=i,v=a===At.DELETED&&l?.isAnnotationDelete?qr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!v)return null;let u=s?.annotationId;if(!u)return null;let _=d?.commentId,I=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:v,targetEntityId:u,eventType:a,targetSubEntityId:_??null,changes:Object.keys(I).length>0?I:void 0,entityData:t,entityTargetData:i??void 0}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",t),null}}mapCommentStatusToActionType(e){try{switch(e){case At.NEWLY_ADDED:return qr.ANNOTATION_ADD;case At.ADDED:return qr.COMMENT_ADD;case At.UPDATED:return qr.COMMENT_UPDATE;case At.DELETED:return qr.COMMENT_DELETE;case At.STATUS_CHANGED:return qr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return qr.PRIORITY_CHANGE;case At.ASSIGNED:return qr.ASSIGN;case At.ACCESS_MODE_CHANGED:return qr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return qr.CUSTOM_LIST_CHANGE;case At.APPROVED:return qr.APPROVE;case At.ACCEPTED:return qr.ACCEPT;case At.REJECTED:return qr.REJECT;case At.REACTION_ADDED:return qr.REACTION_ADD;case At.REACTION_DELETED:return qr.REACTION_DELETE;case At.SUBSCRIBED:return qr.SUBSCRIBE;case At.UNSUBSCRIBED:return qr.UNSUBSCRIBE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",t),null}}buildRecorderActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapRecorderStatusToActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"recorder",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",t),null}}mapRecorderStatusToActionType(e){try{switch(e){case Hl.ADDED:return mO.RECORDING_ADD;case Hl.DELETED:return mO.RECORDING_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",t),null}}buildReactionActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapReactionActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"reaction",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",t),null}}mapReactionActionType(e){try{switch(e){case"add":return vO.REACTION_ADD;case"delete":return vO.REACTION_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",t),null}}buildCommentChanges(e,t,i){try{let a={};switch(e){case At.NEWLY_ADDED:case At.ADDED:a.commentText={from:null,to:t?.commentText??null};break;case At.UPDATED:a.commentText={from:i?.oldCommentText??null,to:t?.commentText??null};break;case At.DELETED:a.commentText={from:t?.commentText??null,to:null};break;case At.STATUS_CHANGED:a.status={from:i?.oldStatus??null,to:i?.newStatus??null};break;case At.PRIORITY_CHANGED:a.priority={from:i?.oldPriority??null,to:i?.newPriority??null};break;case At.ASSIGNED:{a.assignedTo={from:i?.oldAssignedTo??null,to:i?.newAssignedTo??null};break}case At.ACCESS_MODE_CHANGED:a.accessMode={from:i?.oldAccessMode??null,to:i?.newAccessMode??null};break;case At.CUSTOM_LIST_CHANGED:a.customList={from:i?.oldCustomList??null,to:i?.newCustomList??null};break}return a}catch(a){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",a),{}}}extractFeatureSpecificUserIds(e,t){try{switch(e.featureType){case"comment":this.extractCommentActivityUserIds(e,t);break;case"reaction":this.extractReactionActivityUserIds(e,t);break;case"recorder":this.extractRecorderActivityUserIds(e,t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",i)}}extractCommentActivityUserIds(e,t){try{if(e.entityData){let i=this.commentUtilsService.getUserIdsToResolveFromComments([e.entityData]);for(let a of i)t.add(a)}if(e.entityTargetData){let i=e.entityTargetData;if(this.extractUserIdFromValue(i.from,t),Array.isArray(i.to))for(let a of i.to)this.extractUserIdFromValue(a,t);if(Array.isArray(i.taggedUserContacts))for(let a of i.taggedUserContacts)this.extractUserIdFromValue(a,t)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",i)}}extractReactionActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.reactionUtilsService.getUserIdsToResolveFromReactions([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",i)}}extractRecorderActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.recorderUtilsService.getUserIdsToResolveFromRecorders([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",i)}}stripUsersFromChanges(e){try{for(let t of Object.keys(e)){let i=e[t];i&&(i.from=this.stripUserIfPresent(i.from),i.to=this.stripUserIfPresent(i.to))}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",t)}}stripUserIfPresent(e){try{return e&&typeof e=="object"&&"userId"in e?{userId:e.userId}:e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",t),e}}stripUsersFromTemplateData(e){try{for(let t of Object.keys(e)){let i=e[t];i&&typeof i=="object"&&"userId"in i&&(e[t]={userId:i.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",t)}}rehydrateUsersInChanges(e){try{for(let t of Object.values(e))t&&(t.from=this.rehydrateIfUser(t.from),t.to=this.rehydrateIfUser(t.to))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",t)}}rehydrateIfUser(e){try{if(e&&typeof e=="object"&&"userId"in e){let t=e.userId;return this.usersService.getUserById(t)??e}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",t),e}}rehydrateUsersInTemplateData(e){try{for(let t of Object.keys(e))e[t]=this.rehydrateIfUser(e[t])}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",t)}}rehydrateUserInObject(e,t){try{let i=e[t];if(i&&typeof i=="object"&&"userId"in i){let a=i.userId,l=this.usersService.getUserById(a);l&&(e[t]=l)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",i)}}rehydrateUsersInArray(e,t){try{let i=e[t];Array.isArray(i)&&(e[t]=i.map(a=>this.rehydrateIfUser(a)))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",i)}}extractUserIdFromValue(e,t){try{if(e&&typeof e=="object"&&"userId"in e){let i=e.userId;typeof i=="string"&&t.add(i)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",i)}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(cv),X(NL),X(kp),X(rl),X(Gs),X(ol),X(xp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dv=class{constructor({apiKey:o,documentId:r,organizationId:e,folderId:t,veltFolderId:i,clientDocumentId:a,clientOrganizationId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.folderId=t,this.veltFolderId=i,this.clientDocumentId=a,this.clientOrganizationId=l,a&&(this.documentId=mi(a)),l&&(this.organizationId=Pa(l)),t&&(this.folderId=t,this.veltFolderId=Pr(t)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${N.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${o}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${o}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${N.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 LL=class{constructor({apiKey:o,documentId:r,organizationId:e,clientDocumentId:t,clientOrganizationId:i,folderId:a,veltFolderId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.veltFolderId=l,t&&(this.documentId=mi(t)),i&&(this.organizationId=Pa(i)),a&&(this.folderId=a,this.veltFolderId=Pr(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.paths.activities=`${o}/${N.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.organizationId&&(o=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${o}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${o}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${N.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${o}/${N.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${N.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Rbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Nbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let i of e)i?.user?.userId&&t.add(i?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let i=t;e?.user&&typeof e.user=="object"&&(i=h(h({},i),e.user)),e=y(h({},e),{user:i})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var UL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return J(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),i=at(),a=xc.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USERS_FROM_HUDDLE_MESSAGES,moduleName:a,source:"internal",payload:{userIds:t}});let l=yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a});for(let s of e)s?.from?.userId&&l[s.from.userId]&&(s.from=l[s.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var VL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let i of e)i?.updatedBy?.userId&&t.add(i?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(e){try{let t=new Set;return e?.editor?.userId&&t.add(e?.editor?.userId),e?.requestEditorAccess?.user?.userId&&t.add(e?.requestEditorAccess?.user?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return J(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=at(),a=xc.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:a,source:"internal",payload:{userIds:t}}),yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a}),this.mergeSingleEditorLiveStateDataWithUser(e)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),e}})}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Bbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mv=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Se(null),this.notificationById$=new Se({}),this.inFlightRequests=new Map,this.getNotificationById=a=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",l);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in NotificationResolverService constructor:",a)}}getProvider(){try{let e=this.notificationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in NotificationResolverService getProvider:",e);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(e){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",e)}}resolveNotifications(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let Ie=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:e}}),_(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=this.notificationById$.getValue()||{},B=[...new Set(e.notificationIds||[])],q=[],ae=[],Ce=[];for(let Ie of B)M[Ie]||(this.inFlightRequests.has(Ie)?(q.push(this.inFlightRequests.get(Ie)),ae.push(Ie)):Ce.push(Ie));let oe=y(h({},e),{notificationIds:Ce});J(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),Ce.length>0){let Ie=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:oe}});let xe,ye=new Promise(Re=>{xe=Re});for(let Re of Ce)this.inFlightRequests.set(Re,ye.then(Ue=>Ue?.[Re]));let Oe=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,oe,!0):I?.get?.(oe)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Re=>s?{}:(v(),Re&&Re.statusCode!==200?(this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Re,request:oe}}),this.loggingService.catch(Re?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Re?.data)).catch(Re=>{throw v(),Re});try{A=(yield Oe)||{},xe(A);for(let Ue of Ce)this.inFlightRequests.delete(Ue);this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:Ce});let Re={};Object.entries(A).forEach(([Ue,ze])=>{let Ge=this.notificationById$.value?.[Ue];Ge?Ge&&JSON.stringify(Ge)!==JSON.stringify(ze)&&(Re[Ue]=ze):Re[Ue]=ze}),Object.keys(Re).length>0&&this.notificationById$.next(h(h({},this.notificationById$.getValue()),Re)),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Re,request:oe}}),u(Re)}catch(Re){xe({});for(let ze of Ce)this.inFlightRequests.delete(ze);let Ue=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ue,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Re,request:oe}}),s||_(Re),u(A)}}else v(),u({})}catch(Ie){v();let xe=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ie,request:oe}}),_(Ie)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let a=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let l=i||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let s=this.notificationById$.getValue(),d=h({},s);delete d?.[e],this.notificationById$._value=d;let v={notificationId:e,organizationId:t},u=yield Ai(()=>a?.config?.deleteConfig?.url?ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,v,!1):a?.delete?.(v)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=s),this.loggingService.catch(u?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:u,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:e}),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",a);let l=i||at();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:a,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),se(void 0)}}setNotificationDataProvider(e){try{if(e){this.loggingService.log("Setting notification data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.notificationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",t)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jL=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=s,this.notificationResolverService=d}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let i of e){let{notification:a}=i;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let l=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let s of l)t.add(s)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),i=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[i]?.commentText,l=t?.comments?.[i]?.commentHtml;return a&&l&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=l),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let i=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.notification.notificationSourceData.location=l?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=l?.location)),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",i),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let i=this.usersService.getUserById(t?.actionUser?.userId);i&&(t.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);i&&(t.displayHeadlineMessageTemplateData.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);i&&(t.displayHeadlineMessageTemplateData.recipientUser=i)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,t);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",i),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(i=>{i?.notification?.targetAnnotationId&&i?.raw?.notificationSource==="comment"&&t.push(i.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return J(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let i="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield fc(e,i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",i),e}})}getCustomNotificationIdsToResolve(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let t=new Set,i=Array.isArray(e)?e:Object.values(e||{});for(let a of i)if(a?.raw?.notificationSource==="custom"){let l=a?.notification?.id||a?.notificationId;l&&t.add(l)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",t),[]}}mergeResolvedNotificationData(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||e?.raw?.notificationSource!=="custom")return e;let t=e?.notification?.id||e?.notificationId;if(!t)return e;let i=this.notificationResolverService.getNotificationById(t);if(!i)return e;let a=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let l of a)i[l]!==void 0&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]));return Object.keys(i).forEach(l=>{!a.includes(l)&&l!=="notificationId"&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]))}),e.notification&&(e.notification.isNotificationResolverUsed=!0),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(cv),X(kp),X(k),X(An),X(qe),X(rl),X(mv))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $be=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let i of e)i?.user?.userId&&t.add(i.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i.from.userId),i?.to?.length)for(let a of i.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let i=this.usersService.getUserById(t?.userId);i&&(t=i)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var od=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I,A,M,B,q,ae,Ce,oe,fe,Ie,xe,ye,Oe,Re){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=s,this.cursorUtilsService=d,this.huddleUtilsService=v,this.liveStateUtilsService=u,this.loggingService=_,this.multiThreadUtilsService=I,this.notificationUtilsService=A,this.presenceUtilsService=M,this.reactionUtilsService=B,this.recorderUtilsService=q,this.selectionUtilsService=ae,this.tagUtilsService=Ce,this.usersService=oe,this.docService=fe,this.commentAnnotationsResolverService=Ie,this.reactionAnnotationsResolverService=xe,this.recorderAnnotationsResolverService=ye,this.notificationResolverService=Oe,this.activityResolverService=Re}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",i),null}}getFirestorePath({feature:e,properties:t,documentPaths:i,apiKey:a}){try{if(!a)return;let{documentId:l,organizationId:s,folderId:d}=t;s||(s=i?.organizationId);let v=new LL({apiKey:a,documentId:l?`${l}`:"",organizationId:s?`${s}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&v?.userConfig?`${v?.userConfig}/${t?.userId}${t?.documentId?`/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return v?.permissionsUsers?`${v?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&v?.comment?`${v?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&v?.comment?`${v?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&v?.multiThread?`${v?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&v?.multiThread?`${v?.multiThread}`:void 0;case"crdt":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return v?.lastNotificationTimestamp?`${v?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&v?.lastNotificationTimestamp?`${v?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&v?.activities?`${v?.activities}/${t?.id}`:void 0;case"allActivities":return v?.activities?`${v?.activities}`:void 0;case"allLastActivityTimestamp":return v?.lastActivityTimestamp?`${v?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&v?.lastActivityTimestamp?`${v?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&v?.area?`${v?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&v?.area?`${v?.area}`:void 0;case"allDocuments":return v?.document?`${v?.document}`:void 0;case"allLocations":return v?.location?`${v?.location}`:void 0;case"allFolders":return v?.folder?`${v?.folder}`:void 0;case"folder":return v?.folder&&t.folderId?`${v?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&v?.documentUsers?`${v?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&v?.reaction?`${v?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&v?.reaction?`${v?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&v?.recorder?`${v?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&v?.document?`${v?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return v?.organization?`${v?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&v?.document?`${v?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&v?.folder?`${v?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&v?.location&&t?.id?`${v?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&v?.documentUsers?`${v?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return v?.users?`${v?.users}`:void 0;case"allFolderUsers":return v?.users?`${v?.users}`:void 0;case"allOrganizationGroups":return v?.organizationGroups?`${v?.organizationGroups}`:void 0;case"allOrganizationUsers":return v?.users?`${v?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&v?.notificationViews?`${v?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&v?.documentViews?`${v?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&v?.documentViews?`${v?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&v?.locationViews?`${v?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&v?.locationViews?`${v?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&v?.docNotification?`${v?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&v?.docNotification?`${v?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&v?.notificationUsers?`${v?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&v?.notificationUsers?`${v?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(l){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",l);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return N.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return N.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return N.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return N.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return N.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return N.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return N.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return N.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:i,apiKey:a,useFirestore:l}){try{if(!a)return;let{documentId:s,organizationId:d}=t;d||(d=i?.organizationId);let v=new dv({apiKey:a,documentId:s?`${s}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&v?.userConfig?`${v?.userConfig}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&v?.comment?`${v?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&v?.globalContacts?`${v?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&v?.globalContacts?`${v?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&v?.groupContacts?`${v?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&v?.groupContacts?`${v?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&v?.logins?`${v?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&v?.logins?`${v?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&v?.logins?`${v?.logins}${t?.userId}`:void 0;case"customerMetadata":return v?.customerMetadata?`${v?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&v?.arrow?`${v?.arrow}`:void 0;case"arrow":return t?.documentId&&v?.arrow&&t.id?`${v?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&v?.cursor?`${v?.cursor}`:void 0;case"cursor":return t?.documentId&&v?.cursor&&t.id?`${v?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&v?.flock&&t.id?`${v?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&v?.flock&&t.id?`${v?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&v?.huddle?`${v?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&v?.huddle?`${v?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&v?.huddle?`${v?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&v?.huddle?`${v?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&v?.liveState?`${v?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&v?.liveState?`${v?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&v?.liveState&&t?.id?`${v?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&v?.liveStateSingleEditorMode?`${v?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&v?.liveState?`${v?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&v?.liveState?`${v?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&v?.liveState&&t?.id?`${v?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&v?.presence&&t?.userId?`${v?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&v?.presence?`${v?.presence}`:void 0;case"workspaceIam":return v?.workspaceIam?`${v?.workspaceIam}`:void 0;case"selection":return t?.documentId&&v?.selection&&t?.userId?`${v?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&v?.selection?`${v?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&v?.syncVideoPlayer?`${v?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&v?.tag?`${v?.tag}`:void 0;case"tag":return t?.documentId&&v?.tag&&t?.id?`${v?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&v?.userContactUs?`${v?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&v?.userFeedback?`${v?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&v?.userReportBugs?`${v?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&v?.comment?`${v?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&v?.multiThread?`${v?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&v?.crdt?`${v?.crdt}`:void 0;case"crdtData":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&v?.crdt&&t?.id&&t?.versionId?`${v?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&v?.crdt&&t?.id&&t?.messageId?`${v?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&v?.multiThread?`${v?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&v?.organizationNotificationsLastNotificationTimestamp?`${v?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&v?.organizationNotificationsLastNotificationTimestamp?`${v?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&v?.documentIam?`${v?.documentIam}`:void 0;case"allDocuments":return!l&&v?.docs&&t?.documentId?`${v?.docs}/${t?.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&v?.area?`${v?.area}`:void 0;case"area":return!l&&t?.id&&v?.area?`${v?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&v?.folder?`${v?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&v?.documentIam?`${v?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&v?.documentIam?`${v?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&v?.documentIam?`${v?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&v?.organizationGroups?`${v?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&v?.organizationIam?`${v?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&v?.reaction?`${v?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&v?.reaction?`${v?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&v?.recorder?`${v?.recorder}`:void 0;case"organizationMetadata":return!l&&v?.organizationMetadata?`${v?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&v?.heartbeat?`${v?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return v?.heartbeat?`${v?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&v?.heartbeatByDocument?`${v?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return v?.heartbeatByDocument?`${v?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&v?.documentIam?`${v?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&v?.metadata?`${v?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&v?.views?`${v?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&v?.views?`${v?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&v?.views?`${v?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&v?.views?`${v?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&v?.views?`${v?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&v?.views?`${v?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&v?.views?`${v?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&v?.views?`${v?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&v?.views?`${v?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&v?.organizationNotificationsWithDocumentId?`${v?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&v?.organizationNotificationsWithDocumentId?`${v?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&v?.organizationNotificationsUsers?`${v?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&v?.organizationNotificationsUsers?`${v?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",s);return}}resolveAnnotations(i){return J(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=at(),l=Q1.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:l,source:"internal",payload:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let a=at(),l=eS.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:l,source:"internal",payload:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let a=at(),l=tS.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:l,source:"internal",payload:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(_){return J(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:s=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:v=!1,shouldRecorderResolverAwait:u=!1}){try{if(this.usersService.userDataProviderAvailable()){let I=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(I=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}case"allActivities":{t&&typeof t=="object"&&(I=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(t)?t:Object.values(t)));break}default:I=[]}if(I?.length){let A=at(),M=xc.GET_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.FORMAT_RESPONSE,source:"internal",moduleName:M,payload:{userIds:I,feature:e,forceResolve:a}}),i?yield this.usersService.resolveUsers({userIds:I,forceResolve:a,feature:e,uniqueId:A,moduleName:M}):this.usersService.resolveUsers({userIds:I,forceResolve:a,feature:e,uniqueId:A,moduleName:M})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let I=[];switch(e){case"allDocNotifications":case"allUserNotifications":{t&&typeof t=="object"&&(I=this.notificationUtilsService.getCustomNotificationIdsToResolve(t),I=I.filter(A=>!this.notificationResolverService.getNotificationById(A)));break}default:I=[]}if(I?.length){let A=at(),M=fQ.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:Sl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:s}}),s?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.notificationResolverService.resolveNotifications({request:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let I=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);I=[...I,...A],I=I.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);I=[...I,...A],I=I.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allActivities":{if(t&&typeof t=="object"){let A=Array.isArray(t)?t:Object.values(t),M=this.activityUtilsService.getEntityIdsToResolveFromActivities(A,"comment");I=[...I,...M],I=I.filter(B=>!this.commentAnnotationsResolverService.getCommentAnnotationById(B))}break}default:I=[]}if(I?.length){let A=at(),M=Q1.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldCommentAnnotationsResolverAwait:l}}),l?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(e==="allActivities"&&t&&typeof t=="object"){let I=Array.isArray(t)?t:Object.values(t),A=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let M=[];for(let B of I)B?.id&&!this.activityResolverService.getActivityById(B.id)&&M.push(B.id);if(M.length){let B=at(),q=CQ.GET_ACTIVITIES;this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:us.FORMAT_RESPONSE,moduleName:q,source:"internal",payload:{activityIds:M,organizationId:A,shouldActivityResolverAwait:d}}),d?yield this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:B,moduleName:q})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(I,"reaction");if(M=M.filter(B=>!this.reactionAnnotationsResolverService.getAnnotationById(B)),M.length){let B=at(),q=eS.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:v}}),v?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(I,"recorder");if(M=M.filter(B=>!this.recorderAnnotationsResolverService.getAnnotationById(B)),M.length){let B=at(),q=tS.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:q,source:"internal",payload:{recorderAnnotationIds:M,organizationId:A,shouldRecorderResolverAwait:u}}),u?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q})}}}return t}catch(I){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",I),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(l),i),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",i),e}}mergeActivityResolverWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable())switch(t){case"allActivities":return Array.isArray(e)?e.map(i=>this.activityUtilsService.mergeActivityWithResolverData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",i),e}}mergeNotificationsWithResolvedData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(t){case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeResolvedNotificationData(l),i),{}):Array.isArray(e)?e.map(i=>this.notificationUtilsService.mergeResolvedNotificationData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",i),e}}mergeNotificationsWithResolvedData$({data:e,feature:t}){try{return this.notificationResolverService.getNotificationsById$().pipe(ge(()=>{let i=this.mergeNotificationsWithResolvedData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),se(e)}}mergeReactionAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",i),e}}mergeRecorderAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(t){case"allRecorders":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",i),e}}mergeActivitiesWithFeatureData(e){return Array.isArray(e)?e.map(t=>this.activityUtilsService.mergeActivityWithFeatureData(t)):e}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),i&&typeof i=="object"&&!Array.isArray(i))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(s,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(s,i),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.areaUtilsService.mergeAreaWithUser(l),i),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.arrowUtilsService.mergeArrowWithUser(l),i),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.cursorUtilsService.mergeCursorUserWithUser(l),i),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeCommentWithUser(l),i),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(l),i),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(i=>this.notificationUtilsService.mergeNotificationWithUser(i)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeNotificationWithUser(l),i),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.presenceUtilsService.mergePresenceUserWithUser(l),i),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeRecorderWithUser(l),i),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeReactionWithUser(l),i),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.tagUtilsService.mergeTagWithUser(l),i),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(l),i),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(l),i),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"liveStateSingleEditorMode":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.selectionUtilsService.mergeSelectionWithUser(l),i),{}):t;case"allActivities":return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithUser(i)):t;default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",i),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ge(()=>{let i=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ge(()=>{let i=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),se(e)}}mergeRecorderAnnotationsWithData$({data:e,feature:t}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ge(()=>{let i=this.mergeRecorderAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ge(()=>{let i=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof i=="object"?{data:JSON.parse(JSON.stringify(i)),operation:t?.operation??null}:{data:i,operation:t?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ge(i=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:i});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),se(e)}}handleDataStripping(l){return J(this,arguments,function*({feature:e,data:t,actionType:i,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return yield this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:i,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);case"recorder":return this.recorderUtilsService.stripRecorderAnnotationData({data:t,actionType:i});default:return{originalData:t,strippedData:null}}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",s),{originalData:t,strippedData:null}}})}formatData({feature:e,data:t,properties:i,offset:a,isRealtimeDb:l}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let s=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return l?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,s);case"notificationViewsTimestamp":return{views:{[i.user??""]:t}};case"documentUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"documentDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"documentMetadataViews":return l?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return l?t:{metadata:t};case"locationUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"locationDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"locationViews":return l?t:{location:t};case"docNotificationViews":return l?t:{views:t.views};case"userNotificationViews":return l?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",s),t}}modifyAndSetData(l){return J(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let s=yield this.modifyData({feature:e,data:t});i.next({data:s,operation:a})}catch(s){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",s)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:i}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(i??{}).includes(t.doc.id);if(i?.[t.doc.id]){let a=t.doc.data(),l=i?.[t.doc.id];return a?.lastUpdated===l?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(i){return J(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)?y(h({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",i),e}}setDataInLocal(d){return J(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:s=null}){try{let u={comment:"allComments",reaction:"allReactions"}[e];if(!u)return null;let _=t?.metadata?.documentId,I=t?.metadata?.veltFolderId;return Object.keys(i).filter(A=>A.includes(u)&&(!_||A.includes(_)||I&&A.includes(I))).forEach(A=>{let M=i[A]?.subject?.getValue()??{};a==="DELETE"?l&&M?.data?.[l]&&(delete M?.data?.[l],i[A]?.subject&&i[A].subject.next({data:M?.data,operation:s})):i[A]?.subject?.next({data:y(h({},M?.data),{[t?.annotationId]:t}),operation:s})}),null}catch(v){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",v),null}})}handleCommentEncryption(s){return J(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l})}catch(d){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",d),e}})}handleReactionEncryption(a){return J(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:i})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",l),e}})}rtdbDefaultTransactionCallback(e,t){try{let i=h({},e||{});return Object.entries(t).forEach(([a,l])=>{l==null?delete i[a]:i[a]=l}),i}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",i),e}}};o.\u0275fac=function(t){return new(t||o)(X(mS),X(Rbe),X(Nbe),X(cv),X(Fbe),X(tr),X(Lbe),X(UL),X(VL),X(k),X(Bbe),X(jL),X($be),X(NL),X(kp),X(Hbe),X(Gbe),X(An),X(ct),X(rl),X(Gs),X(ol),X(mv),X(xp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zbe=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{Cn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe($e(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,s])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||En?.firebaseLogLevel||"silent";wJ(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=yp.getFirestoreProdDbName(l,a.firebaseOptions),v=this.configService.getProxyConfig();if(v?.v2DbHost){let u={host:v.v2DbHost,ssl:!0};v.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,s&&(u.localCache=dQ({tabManager:mQ()}));try{this.firestore$.next(dL(Bl(),u,d))}catch(_){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",_),this.firestore$.next(K1(d))}}else if(s)try{let u=Bl(),_=dL(u,{localCache:dQ({tabManager:mQ()})},d);this.firestore$.next(_)}catch{this.firestore$.next(K1(d))}else this.firestore$.next(K1(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||K1("DocumentIdDb");if(e){let t=cO(e,"generateDocumentId");return X1(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(X(Nt),X(qe),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I,A,M,B){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=s,this.databaseService=d,this.configService=v,this.docService=u,this.usersService=_,this.commentAnnotationsResolverService=I,this.reactionAnnotationsResolverService=A,this.recorderAnnotationsResolverService=M,this.notificationResolverService=B,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(q=>{if(q){this.db=q;let ae=Ur(q,".info/serverTimeOffset");this.offsetListener=mg(ae,Ce=>{let oe=Ce.val();this.offset=oe})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(q=>{q&&(this.firestore=q)}))}setActivityService(e){this.activityService=e}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return J(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return ms(i).update(t)}return Promise.resolve()}catch(i){return this.loggingService.catch("Error in setupOnDisconnect:",i),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Cn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe($e(([t,i])=>!!t),ut(1),ln(([t,i])=>{e({db:t,firestore:i})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,i,a,l,s){return J(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>J(this,[u],function*({db:d,firestore:v}){let _;t?.skipFirestore||(_=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let I=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!d){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let A,M;try{I&&(A=Ur(d,`${I}`))}catch{this.loggingService.catch("Error in dbRef")}try{_?.includes("/organizations")&&v&&_&&(M=X1(v,`${_}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:_}),s&&s({firestoreAvailable:!!v})}catch(A){this.loggingService.catch(`Error in ${e} operation: `,A),l&&l(A)}}))}catch(d){this.loggingService.catch("Error in performDatabaseOperation:",d)}})}setData(d){return J(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,v=>J(this,null,function*(){if(v.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Wf(v.dbRef,()=>JSON.parse(JSON.stringify(u))):yield qf(v.dbRef,JSON.parse(JSON.stringify(u)))}try{if(v.firestoreRef&&v.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:_,originalData:I,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,B=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:s?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:v.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(_,B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:I,firestorePath:v.firestorePath??""}))}else if(e==="recorder"){let M=null,B=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:_,eventType:A},B)),I&&(M?.isSuccess||M===null)&&this.firestore&&(yield pQ(this.firestore,q=>J(this,null,function*(){q.set(v.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield hQ(v.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(v){this.loggingService.catch(`Error in setData for ${e}`,v)}})}updateData(d){return J(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,v=>J(this,null,function*(){if(v.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Wf(v.dbRef,_=>{let I;return i?.rtdbTransactionCallback?I=i.rtdbTransactionCallback(_,u):I=this.commonDbUtilsService.rtdbDefaultTransactionCallback(_,u),JSON.parse(JSON.stringify(I))}):yield k8(v.dbRef,JSON.parse(JSON.stringify(u)))}try{if(v.firestoreRef&&v.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:_,originalData:I,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,B=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:s?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:v.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(_,B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:I,firestorePath:v.firestorePath??""}))}else if(e==="recorder"){let M=null,B=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:_,eventType:A},B)),I&&(M?.isSuccess||M===null)&&this.firestore&&(yield pQ(this.firestore,q=>J(this,null,function*(){q.set(v.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield hQ(v.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(v){this.loggingService.catch(`Error in updateData for ${e}`,v)}})}createActivityFromExtraData(e,t){try{if(!t?.actionType||!this.activityService)return;let i=this.activityUtilsService.buildActivityDataFromExtraData({feature:e,extraData:t});i&&this.activityService.createActivity(i)}catch(i){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",i)}}deleteData(s){return J(this,arguments,function*({feature:e,properties:t,callback:i,errorCallback:a,extraData:l}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.createActivityFromExtraData(e,l),this.performDatabaseOperation(e,t,d=>J(this,null,function*(){d.dbRef&&(yield y8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let v=null,u=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let v=null,u=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let v=null,u=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield gL(d.firestoreRef))}else if(e==="userNotification"){let v=null,u=at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:Sl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),v=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(v?.isSuccess||v===null)&&(yield gL(d.firestoreRef))}else yield gL(d.firestoreRef)}catch(v){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,v)}}),void 0,a,i)}catch(d){this.loggingService.catch(`Error in deleteData for ${e}`,d)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=at()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),at()||"noDocumentId"}}queryData(i){return J(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 J(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let i=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=cO(this.firestore,i);t?.useCollectionGroup&&(a=vQ(this.firestore,i));let l=t?.firestoreQuery??[],s=uQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield mbe(s).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,v),null));return d?d.data().count:0}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,d),0}else try{let d=yield gbe(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let v=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:v})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),v}}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,d),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(i){return this.loggingService.catch(`Error in Firestore query for ${e}:`,i),[]}})}handleRtdbQuery(e,t){return J(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let i=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Ur(this.db,i),l=t?.rtdbQuery??[],s=oY(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield tY(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let v=d.val();return v?t?.skipObjectValues?v:Object.values(v??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return J(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let l=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let s=yield vbe(X1(this.firestore,l)).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,v),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:v})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=s.data();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,s),{}}}if(this.db){let l=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let s=yield tY(Ur(this.db,l)).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,v),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:v})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=s.val();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,s),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return Cn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe($e(l=>!!l))]).pipe($e(([l,s])=>l?i&&!s?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),be(([l,s])=>{try{if(i&&s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,s).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.firestoreSubscriptions[a]=u}return new Ht(v=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>v.next(_),_=>v.error(_),()=>v.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(l){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleRealtimeDbListener(e,t,l).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.rtdbSubscriptions[a]=u}return new Ht(v=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>v.next(_),_=>v.error(_),()=>v.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return se({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),se({})}}),Vh(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,i){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),l=`${e}-${JSON.stringify(t)}`;return a?new Ht(s=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,s,t):this.setupDocumentListener(i,a,e,s,t);return()=>{s.complete(),s.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(be(s=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:s})),be(s=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:s,feature:e}):se(s)),be(s=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:s,feature:e}):se(s)),be(s=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:s,feature:e}):se(s)),kt(Jt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),se({}))}setupCollectionListener(e,t,i,a,l){let s=`${i}-${JSON.stringify(l)}`,d=cO(e,t);if(l?.useCollectionGroup&&(d=vQ(e,t)),l?.useQuery&&l?.firestoreQuery){let _=l?.firestoreQuery??[];d=uQ(d,..._)}let v=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),gQ(d,_=>{try{let I=JSON.parse(JSON.stringify(this.observablesCache[s]?.subject?.getValue()?.data??{})),A=null,M=!1;_?.docChanges()?.length?_.docChanges().forEach(B=>{["allComments","allReactions","allRecorders"].includes(i)&&!v&&B.type!=="removed"&&u.push(B.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:B,cache:this.observablesCache[s]?.subject?.getValue()?.data??{}})||(M=!0,Object.assign(I,this.handleCollectionChange(B,I)),B.type==="removed"&&(A||(A={type:B.type,ids:[]}),A.ids.push(B.doc.id)))}):M=!0,M&&(["allComments","allReactions","allRecorders"].includes(i)&&u?.length&&(this.commonDbUtilsService.resolveAnnotations({data:u,feature:i}),u=[]),this.commonDbUtilsService.modifyAndSetData({feature:i,data:I,subscriber:a,operation:A})),v=!1}catch(I){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,I),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(I,i,a)}},_=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,_),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(_,i,a)})}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,i,a,l){let s=X1(e,t);return gQ(s,d=>{try{let v=d.data()||{};l?.field&&(v=v?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:v,subscriber:a,operation:null})}catch(v){this.handleListenerError(v,i,a)}},d=>this.handleListenerError(d,i,a))}handleListenerError(e,t,i){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,i){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let s=t?.rtdbQuery??[];l=oY(l,...s)}return this.objectValFromChildEvents(l,e).pipe(Xn(s=>(this.loggingService.catch(`RTDB listener error for ${e}:`,s),se({}))),ge(s=>(s===null&&(s={}),s&&typeof s=="object"?Object.entries(s??{}).reduce((v,[u,_])=>(v[u]=this.commonDbUtilsService.addMetadata(_,t),v),{}):this.commonDbUtilsService.addMetadata(s,t))),be(s=>this.commonDbUtilsService.modifyData({feature:e,data:s})),be(s=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:s}),operation:null})))))}pushData(a){return J(this,arguments,function*({feature:e,properties:t,data:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${e}`,"color: green;"),this.performDatabaseOperation(e,t,l=>J(this,null,function*(){if(l.dbRef){let s=S8(l.dbRef);yield qf(s,JSON.parse(JSON.stringify(l.data)))}}),i)}catch(l){this.loggingService.catch(`Error in pushData for ${e}`,l)}})}streamChildAdded({feature:e,properties:t,afterTs:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${e}`,"color: green;"),new Ht(a=>{let l=null,s=!1,d=({db:v})=>{if(!v||s||!this.authService.getUser())return;let u=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!u)return;let I=Ur(v,u),A=!1,M=ae=>{try{let Ce=ae.val();if(A){if(i!=null&&Ce?.timestamp!=null&&Ce.timestamp<=i)return;a.next(Ce)}}catch(Ce){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,Ce)}},B=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(Ce){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,Ce)}};rY(I,M,B);let q=mg(I,()=>{A=!0},B,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),yD(I,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{s=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),se(null)}}objectValFromChildEvents(e,t){return new Ht(i=>{let a={},l=!1,s=null,d=B=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,B),i.error(B)}catch{}},v=B=>{try{if(!Mr(B,s)){let q=JSON.parse(JSON.stringify(B));s=q,i.next(q)}}catch{}},u=B=>{try{B.key&&(a[B.key]=B.val(),l&&v(h({},a)))}catch{}},_=B=>{try{B.key&&(a[B.key]=B.val(),l&&v(h({},a)))}catch{}},I=B=>{try{B.key&&(delete a[B.key],l&&v(h({},a)))}catch{}},A=B=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};s=q,i.next(q),l=!0}}catch{}};rY(e,u,d),Lve(e,_,d),Uve(e,I,d);let M=mg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),yD(e,"child_added",u),yD(e,"child_changed",_),yD(e,"child_removed",I)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(X(mS),X(qe),X(od),X(tr),X(k),X(zbe),X($n),X(Nt),X(ct),X(An),X(rl),X(Gs),X(ol),X(mv))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vv=(()=>{let o=class o{static uniquifySvgIds(e){let t=`v${++o.idCounter}`,i=/\bid="([^"]+)"/g,a=[],l;for(;(l=i.exec(e))!==null;)a.push(l[1]);let s=e;for(let d of a){let v=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;s=s.replace(new RegExp(`\\bid="${v}"`,"g"),`id="${u}"`),s=s.replace(new RegExp(`url\\(#${v}\\)`,"g"),`url(#${u})`),s=s.replace(new RegExp(`href="#${v}"`,"g"),`href="#${u}"`)}return s}constructor(e,t,i){this.domService=e,this.loggingService=t,this.sanitizer=i,this.emojis={},this.emojisSignal=De({}),this.rawSvgs={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let l=o.Icons[a];this.rawSvgs[a]=l,this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(l)))}),Object.keys(o.GIF_PATHS).forEach(a=>{let l=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(l))}),this.emojisSignal.set(h({},this.emojis))}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{let t=this.rawSvgs[e];return t?this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(t))):this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let i=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(i=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(i))}catch{return""}}setEmojiList(e){try{this.emojis={},this.rawSvgs={},Object.keys(e).forEach(t=>{let i=e[t];if(i.svg)this.rawSvgs[t]=i.svg,this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(i.svg)));else if(i.url){let a=`<img src="${i.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else i.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(i.emoji)))}),this.emojisSignal.set(h({},this.emojis))}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.idCounter=0,o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
222
+ `+dl),um&&AL([ze,Ge,$r],Zs=>{dl=yO(dl,Zs," ")}),oe&&bh?oe.createHTML(dl):dl},o.setConfig=function(){let yn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};HC(yn),VC=!0},o.clearConfig=function(){gd=null,VC=!1},o.isValidAttribute=function(yn,Ke,Ut){gd||HC({});let cn=zi(yn),Ho=zi(Ke);return GC(cn,Ho,Ut)},o.addHook=function(yn,Ke){typeof Ke=="function"&&SO(Ue[yn],Ke)},o.removeHook=function(yn,Ke){if(Ke!==void 0){let Ut=EWe(Ue[yn],Ke);return Ut===-1?void 0:TWe(Ue[yn],Ut,1)[0]}return Sbe(Ue[yn])},o.removeHooks=function(yn){Ue[yn]=[]},o.removeAllHooks=function(){Ue=Tbe()},o}var sS=Abe();var Mbe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Be=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new lt,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new lt,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new pr),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let s=[];return l.forEach(d=>{if(!Co(d))if(d instanceof HTMLElement){if(d.className.includes("cdk-overlay-container")||d.className.includes("cdk-overlay-connected-position-bounding-box"))return;if(d.className.includes("cdk-overlay")){let v=!1;d.childNodes.forEach(u=>{Co(u)&&(v=!0)}),v||s.push(d)}else s.push(d)}else s.push(d)}),s}catch(s){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",s),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Nr(),ln(([s,d])=>{try{let v=d.filter(_=>!s.includes(_)),u=s.filter(_=>!d.includes(_));u.length&&u.map(I=>document.getElementById(I)).filter(I=>I).forEach(I=>{this.unlistenElementScroll&&this.unlistenElementScroll[I.id]&&this.unlistenElementScroll[I.id]()}),v.length&&v.map(I=>document.getElementById(I)).filter(I=>I).forEach(I=>{this.unlistenElementScroll[I.id]=this.renderer.listen(I,"scroll",A=>{let M=this.calculateScreenSize();this.currentScreenSize$.next(M)})})}catch(v){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",v)}})).subscribe(()=>{},s=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",s)}),this.getSelectedAnnotationsMap$().subscribe(s=>{Object.keys(s||{})?.length?ghe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):uhe("snippylyUserScalableNo")},s=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",s)})}catch(l){this.loggingService.catch("Error in DomService constructor: ",l)}}setDocService(e){try{this.docService=e,this.subscribeToDomEvents()}catch(t){this.loggingService.catch("Error in DomService setDocService: ",t)}}setDynamicIdPatterns(e){try{let t=e.map(i=>typeof i=="string"?new RegExp(i):i).filter(Boolean);t.length&&(this.dynamicIdPatterns=t)}catch(t){this.loggingService.catch("Error in DomService setDynamicIdPatterns: ",t)}}isLikelyDynamicId(e){try{return e?this.dynamicIdPatterns.some(t=>t.test(e)):!1}catch{return!1}}getStableAttributes(e){try{let t={};if(!e.getAttributeNames)return t;let i=new Set(["id","class","style"]);return e.getAttributeNames().forEach(l=>{if(i.has(l)||l.includes("snippyly")||l.includes("velt"))return;let s=e.getAttribute(l);s&&s.length<=256&&(t[l]=s)}),t}catch{return{}}}buildStableElementSelector(e,t){try{if(Object.keys(t).length===0)return;let a=[e.tagName?.toLowerCase()],l=["data-","aria-","role","name","title","type"];return Object.keys(t).sort((d,v)=>{let u=l.findIndex(I=>d.startsWith(I)),_=l.findIndex(I=>v.startsWith(I));return(u===-1?99:u)-(_===-1?99:_)}).slice(0,4).forEach(d=>{let v=CSS.escape(t[d]);a.push(`[${d}="${v}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,s=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),s++,s>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return ehe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],s=e,d=0;for(;s&&s!==document.documentElement&&d<i;){let I=this.buildRobustXPathSegment(s);if(I&&(l.unshift(I),this.isStrongAnchorSegment(I)))break;s=s.parentElement,d++}if(l.length===0)return;let u=(a?"/":"//")+l.join("/");return l.some(I=>I.includes("[@")||I.includes("[contains(@class"))?u:void 0}catch{return}}buildRobustXPathSegment(e){try{let t=e.tagName.toLowerCase(),i=e.id;if(i&&!this.isLikelyDynamicId(i)&&document.querySelectorAll(`[id="${CSS.escape(i)}"]`).length===1)return`*[@id=${this.escapeXPathValue(i)}]`;let a=["data-region","data-instanceid","data-action","data-key","data-block","data-activityid"];for(let I of a){let A=e.getAttribute(I);if(A)return`${t}[@${I}=${this.escapeXPathValue(A)}]`}let l=Array.from(e.attributes).filter(I=>I.name.startsWith("data-")&&!I.name.includes("snippyly")&&!I.name.includes("velt")&&I.value.length<100).sort((I,A)=>I.value.length-A.value.length);if(l.length>0){let I=l[0];return`${t}[@${I.name}=${this.escapeXPathValue(I.value)}]`}let s=e.getAttribute("role");if(s)return`${t}[@role=${this.escapeXPathValue(s)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let v=e.getAttribute("name");if(v)return`${t}[@name=${this.escapeXPathValue(v)}]`;let u=e.getAttribute("type");if(u)return`${t}[@type=${this.escapeXPathValue(u)}]`;let _=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(_.length>0){let I=_.map(A=>`contains(@class, ${this.escapeXPathValue(A)})`).join(" and ");return`${t}[${I}]`}if(e.parentElement){let I=Array.from(e.parentElement.children).filter(A=>A.tagName===e.tagName);if(I.length>1){let A=I.indexOf(e)+1;return`${t}[${A}]`}}return t}catch{return}}isStrongAnchorSegment(e){try{return!!(e.includes("[@id=")||["main","navigation","banner","contentinfo","complementary","search"].some(a=>e.includes(`[@role='${a}']`))||["data-region","data-instanceid","data-activityid"].some(a=>e.includes(`[@${a}=`)))}catch{return!1}}escapeXPathValue(e,t=!0){try{return e.includes("'")?e.includes('"')?`concat(${e.split("'").map(l=>`'${l}'`).join(`,"'",`)})`:t?`"${e}"`:e:t?`'${e}'`:e}catch{try{return`concat(${e.split("'").map(s=>`'${s}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}getAllElementsFromRobustXPath(e){try{let t=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),i=[];for(let a=0;a<t.snapshotLength;a++){let l=t.snapshotItem(a);l instanceof Element&&i.push(l)}return i}catch{return[]}}generateAnchorRecord(e,t){try{let i=this.generateAnchorRecordForElement(e,t),a=null;if(e.parentElement&&e.parentElement instanceof HTMLElement&&Zr(e.parentElement)&&e.parentElement!==document.body&&(a=e.parentElement),i&&a){let l=this.generateAnchorRecordForElement(a,t);l&&(i.parent=l)}return i}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecord: ",i),null}}generateAnchorRecordForElement(e,t){try{if(!e)return null;let i=e,a=i.tagName?.toUpperCase();if(!a)return null;let l=i.id&&!this.isLikelyDynamicId(i.id)?i.id:void 0,s=this.getStableAttributes(i),d=this.buildStableElementSelector(i,s),v=this.getVisibleText(i),u=this.hashText(v||""),_=this.generateRobustXPath(i),I=this.getXPath(i),A=this.getXPath(i,!0),M=this.getXPath(i,!0,!0);return{version:"1.0",id:l,tagName:a,elementSelector:d,robustXPath:_||void 0,xPath:I||void 0,fXPath:A||void 0,cfXPath:M||void 0,contentHash:u?{value:u,algorithm:"md5",source:"textContent"}:void 0,createdAt:Date.now()}}catch(i){return this.loggingService.catch("Error in DomService generateAnchorRecordForElement: ",i),null}}resolveAnchorRecord(e){try{let t=[],i=null,a=(u,_,I=0)=>{let A=[],M=I;if(A.push({method:_,score:I}),e.tagName&&u.tagName?.toUpperCase()===e.tagName&&(M+=10,A.push({method:"tagName-match",score:10})),e.contentHash?.value){let B=this.getVisibleText(u);this.hashText(B)===e.contentHash.value&&(M+=30,A.push({method:"contentHash-match",score:30}))}t.push({el:u,score:M,by:_,scoreBreakdown:A})};if(e.id){let u=document.querySelectorAll(`#${CSS.escape(e.id)}`);if(u.length===1)return{element:u[0],matchedBy:"id",score:90};u.length>1&&u.forEach(_=>a(_,"id-duplicate",70))}if(e.elementSelector){let u=document.querySelectorAll(e.elementSelector);if(u.length===1)return{element:u[0],matchedBy:"element-selector",score:80};u.forEach(_=>a(_,"element-selector-duplicate",60))}e.robustXPath&&this.getAllElementsFromRobustXPath(e.robustXPath).slice(0,20).forEach(A=>a(A,"robustXPath",50)),e?.parent&&(i=this.resolveAnchorRecord(e.parent),i.element&&i.element.querySelectorAll(e.tagName?.toLowerCase()||"*").forEach(_=>a(_,"parent+tag",40)));let l=(u,_,I)=>{if(!u)return;let A=this.getElementFromXPath(u);A&&a(A,_||"xpath",I||30)};if(l(e.xPath,"xPath",30),l(e.cfXPath,"cfXPath",30),l(e.fXPath,"fXPath",30),e.contentHash?.value&&t.length===0){let _=I=>{let A=0;for(let M=0;M<I.length&&A<400;M++){let B=I[M];if(A++,!this.isElementVisible(B))continue;let q=this.getVisibleText(B),ae=this.hashText(q);ae&&ae===e.contentHash?.value&&a(B,"contentHash",15)}};if(i?.element&&i?.element instanceof Element){let I=i?.element?.querySelectorAll("*");_(I)}}if(!t.length)return{element:null};t.sort((u,_)=>_.score-u.score);let s=t[0].score,d=t.filter(u=>u.score===s);if(d.length>1){let u=[{path:e.xPath,label:"xPath"},{path:e.cfXPath,label:"cfXPath"},{path:e.fXPath,label:"fXPath"}];for(let _ of u)if(_.path){let I=this.getElementFromXPath(_.path);if(I){let A=d.find(M=>M.el===I);if(A)return{element:A.el,matchedBy:`${A.by}+position`,score:A.score,scoreBreakdown:A.scoreBreakdown}}}}let v=t[0];return{element:v.el,matchedBy:v.by,score:v.score,scoreBreakdown:v.scoreBreakdown}}catch(t){return this.loggingService.catch("Error in DomService resolveAnchorRecord: ",t),{element:null}}}subscribeToDomEvents(){try{this.docService?.getDocumentPaths$().pipe(ge(e=>{e?(this.onWindowResize(),this.onWindowScroll(),this.onPointerDown(),this.onWindowClick(),this.onWindowKeyupBackspace(),this.onWindowKeyupDelete(),this.onWindowKeyupEsc(),this.onWindowPopState(),this.onWindowKeydownShift(),this.onWindowKeyupShift(),this.addPointerMoveListener(),this.addPointerUpListener(),this.addSelectionChangeListener(),this.onDocumentFocus()):(this.unsubscribeFromWindowResize(),this.unsubscribeFromWindowScroll(),this.unsubscribeFromPointerDown(),this.unsubscribeFromWindowClick(),this.unsubscribeFromWindowKeyupBackspace(),this.unsubscribeFromWindowKeyupDelete(),this.unsubscribeFromWindowKeyupEsc(),this.unsubscribeFromWindowPopState(),this.unsubscribeFromWindowKeydownShift(),this.unsubscribeFromWindowKeyupShift(),this.unsubscribeFromPointerMoveListener(),this.unsubscribeFromPointerUpListener(),this.unsubscribeFromSelectionChangeListener(),this.unsubscribeFromDocumentFocus(),this.unsetMutationObserver())})).subscribe(),this.onDocumentClick()}catch(e){this.loggingService.catch("Error in DomService subscribeToDomEvents: ",e)}}setScrollableElementsIds(e){try{e&&e.length&&this.scrollableElementsIds$.next(Array.from(new Set(e)))}catch(t){this.loggingService.catch("Error in DomService setScrollableElementsIds: ",t)}}getScrollableElementsIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScrollableElementsIds$","color: green;"),this.scrollableElementsIds$.asObservable()}removeScrollableElementsIds(){this.scrollableElementsIds$.next([])}setMutationObserver(e){try{this.mutationObserver||(this.loggingService.log("%c[WB] Calling DomService FUNCTION: setMutationObserver","color: green;"),this.loggingService.log("%c[WB] setMutationObserver from: "+e,"color: green;"),this.animationFilterEnabled=this.detectAnimationLibraries(),this.loggingService.log("%c[WB] Animation filter:","color: green;",this.animationFilterEnabled?"ENABLED (library detected)":"DISABLED (no library)"),this.mutationObserver=new MutationObserver(t=>{try{if(t?.find(a=>a?.attributeName===N.VELT_IGNORE_CHANGE_DETECTION))return;let i=t.filter(a=>a.type==="childList").filter(a=>{let l=a.target;return a.removedNodes.forEach(s=>{let d=s;if(typeof d.getAttribute=="function"){let v=d.getAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(v!==null&&v!==""){let u=this.xpathCacheId.get(v);u!==void 0&&(this.xpathCacheId.delete(v),this.xpathCache.delete(u))}}}),Co(l)?!1:!!(this.filterSnippylyNodes(a.addedNodes).length||this.filterSnippylyNodes(a.removedNodes).length)});this.animationFilterEnabled?this.childListMutation$.next(i.filter(a=>!this.isAnimatingElement(a.target))):this.childListMutation$.next(i),i.push(...t.filter(a=>a.type==="attributes").filter(a=>!Co(a.target)).filter(a=>this.filterSnippylyNodes([a.target]).length).filter(a=>{if(a){let l=a.target;return l?.classList?.contains("snippyly-sidebar-panel")?!1:l?!l.getAttribute(N.VELT_IGNORE_CHANGE_DETECTION):!0}return!0})),i=i.filter(a=>{let l=!0;return Object.keys(N.INGNORE_MUTATION_OBSERVER_CHANGE_TAGS).forEach(s=>{a.target?.closest(s)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Zr(a.target)),this.animationFilterEnabled&&(i=i.filter(a=>!this.isAnimatingElement(a.target))),i.length&&this.mutation$.next(i)}catch(i){this.loggingService.catch("Error in DomService change detection: ",i)}}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0}))}catch(t){this.loggingService.catch("Error in DomService change detection: ",t)}}detectAnimationLibraries(){try{if(this.animationLibraryDetected!==null)return this.animationLibraryDetected;let e=window;return e.gsap||e.TweenMax||e.TweenLite||e.TimelineMax||e.TimelineLite?(this.loggingService.log("%c[WB] Detected animation library: GSAP","color: green;"),this.animationLibraryDetected=!0,!0):e.Swiper?(this.loggingService.log("%c[WB] Detected animation library: Swiper","color: green;"),this.animationLibraryDetected=!0,!0):e.AOS?(this.loggingService.log("%c[WB] Detected animation library: AOS","color: green;"),this.animationLibraryDetected=!0,!0):e.anime?(this.loggingService.log("%c[WB] Detected animation library: Anime.js","color: green;"),this.animationLibraryDetected=!0,!0):e.lottie||e.Lottie||e.bodymovin?(this.loggingService.log("%c[WB] Detected animation library: Lottie","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector("[data-framer-component-type]")?(this.loggingService.log("%c[WB] Detected animation library: Framer Motion","color: green;"),this.animationLibraryDetected=!0,!0):document.querySelector(this.ANIMATION_LIBRARY_SELECTOR)?(this.loggingService.log("%c[WB] Detected animation library: DOM markers","color: green;"),this.animationLibraryDetected=!0,!0):(this.loggingService.log("%c[WB] No animation library detected","color: green;"),this.animationLibraryDetected=!1,!1)}catch{return this.animationLibraryDetected=!1,!1}}isAnimatingElement(e){try{if(!e||typeof e.closest!="function")return!1;let t=window;if(t.gsap&&typeof t.gsap.isTweening=="function"){if(t.gsap.isTweening(e))return!0;if(typeof t.gsap.getTweensOf=="function")try{if(t.gsap.getTweensOf(e).length>0)return!0}catch{}}else if(t.TweenMax&&typeof t.TweenMax.isTweening=="function"){if(t.TweenMax.isTweening(e))return!0;if(typeof t.TweenMax.getTweensOf=="function")try{if(t.TweenMax.getTweensOf(e).length>0)return!0}catch{}}let i=e.style?.cssText||"";if(i){let d=i.includes("transform")||i.includes("translate3d")||i.includes("translate(")||i.includes("scale3d")||i.includes("rotate"),v=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(v||u))return!0}if(e.style&&(e.style.animation!==""&&e.style.animation!=="none"||e.style.transition!==""&&e.style.transition!=="none")||e.classList?.contains("animate")||e.classList?.contains("animating")||e.classList?.contains("animated")||e.classList?.contains("animation"))return!0;let a=this.staticAnimationCache.get(e);if(a!==void 0)return a;let l=!1,s=e.className||"";return typeof s=="string"&&(s.includes("slider")&&(s.includes("bullet")||s.includes("pagination"))&&(l=!0),s.includes("swiper-pagination")&&(l=!0)),!l&&(e.hasAttribute("data-aos")||e.hasAttribute("data-motion"))&&(l=!0),!l&&e.closest(this.ANIMATION_LIBRARY_SELECTOR)&&(l=!0),this.staticAnimationCache.set(e,l),l}catch{return!1}}unsetMutationObserver(){try{this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.staticAnimationCache=new WeakMap,this.animationLibraryDetected=null,this.animationFilterEnabled=!1)}catch(e){this.loggingService.catch("Error in DomService unsetMutationObserver: ",e)}}detectNetworkStatusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: detectNetworkStatusChange","color: green;");try{Ro(Or(window,"offline").pipe(ge(()=>!1)),Or(window,"online").pipe(ge(()=>!0)),new Ht(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 pr),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()!==N.TAGS.SUPERFLOW_TOOLBAR&&(this.documentClick$.next(e),this.documentClickSubject$.next(e))},document.addEventListener("click",this.documentClickListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentClick: ",e)}}unsubscribeFromDocumentClick(){try{this.documentClickListener&&typeof this.documentClickListener=="function"&&(document.removeEventListener("click",this.documentClickListener,!0),this.documentClickListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentClick: ",e)}}onDocumentFocus(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentFocus","color: green;");try{this.unsubscribeFromDocumentFocus(),this.documentFocusListener=e=>{this.documentFocus$.next(e)},document.addEventListener("focus",this.documentFocusListener,!0)}catch(e){this.loggingService.catch("Error in DomService onDocumentFocus: ",e)}}unsubscribeFromDocumentFocus(){try{this.documentFocusListener&&typeof this.documentFocusListener=="function"&&(document.removeEventListener("focus",this.documentFocusListener,!0),this.documentFocusListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromDocumentFocus: ",e)}}onWindowKeydownShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydownShift","color: green;");try{this.unsubscribeFromWindowKeydownShift(),this.unlistenWindowKeydownShift=this.renderer.listen("window","keydown.shift",e=>{this.windowKeydownShift$.next(e),this.windowKeyupShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeydownShift: ",e)}}unsubscribeFromWindowKeydownShift(){try{this.unlistenWindowKeydownShift&&typeof this.unlistenWindowKeydownShift=="function"&&(this.unlistenWindowKeydownShift(),this.unlistenWindowKeydownShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeydownShift: ",e)}}onWindowKeyupShift(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupShift","color: green;");try{this.unsubscribeFromWindowKeyupShift(),this.unlistenWindowKeyupShift=this.renderer.listen("window","keyup.shift",e=>{this.windowKeyupShift$.next(e),this.windowKeydownShift$.next(null)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupShift: ",e)}}unsubscribeFromWindowKeyupShift(){try{this.unlistenWindowKeyupShift&&typeof this.unlistenWindowKeyupShift=="function"&&(this.unlistenWindowKeyupShift(),this.unlistenWindowKeyupShift=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupShift: ",e)}}onWindowKeydown$(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeydown$","color: green;");try{return Or(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Pc}}addPointerMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerMoveListener","color: green;");try{this.unsubscribeFromPointerMoveListener(),this.unlistenPointerMoveListener=this.renderer.listen("document","pointermove",e=>{this.windowPointerMove$.next(e),this.mouseMoveEvent=e})}catch(e){this.loggingService.catch("Error in DomService addPointerMoveListener: ",e)}}unsubscribeFromPointerMoveListener(){try{this.unlistenPointerMoveListener&&typeof this.unlistenPointerMoveListener=="function"&&(this.unlistenPointerMoveListener(),this.unlistenPointerMoveListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerMoveListener: ",e)}}addPointerUpListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromPointerUpListener(),this.unlistenPointerUpListener=this.renderer.listen("document","pointerup",e=>{this.windowPointerUp$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromPointerUpListener(){try{this.unlistenPointerUpListener&&typeof this.unlistenPointerUpListener=="function"&&(this.unlistenPointerUpListener(),this.unlistenPointerUpListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerUpListener: ",e)}}addSelectionChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addPointerUpListener","color: green;");try{this.unsubscribeFromSelectionChangeListener(),this.unlistenSelectionChangeListener=this.renderer.listen("document","selectionchange",e=>{this.documentSelectionChange$.next(e)})}catch(e){this.loggingService.catch("Error in DomService addPointerUpListener: ",e)}}unsubscribeFromSelectionChangeListener(){try{this.unlistenSelectionChangeListener&&typeof this.unlistenSelectionChangeListener=="function"&&(this.unlistenSelectionChangeListener(),this.unlistenSelectionChangeListener=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromSelectionChangeListener: ",e)}}updateCurrentMousePosition(e){try{if(this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY,this.currentMousePosition.clientX=e.clientX,this.currentMousePosition.clientY=e.clientY,e.target){let t=this.getXPath(e.target),i=e.target;if(t?.includes("name()='svg'")){let u=this.getXPath(t);u&&(i=u.iterateNext()||e.target)}let a=i.getBoundingClientRect(),l=e.clientX-a.x,s=e.clientY-a.y,d=l*100/(a.width||1),v=s*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:v,leftPercentage:d}}else this.currentMousePosition.element=null;this.currentMousePosition$.next(this.currentMousePosition)}catch(t){this.loggingService.catch("Error in DomService updateCurrentMousePosition: ",t)}}getTargetElementForCursorPosition(e,t=!0,i=!1,a=!0,l,s=!0,d){try{let v=e,u=v?.touches?.length?v.touches[0]?.clientX:v?.clientX,_=v?.touches?.length?v.touches[0]?.clientY:v?.clientY;d&&(u=d.clientX,_=d.clientY);let I=this.getBackgroundElement(u,_,t,i);if(I&&l&&typeof l=="function"&&(I=l(I)),I){let A=this.getXPath(I),M=this.getXPath(I,!0),B=I.getBoundingClientRect(),q=u-B.x,ae=_-B.y,Ce=q*100/(B.width||1),oe=ae*100/(B.height||1),fe={xpath:A,fXpath:M,leftPercentage:Ce,topPercentage:oe};if(a){let Ie=this.getXPath(I,!0,!0);fe.cfXpath=Ie}if(s){let Ie=this.generateAnchorRecord(I);Ie&&(fe.anchor=Ie)}return fe}else return null}catch(v){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",v),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),s=[];l.forEach(v=>{Co(v)?s=[]:Zr(v)&&s.push(v)}),a&&(s=s.filter(v=>this.isElementVisibleOnScreen(v)));let d=0;return i||s?.forEach((v,u)=>{v.tagName.toLowerCase()==="svg"&&(d=u)}),s[d]}catch(l){return this.loggingService.catch("Error in DomService getBackgroundElement: ",l),null}}getBackgroundVeltElement(e,t){try{let i=document.elementsFromPoint(e,t),a=[];return i.forEach(l=>{Co(l)&&Zr(l)&&a.push(l)}),a[0]}catch(i){return this.loggingService.catch("Error in DomService getBackgroundSnippylyElement: ",i),null}}setPointerPosition(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPointerPosition","color: green;");try{this.previousMousePosition.pageX=e.pageX,this.previousMousePosition.pageY=e.pageY,this.currentMousePosition.pageX=e.pageX,this.currentMousePosition.pageY=e.pageY}catch(t){this.loggingService.catch("Error in DomService setPointerPosition: ",t)}}getCurrentWindowSize$(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSize","color: green;"),this.currentScreenSize$.asObservable()}getCurrentMousePosition$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentMousePosition","color: green;"),this.currentMousePosition$.asObservable()}getCurrentWindowSizeValue(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCurrentWindowSizeValue","color: green;"),this.currentScreenSize$.value}getTopLeftPosition(){this.loggingService.log("%c[WB] Calling FUNCTION: getTopLeftPosition","color: green;");try{let e=document?.body?.getBoundingClientRect()||document?.documentElement?.getBoundingClientRect(),t=this.currentMousePosition?.pageX||e.x+200,i=Math.min(t,e.width/2),a=Math.abs(e.y),l=e.y-20;return a>50&&(l=Math.abs(e.y)+180),this.loggingService.log(e),this.loggingService.log(i),this.loggingService.log(l),{topPositionX:i,topPositionY:l}}catch(e){return this.loggingService.catch("Error in DomService getTopLeftPosition: ",e),{topPositionX:0,topPositionY:0}}}toggleSelection(){this.enableRectSelectionSubject$.next(!this.enableRectSelectionSubject$.value)}enableSelection(){this.enableRectSelectionSubject$.next(!0)}disableSelection(){this.enableRectSelectionSubject$.next(!1)}setPinHighlighterClass(e){this.pinHighlighterClass$.next(e)}setTextHighlighterClass(e){this.textHighlighterClass$.next(e)}getTextHighlighterClass(){return this.textHighlighterClass$.asObservable()}enableCommentPinHighlighter(){this.commentPinHighlighter$.next(!0)}disableCommentPinHighlighter(){this.commentPinHighlighter$.next(!1)}getCommentPinHighlighter$(){return this.commentPinHighlighter$.asObservable()}getCommentPinHighlighter(){return this.commentPinHighlighter$?.value}highlightElement(e,t,i){if(e){if(!i&&this.getCommentPinHighlighter()&&(this.pinHighlighterClass$.value?this.addClassToElement(e,this.pinHighlighterClass$.value):this.addClassToElement(e,N.SNIPPYLY_HIGHLIGHT)),t&&!e.hasAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)){let a=e.style.getPropertyValue("cursor"),l=e.style.getPropertyPriority("cursor"),s=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(N.ATTRIBUTES.DEFAULT_CURSOR,s?JSON.stringify(s):""),e.style.setProperty("cursor",t,"important")}e.setAttribute(N.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true")}}removeHighlightFromElement(e){if(e&&(this.pinHighlighterClass$.value&&this.removeClassFromElement(e,this.pinHighlighterClass$.value),this.removeClassFromElement(e,N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.VELT_IGNORE_CHANGE_DETECTION),e.hasAttribute(N.ATTRIBUTES.DEFAULT_CURSOR))){try{if(e.style.removeProperty("cursor"),e.getAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)){let t=JSON.parse(e.getAttribute(N.ATTRIBUTES.DEFAULT_CURSOR));e.style.setProperty("cursor",t.defaultCursorValue,t.defaultCursorPriority)}}catch{}e.removeAttribute(N.ATTRIBUTES.DEFAULT_CURSOR)}}highlightUserElement(e,t,i,a=!1){try{e&&(this.addClassToElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT),a&&this.addClassToElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.setAttribute(N.SNIPPYLY_HIGHLIGHT,"true"),e.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true"),t&&!e.style.getPropertyValue(N.VELT_SELECTION_COLOR)&&e.style.setProperty(N.VELT_SELECTION_COLOR,t),i&&e.setAttribute(N.SNIPPYLY_HIGHLIGHT_USER_NAME,i))}catch(l){this.loggingService.catch("Error in DomService highlightUserElement: ",l)}}removeHighlightUserFromElement(e){try{e&&(this.removeClassFromElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT),this.removeClassFromElement(e,N.VELT_LIVE_SELECTION_ON_ELEMENT_DEFAULT),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT),e.removeAttribute(N.VELT_IGNORE_CHANGE_DETECTION),e.removeAttribute(N.VELT_SELECTION_COLOR),e.removeAttribute(N.SNIPPYLY_HIGHLIGHT_USER_NAME),e.style.removeProperty(N.VELT_SELECTION_COLOR))}catch(t){this.loggingService.catch("Error in DomService removeHighlightUserFromElement: ",t)}}previewHighlightElement(e){e&&e.setAttribute(N.SNIPPYLY_HIGHLIGHT_PREVIEW,"true")}removePreviewHighlightFromElement(e){e&&e.removeAttribute(N.SNIPPYLY_HIGHLIGHT_PREVIEW)}getXPath(e,t=!1,i=!1,a){try{let l=this.calculateXPath(e,t,i,a);if(l&&typeof l=="string"&&l.includes("/svg")){let s=l.split("/"),d=!1;s.forEach((v,u)=>{v.includes("svg")&&(d=!0),d&&(s[u]="svg:"+v)}),l=s.join("/")}return l}catch(l){this.loggingService.catch("Error in DomService getXPath:",l)}}namespaceResolver(e){return e==="svg"?"http://www.w3.org/2000/svg":null}calculateXPath(e,t,i,a){try{if(e){if(typeof e=="string")return document.evaluate(e,a||document,this.namespaceResolver,XPathResult.ANY_TYPE,null);if(!e||e.nodeType!=1)return"";if(e.id&&document.querySelectorAll(`[id='${e.id}']`)?.length===1&&!t)return"//*[@id='"+e.id+"']";if(i&&e.className&&e.className.split){let s=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(s){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),v=Array.from(e.parentNode?.children||[]).filter(u=>u.nodeType===1&&u.tagName===e.tagName?u.className?.split(" ")?.filter(I=>I?.includes("snippyly")||I?.includes("velt")||["show-pin-cursor"].includes(I))[0]===s:!1);if(v.length>1){let u=v.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${s} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(s){return s.tagName==e.tagName});return this.calculateXPath(e.parentNode,t,i)+"/"+e.tagName.toLowerCase()+(l.length>1?"["+([].indexOf.call(l,e)+1)+"]":"")}}catch(l){this.loggingService.catch("Error in DomService calculateXPath:",l)}}getElementFromXPath(e,t=document){try{if(this.xpathCache.has(e)){let a=this.xpathCache.get(e);if(a!==void 0&&document.contains(a))return a;this.xpathCache.delete(e)}let i=this.getXPath(e,!1,!1,t);if(i){let a=i?.iterateNext();if(a!==null&&typeof a.setAttribute=="function"){let l=at();a.setAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID,l),this.xpathCacheId.set(l,e)}return this.xpathCache.set(e,a),a}return null}catch(i){return this.loggingService.catch("Error in DomService getElementFromXPath:",i),null}}getElementFromTargetElement(e){try{let t=null;if(e?.anchor){let i=this.resolveAnchorRecord(e.anchor);i?.element&&(t=i.element)}else e?.xpath?t=this.getElementFromXPath(e.xpath):e?.cfXpath?t=this.getElementFromXPath(e.cfXpath):e?.fXpath&&(t=this.getElementFromXPath(e.fXpath));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetElement:",t),null}}getElementFromTargetTextRange(e){try{let t=null;if(e?.commonAncestorContainerAnchor){let i=this.resolveAnchorRecord(e.commonAncestorContainerAnchor);i?.element&&(t=i.element)}else e?.commonAncestorContainer&&(t=this.getElementFromXPath(e.commonAncestorContainer));return t}catch(t){return this.loggingService.catch("Error in DomService getElementFromTargetTextRange:",t),null}}calculateScreenSize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{let e=[document?.body?.clientHeight||0,document?.documentElement?.clientHeight||0,window?.innerHeight||0],t=[document?.body?.clientWidth||0,document?.documentElement?.clientWidth||0,window?.innerWidth||0];this.calculatePageScrollHeight(),this.loggingService.log(this.pageScrollHeight),this.loggingService.log(this.nodeMap),this.highestNode=this.nodeMap[this.pageScrollHeight];let i=new hO;return i.screenWidth=Math.max(...t),i.screenHeight=Math.max(...e),i.screenScrollHeight=this.pageScrollHeight,i}catch(e){return this.loggingService.catch("Error in DomService calculateScreenSize:",e),new hO}}calculatePageScrollHeight(){this.loggingService.log("%c[WB] Calling FUNCTION: calculatePageScrollHeight","color: green;");try{this.pageScrollHeight=0,this.findLongestNode(document?.documentElement?.childNodes)}catch(e){this.loggingService.catch("Error in DomService calculatePageScrollHeight: ",e)}}removeSnippylyContent(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeSnippylyContent","color: green;");try{let i=new DOMParser().parseFromString(e,"text/html");i.querySelectorAll("[data-snippyly-cache-id]").forEach(_=>{_.removeAttribute("data-snippyly-cache-id")}),i.querySelectorAll("[data-velt-cache-id]").forEach(_=>{_.removeAttribute("data-velt-cache-id")}),i.querySelectorAll(".comment-text-highlight").forEach(_=>{_?.parentNode?.insertBefore(document.createTextNode(_?.textContent),_),_.remove()});let d=document.createNodeIterator(i,NodeFilter.SHOW_COMMENT),v;for(;v=d.nextNode();)v?.remove();return this.mergeAdjacentTextNodes(i.body),this.sanitizeHtml(i.body.innerHTML)}catch(t){return this.loggingService.catch("Error in DomService removeSnippylyContent: ",t),e}}mergeAdjacentTextNodes(e){try{let t=e.firstChild;for(;t;){if(t.nodeType===Node.TEXT_NODE){let i=t.nextSibling;for(;i&&i.nodeType===Node.TEXT_NODE;)t.textContent+=i.textContent,i.remove(),i=t.nextSibling}t=t.nextSibling}}catch(t){this.loggingService.catch("Error in DomService mergeAdjacentTextNodes: ",t)}}findLongestNode(e){try{for(let t=e.length-1;t>=0;t--){if(e[t]?.scrollHeight&&e[t]?.clientHeight){let i=Math.max(e[t]?.scrollHeight,e[t]?.clientHeight);this.pageScrollHeight=Math.max(i,this.pageScrollHeight),this.nodeMap[i]=e[t]}e[t]?.childNodes?.length&&this.findLongestNode(e[t]?.childNodes)}}catch(t){this.loggingService.catch("Error in DomService findLongestNode: ",t)}}resetSelectedAnnotationsMap(e=!0,t){try{let i=Array.from(document.querySelectorAll(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`)),a=this.getDraftCommentAnnotationDialogs()||[];i.push(...a),i=Array.from(new Set(i));let l=i.map(u=>u.classList.contains("velt-annotation-draft-checked")?(u.classList.remove("velt-annotation-draft-checked"),null):(this.removeClassFromElement(u,"velt-comment-dialog-shake"),setTimeout(()=>{this.addClassToElement(u,"velt-comment-dialog-shake"),u.getAttribute(N.ATTRIBUTES.VELT_ANNOTATION_EDIT_COMMENT)||u.classList.contains("velt-annotation-draft-checked")||this.addClassToElement(u,"velt-annotation-draft-checked")},100),u.getAttribute(N.ATTRIBUTES.VELT_ANNOTATION_DRAFT))).filter(u=>u),s=Object.keys(this.getRecordingInProgress()||{});l=[...l,...s];let d=this.selectedAnnotationsMap$.value;if(e&&this.selectedAnnotationsMap$.value&&Object.keys(this.selectedAnnotationsMap$.value).length){let u=[];Object.keys(d).forEach(_=>{if(d[_]?.type==="tag"){let I=d[_];I?.to?.length||l.includes(_)||u.push(I)}else d[_]?.comments?.length||l.includes(_)||u.push(d[_])}),this.deleteAnnotations$.next(u),this.deleteAnnotations$.next([])}let v={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(v[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(v[u]=d[u]);break;default:d[u]?.type!==t&&(v[u]=d[u]);break}}),Object.keys(v).forEach(u=>{let _=v[u]?.multiThreadAnnotationId;_&&!v[_]&&(v[_]={annotationId:_,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(v)&&this.selectedAnnotationsMap$.next(v),this.setDialogOpenedInSidebar(!1)}catch(i){this.loggingService.catch("Error in DomService resetSelectedAnnotationsMap: ",i)}}setRecordingInProgress(e,t){try{if(t)this.recordingInProgress$.next(y(h({},this.recordingInProgress$.value),{[e]:t}));else{let i=this.recordingInProgress$.value;delete i[e],this.recordingInProgress$.next(i)}}catch(i){this.loggingService.catch("Error in DomService setRecordingInProgress: ",i)}}resetRecordingInProgress(){try{this.recordingInProgress$.next({})}catch(e){this.loggingService.catch("Error in DomService resetRecordingInProgress: ",e)}}getRecordingInProgress(){try{return this.recordingInProgress$.value}catch(e){return this.loggingService.catch("Error in DomService getRecordingInProgress: ",e),{}}}getDraftCommentAnnotationDialogs(){try{let e=[],t=Array.from(document.querySelectorAll(`${N.TAGS.SNIPPYLY_COMMENT_DIALOG}`)),i=Array.from(document.querySelectorAll(`${N.TAGS.VELT_COMMENT_DIALOG}`));return[...t,...i].forEach(l=>{if(l?.shadowRoot){let s=l.shadowRoot.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);s&&e.push(s)}else{let s=l.querySelector(`${N.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(s?.shadowRoot){let d=s.shadowRoot?.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}else{let d=l.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);d&&e.push(d)}}}),e}catch(e){return this.loggingService.catch("Error in DomService getDraftCommentAnnotationDialogs: ",e),[]}}getSelectedAnnotationsMap(e){try{let t=this.selectedAnnotationsMap$.value;if(e){let i={};return Object.keys(t).forEach(a=>{switch(e){case"comment":["comment","videoPin"].includes(t[a].type)&&(i[a]=t[a]);break;default:t[a].type===e&&(i[a]=t[a]);break}}),i}else return t}catch(t){return this.loggingService.catch("Error in DomService getSelectedAnnotationsMap: ",t),{}}}getSelectedAnnotationsMap$(e){return this.selectedAnnotationsMap$.asObservable().pipe(ge(t=>{if(e){let i={};return Object.keys(t).forEach(a=>{t[a].type===e&&(i[a]=t[a])}),i}else return t}))}getSelectedComments$(){return this.selectedAnnotationsMap$.asObservable().pipe(ge(e=>Object.values(e)))}getSelectedAnnotationsLocationMap(){try{return this.selectedAnnotationsLocationMap$.value}catch(e){return this.loggingService.catch("Error in DomService getSelectedAnnotationsLocationMap: ",e),{}}}getSelectedAnnotationsLocationMap$(){return this.selectedAnnotationsLocationMap$.asObservable()}toggleAnnotationSelection(e,t,i,a=!1,l){try{i==="sidebarShowReplies"?this.setDialogOpenedInSidebar(!0):this.setDialogOpenedInSidebar(!1);let s=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));s[e.annotationId]&&!a?delete s[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(s={}),s[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(s[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(s),Object.keys(d).forEach(v=>{s[v]||delete d[v]}),this.selectedAnnotationsLocationMap$.next(d)}catch(s){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",s)}}setSelectedAnnotationLocation(e,t){try{let i=JSON.parse(JSON.stringify(this.getSelectedAnnotationsLocationMap()||{}));i?.[e]!==t&&(i[e]=t,this.selectedAnnotationsLocationMap$.next(i))}catch(i){this.loggingService.catch("Error in DomService setSelectedAnnotationLocation: ",i)}}updateSelectedAnnotationInMap(e){try{let t=this.selectedAnnotationsMap$.value;e.forEach(i=>{t[i.annotationId]&&(t[i.annotationId]=i)}),this.selectedAnnotationsMap$.next(t)}catch(t){this.loggingService.catch("Error in DomService updateSelectedAnnotationInMap: ",t)}}getDeleteCommmentAnnotations$(){try{return this.deleteAnnotations$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeleteCommmentAnnotations$: ",e),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 i={offsetTop:0,offsetLeft:0},a=e;if(a===t){let l=window.getComputedStyle(e);l.position==="static"&&l.transformStyle!="preserve-3d"&&l.transform=="none"&&(i.offsetLeft=e?.offsetLeft||0,i.offsetTop=e?.offsetTop||0)}if(a!==t)if(e?.closest("svg"))for(;a&&a!==t;){let s=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let v=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-v.left,i.offsetTop+=u.top-v.top}}else s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop);if(a=a.parentElement,e instanceof SVGElement&&a===t){let d=window.getComputedStyle(a);d.position==="static"&&d.transformStyle!="preserve-3d"&&d.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0)}}else{let s=window.getComputedStyle(a);s.position==="static"?s.transformStyle!="preserve-3d"&&s.transform=="none"&&(i.offsetLeft+=a?.offsetLeft||0,i.offsetTop+=a?.offsetTop||0):(i.offsetLeft+=a.offsetLeft,i.offsetTop+=a.offsetTop)}return i}catch(i){return this.loggingService.catch("Error in DomService getElementOffset: ",i),{offsetTop:0,offsetLeft:0}}}isElementVisible(e){try{if(typeof e?.getBoundingClientRect=="function"){let{width:t,height:i,top:a,bottom:l}=e?.getBoundingClientRect();return t>0||i>0||a<window.innerHeight&&l>0}else return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisible: ",t),!1}}isElementVisibleOnScreen(e){try{if(e){if(!(e instanceof Element))return!1;let t=e,i=window.getComputedStyle(t);return!(i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0)}return!1}catch(t){return this.loggingService.catch("Error in DomService isElementVisibleOnScreen: ",t),!1}}getClickAndDragPointsObservable(){return new Ht(e=>{let t=Or(document,"mousedown").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=Or(document,"mousemove").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=Or(document,"mouseup").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),s=t.pipe(be(d=>i.pipe(Nr(),ge(([v,u])=>({startPoint:d,prevPoint:v,curPoint:u})),zo(a)))).subscribe(e);return()=>s.unsubscribe()})}drawRectangle(e,t){let i=document.querySelector(".rectangle");i||(i=document.createElement("div"),this.addClassToElement(i,"rectangle"),i.setAttribute(N.ATTRIBUTES.VELT_COMMENT_DISABLED,"true"),i.setAttribute(N.VELT_IGNORE_CHANGE_DETECTION,"true"),document.body.appendChild(i));let a=Math.abs(t.x-e.x),l=Math.abs(t.y-e.y),s=Math.min(e.x,t.x),d=Math.min(e.y,t.y);return i.style.width=`${a}px`,i.style.height=`${l}px`,i.style.left=`${s}px`,i.style.top=`${d}px`,i.style.position="absolute",i.style.border="2px dashed #f00",i.style.pointerEvents="none",i.style.zIndex="2147483577",i}getRange(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getRange","color: green;"),window.getSelection()?.toString()){let e=window.getSelection();if(e?.rangeCount)return e.getRangeAt(0)}return null}catch(e){return this.loggingService.catch("Error in DomService getRange: ",e),null}}clearTextSelection(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearTextSelection","color: green;"),window.getSelection&&(window.getSelection()?.empty?window.getSelection()?.empty():window.getSelection()?.removeAllRanges&&window.getSelection()?.removeAllRanges())}catch(e){this.loggingService.catch("Error in DomService clearTextSelection: ",e)}}getTargetTextRangeFromSelectionRange(e){try{let t={},i=e.commonAncestorContainer;i?.nodeType===Node.TEXT_NODE&&(i=i.parentElement);let a=document.body;if(i){let s=this.getTextXPath(i);this.isXpathWithId(s)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let s=this.getElementFromXPath(t.commonAncestorContainer);if(s){t.commonAncestorContainerFXpath=this.getXPath(s,!0),t.commonAncestorContainerCFXpath=this.getXPath(s,!0,!0);let d=this.generateAnchorRecord(s);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=s0(a,0,e.startContainer,e.startOffset,e.toString())+1,t}catch(t){this.loggingService.catch("Error in DomService getTargetTextRangeFromSelectionRange: ",t);return}}getTextXPath(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: getTextXPath","color: green;"),e.nodeType===Node.TEXT_NODE){let t=1,i=e.previousSibling;for(;i;)i.nodeType===Node.TEXT_NODE&&t++,i=i.previousSibling;return this.getXPath(e.parentElement)}else return this.getXPath(e)}catch(t){this.loggingService.catch("Error in DomService getTextXPath: ",t);return}}getHostElement(e){try{if(N.NON_NESTABLE_ELEMENTS[e?.tagName?.toLowerCase()]){let i=e?.closest("picture");return i?i?.parentElement:e.parentElement}let t=e.closest("svg");return t?t?.parentElement:e}catch(t){return this.loggingService.catch("Error in DomService getHostElement: ",t),e}}isElementInsideAdditionalLocationContainer(e){try{return!!e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`)}catch(t){return this.loggingService.catch("Error in DomService isElementInsideAdditionalLocationContainer: ",t),!1}}getAdditionalLocationContainer(e){try{return e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`)||null}catch(t){return this.loggingService.catch("Error in DomService getAdditionalLocationContainer: ",t),null}}isXpathWithId(e){try{return typeof e=="string"?!!e?.includes("[@id="):!1}catch(t){return this.loggingService.catch("Error in DomService isXpathWithId: ",t),!1}}getListedElements({elementIds:e,elementClassNames:t,elementQuerySelectors:i}){try{let a=[];if(e?.length)for(let l=0;l<e.length;l++){let s=document.getElementById(e[l]);s&&a.push(s)}if(t?.length)for(let l=0;l<t.length;l++){let s=document.getElementsByClassName(t[l]);for(let d=0;d<s.length;d++){let v=s[d];v&&v instanceof HTMLElement&&a.push(v)}}if(i?.length)for(let l=0;l<i.length;l++){let s=document.querySelectorAll(i[l]);for(let d=0;d<s.length;d++){let v=s[d];v&&v instanceof HTMLElement&&a.push(v)}}return a}catch(a){return this.loggingService.catch("Error in DomService getListedElements: ",a),[]}}isElementInsideListedElementIds(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementById(t[i]);if(a&&a.contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementIds: ",i),!1}}isElementInsideListedElementClassNames(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.getElementsByClassName(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementClassNames: ",i),!1}}isElementInsideListedElementQuerySelectors(e,t){try{if(t?.length){for(let i=0;i<t.length;i++){let a=document.querySelectorAll(t[i]);for(let l=0;l<a.length;l++)if(a[l].contains(e))return!0}return!1}return!0}catch(i){return this.loggingService.catch("Error in DomService isElementInsideListedElementQuerySelectors: ",i),!1}}addClassToElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addClassToElement","color: green;"),e&&(e.classList?.contains(t)||e.classList?.add(t))}catch(i){this.loggingService.catch("Error in DomService addClassToElement: ",i)}}removeClassFromElement(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeClassFromElement","color: green;"),e&&e.classList?.contains(t)&&e.classList?.remove(t)}catch(i){this.loggingService.catch("Error in DomService removeClassFromElement: ",i)}}isElementInsideParentWithAttribute(e,t,i){try{let a=e;for(;a&&a!==document.body;){if(a?.getAttribute&&a?.getAttribute(t)===i)return!0;a=a.parentElement}return!1}catch(a){return this.loggingService.catch("Error in DomService isElementInsideParentWithAttribute: ",a),!1}}setVideoEditorHandlingDelete(e){try{this.isVideoEditorHandlingDelete=e}catch(t){this.loggingService.catch("Error in DomService setVideoEditorHandlingDelete: ",t)}}isVideoEditorHandlingDeleteKey(){try{return this.isVideoEditorHandlingDelete}catch(e){return this.loggingService.catch("Error in DomService isVideoEditorHandlingDeleteKey: ",e),!1}}setCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomCss","color: green;"),this.customCss$.next(e)}catch(t){this.loggingService.catch("Error in DomService setCustomCss: ",t)}}getCustomCss$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getCustomCss$","color: green;"),this.customCss$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getCustomCss$: ",e),se(null)}}injectCustomCss(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: injectCustomCss","color: green;");let t=this.customCss$.value;if(t){let i=e?.shadowRoot?.querySelector(`[${N.VELT_CUSTOM_CSS}]`);if(i&&i.remove(),t?.type==="link"){let a=document.createElement("link");a.href=t?.value,a.rel="stylesheet",a.setAttribute(N.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}else{let a=document.createElement("style");a.innerHTML=this.sanitizeHtml(t?.value),a.setAttribute(N.VELT_CUSTOM_CSS,"true"),e?.shadowRoot?.appendChild(a)}}}catch(t){this.loggingService.catch("Error in DomService injectCustomCss: ",t)}}trimCommentHtml(e){try{let t=document.createElement("div");t.innerHTML=e,this.removeEmptyElements(t);let i=t.innerHTML;return i=i.replace(o.MULTIPLE_NBSP_REGEX," ").replace(o.TRIM_NBSP_REGEX,"").trim(),i}catch(t){return this.loggingService.catch("Error in DomService trimCommentHtml: ",t),e}}removeEmptyElements(e){try{let a=function(l){return i.test(l.innerHTML)};var t=a;let i=/^\s*(<br\s*\/?>)?\s*$/;for(;e.firstChild&&a(e.firstChild);)e.removeChild(e.firstChild);for(;e.lastChild&&a(e.lastChild);)e.removeChild(e.lastChild)}catch(i){this.loggingService.catch("Error in DomService removeEmptyElements: ",i)}}normalizeWhitespace(e){try{e.childNodes.forEach(t=>{t.nodeType===Node.TEXT_NODE?t.nodeValue=t.nodeValue?.replace(/\s+/g," ").trim()??"":t.nodeType===Node.ELEMENT_NODE&&this.normalizeWhitespace(t)})}catch(t){this.loggingService.catch("Error in DomService normalizeWhitespace: ",t)}}sanitizeHtml(e){try{return this.loggingService.log("%c[WB] Calling FUNCTION: sanitizeHtml","color: green;"),sS.sanitize(e,Mbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeHtmlForPaste(e){try{let t=this.convertStylesToTags(e);return sS.sanitize(t,{ALLOWED_TAGS:["b","strong","i","em","u","a","br"],ALLOWED_ATTR:["href","target","rel"]})}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtmlForPaste: ",t),""}}convertStylesToTags(e){try{let t=document.createElement("div");return t.innerHTML=e,this.processNodeStyles(t),t.innerHTML}catch(t){return this.loggingService.catch("Error in DomService convertStylesToTags: ",t),e}}processNodeStyles(e){try{let t=Array.from(e.childNodes);for(let i of t)if(i.nodeType===Node.ELEMENT_NODE){this.processNodeStyles(i);let a=i,l=a.style,s=i,d=l?.fontWeight;if(d==="bold"||d==="700"||d==="800"||d==="900"){let v=a.tagName?.toLowerCase();if(v!=="b"&&v!=="strong"){let u=document.createElement("b");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}if(l?.fontStyle==="italic"){let v=a.tagName?.toLowerCase();if(v!=="i"&&v!=="em"){let u=document.createElement("i");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}if((l?.textDecorationLine?.includes("underline")||l?.textDecoration?.includes("underline"))&&a.tagName?.toLowerCase()!=="u"){let u=document.createElement("u");s.parentNode.insertBefore(u,s),u.appendChild(s),s=u}}}catch(t){this.loggingService.catch("Error in DomService processNodeStyles: ",t)}}sanitizeSvg(e){try{return sS.sanitize(e,Mbe)}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 pr;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 pr)}}getTabId(){try{let e=sessionStorage.getItem(N.SESSION_STORAGE.VELT_TAB_ID);!e&&this.tabId&&(e=this.tabId,sessionStorage.setItem(N.SESSION_STORAGE.VELT_TAB_ID,e)),!this.tabId&&e&&(this.tabId=e);let t=this.getTabIdFromWindowName();return(!e||e!==t)&&(e=at(),this.tabId=e,sessionStorage.setItem(N.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 pr}}isMobileDevice(){try{return new pr().getDeviceType()===Bi.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new pr().getDeviceType()===Bi.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new pr().getDeviceType()===Bi.DESKTOP}catch(e){return this.loggingService.catch("Error in DomService isDesktopDevice: ",e),!1}}deepCloneElement(e){try{var t=document.createElement(e?.tagName);return Array.from(e.attributes).forEach(i=>{t.setAttribute(i.nodeName,i.nodeValue)}),e.childNodes.forEach(i=>{i.nodeType===Node.ELEMENT_NODE?t.appendChild(this.deepCloneElement(i)):i.nodeType===Node.TEXT_NODE&&t.appendChild(document.createTextNode(i.nodeValue))}),t}catch(i){return this.loggingService.catch("Error in DomService deepCloneElement: ",i),e}}setRandomNumberToElementRecursive(e){try{if(!e)return;let t=Math.random().toString(36).substring(7);e&&e.setAttribute&&typeof e.setAttribute=="function"&&(e.getAttribute("velt-wireframe-id")||e.setAttribute("velt-wireframe-id",t)),Array.from(e.children).forEach(a=>{this.setRandomNumberToElementRecursive(a)})}catch(t){this.loggingService.catch("Error in DomService setRandomNumberToElementRecursive: ",t)}}setDialogOpenedInSidebar(e){this.dialogOpenedInSidebar$.next(e)}getDialogOpenedInSidebar(){return this.dialogOpenedInSidebar$.asObservable()}removeWireframeSuffixFromTags(e){if(!e)return;Array.from(e.children).forEach(i=>{if(this.removeWireframeSuffixFromTags(i),i.tagName.toLowerCase().endsWith("-wireframe")){let a=i.tagName.toLowerCase().replace("-wireframe",""),l=document.createElement(a);for(Array.from(i.attributes).forEach(s=>{l.setAttribute(s.name,s.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new pr().getDeviceType()===Bi.MONITOR}catch(e){return this.loggingService.catch("Error in DomService isMonitorDevice: ",e),!1}}isElementOriginallyStatic(e){try{return window.getComputedStyle(e).position==="static"||e.hasAttribute(N.ATTRIBUTES.VELT_COMMENT_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_AREA_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_TAG_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_RECORDER_PIN_HOST_STATIC)||e.hasAttribute(N.ATTRIBUTES.VELT_ARROW_PIN_HOST_STATIC)}catch(t){return this.loggingService.catch("Error in DomService isElementOriginallyStatic: ",t),!1}}};o.MULTIPLE_NBSP_REGEX=/(?:&nbsp;\s*){2,}/g,o.TRIM_NBSP_REGEX=/^(?:&nbsp;\s*)+|(?:&nbsp;\s*)+$/g,o.\u0275fac=function(t){return new(t||o)(X(st),X(xi),X(k),X(Rd))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var qe=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=s,this.analyticsService=d,this.loggingService=v,this.user$=new Se(null),this.userOptions$=new Se(null),this.userContacts$=new Se(null),this.userOrganization$=new Se(null),this.isPrivateCommentsEnabled$=new Se(!1),this.providedUser=new ra,this.firebaseConfig$=new Se(null),this.advancedQueries$=new Se(null),this.planDetails$=new Se(null),this.signOutPreviousUser$=new Se(null),this.preSignOutFunctions=new Map,this.autoLoginCalled=!1,this.autoLoginRequired=!0,this.config=null,this.getPlanDetailsCalled=!1,this.forceReLoggedIn=!1,this.lastLoggedInUserData=null,this.sessionReLoginCount=0,this.SESSION_RE_LOGIN_COUNT_LIMIT=10,this.sessionReLoginSubscription=null,this.onRetrySubscription=null,this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT=3,this.tokenExpiredErrorCount=0,this.loggingService.log("%c[WB] Creating CLASS: AuthService","color: blue;");try{try{let u=this.configService.getAuthProxyHost();if(u){let _=this.afAuth?.config;_&&(_.apiHost=u,_.tokenApiHost=u)}}catch{}this.analyticsService.setAuthService(this),this.configService.getConfig$().subscribe(u=>{this.config=u}),this.forceReLoggedIn=localStorage.getItem(N.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN)==="true",this.sessionReLoginSubscription=Cr(this.afAuth).pipe(yo(this.afAuth.currentUser),Nr(),be(([u,_])=>this.domService.onNetworkStatusChange$().pipe($e(I=>I),ut(1),ge(()=>({previousUser:u,currentUser:_}))))).subscribe(I=>J(this,[I],function*({previousUser:u,currentUser:_}){if(!_&&u){let A=u?.stsTokenManager?.expirationTime,M=new Date().getTime(),B=A-M;M>A&&(this.analyticsService.trackEvent(Y.Events.Core.SDK_SESSION_TOKEN_EXPIRED,{apiKey:this.apiKey,user:this.user$.value,lastLoggedInUserData:this.lastLoggedInUserData,timeLeft:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.user$.value&&u?.uid===this.user$.value?.userSnippylyId&&this.lastLoggedInUserData?.user?.userSnippylyId===this.user$.value?.userSnippylyId&&(this.sessionReLoginCount>this.SESSION_RE_LOGIN_COUNT_LIMIT?(this.analyticsService.trackEvent(Y.Events.Core.SDK_SESSION_RE_LOGIN_COUNT_EXCEEDED,{apiKey:this.apiKey,clientUserId:this.lastLoggedInUserData.user.userId,snippylyUserId:this.lastLoggedInUserData.user.userSnippylyId,timeLeft:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.user$.value?.userSnippylyId),this.sessionReLoginSubscription?.unsubscribe()):(this.sessionReLoginCount++,this.analyticsService.trackEvent(Y.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:B,forceReset:this.userOptions$.value?.forceReset,sessionReLoginCount:this.sessionReLoginCount},!0,this.lastLoggedInUserData.user.userSnippylyId),this.lastLoggedInUserData.user=yield this.updateUserWithColorAndTextColor(this.lastLoggedInUserData.user),this.initializeClient(this.lastLoggedInUserData.user,this.lastLoggedInUserData.userOptions,this.lastLoggedInUserData.initializeClientToken,this.lastLoggedInUserData.autoLogin,"internal-sessionReLogin"))))}}),u=>{this.loggingService.catch("Error in AuthService sessionReLoginSubscription: ",u)}),this.getUser$().pipe(kt(Jt)).subscribe(u=>{let _=Uo(u);this.coreActionsService.triggerAction(tt.USER_UPDATE,_),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:tt.USER_UPDATE,payload:{user:_}})})}catch(u){this.loggingService.catch("Error in AuthService constructor: ",u)}}setApiKey(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: setApiKey","color: green;",e);try{if(this.apiKey){this.loggingService.log("API key is already set");return}this.apiKey=e,this.configService.setApiKey(this.apiKey),t||(t=new fL),this.configService.initConfig(t);let i=this.configService.getProxyConfig();if(i?.authHost)try{let a=this.afAuth?.config;a&&(a.apiHost=i.authHost,a.tokenApiHost=i.authHost)}catch(a){this.loggingService.catch("Error setting auth proxy config: ",a)}t.debugMode?sessionStorage.setItem("debugMode","true"):sessionStorage.removeItem("debugMode"),this.autoLoginCalled||Cr(this.afAuth).pipe(ut(1)).subscribe(a=>J(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Hm(a,!0).catch(s=>null);if(l){let{user:s}=l?.claims;this.autoLoginRequired&&(s=yield this.updateUserWithColorAndTextColor(s),this.initializeClient(s,this.userOptions$?.value?y(h({},this.userOptions$?.value),{replaceContacts:!1,replaceGroupContacts:!1,replacePrivateContacts:!1}):{},new Date().getTime(),!0,"internal-autoLogin"))}}}))}catch(i){this.loggingService.catch("Error in setApiKey: ",i)}}setUsersService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUsersService","color: green;"),this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService: ",t)}}setDocService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocService","color: green;"),this.docService=e}catch(t){this.loggingService.catch("Error in setDocService: ",t)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in setContactService: ",t)}}setIamService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setIamService","color: green;"),this.iamService=e}catch(t){this.loggingService.catch("Error in setIamService: ",t)}}setAreaService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAreaService","color: green;"),this.areaService=e}catch(t){this.loggingService.catch("Error in setAreaService: ",t)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService: ",t)}}setReactionService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setReactionService","color: green;"),this.reactionService=e}catch(t){this.loggingService.catch("Error in setReactionService: ",t)}}setRecorderAnnotationService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRecorderAnnotationService","color: green;"),this.recorderAnnotationService=e}catch(t){this.loggingService.catch("Error in setRecorderAnnotationService: ",t)}}setActivityService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setActivityService","color: green;"),this.activityService=e}catch(t){this.loggingService.catch("Error in setActivityService: ",t)}}setViewsService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setViewsService","color: green;"),this.viewsService=e}catch(t){this.loggingService.catch("Error in setViewsService: ",t)}}setCommonDbService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommonDbService","color: green;"),this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService: ",t)}}setCrdtService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCrdtService","color: green;"),this.crdtService=e}catch(t){this.loggingService.catch("Error in setCrdtService: ",t)}}validateOrganizationId(e){if(this.isVersionGreaterThanOrEqualTo4()&&!e?.organizationId)if(this.analyticsService.trackEvent(Y.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 J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setVeltAuthProvider","color: green;");try{this.onRetrySubscription?.unsubscribe();let t=null;if(!e.user)return null;e.generateToken&&typeof e.generateToken=="function"&&(t=yield e.generateToken());let i=yield lZ(()=>window.Velt.identify(e.user,h(h({},e.options||{}),t&&{authToken:t}),{fromProvider:!0}).catch(a=>(e.onError&&typeof e.onError=="function"&&e.onError(a),Promise.reject(a))),e.retryConfig||{retryCount:0,retryDelay:0});return i&&e.generateToken&&typeof e.generateToken=="function"&&(this.onRetrySubscription=this.coreActionsService.onAction(tt.ERROR).pipe($e(a=>a.code==="token_expired"),ut(10)).subscribe(a=>J(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],s=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],v=this.docService?.getLocation();v&&d.push(v.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(I=>{d.push(I.location)}),(yield lZ(()=>J(this,null,function*(){try{let I=yield e.generateToken?.();return I?window.Velt.identify(e.user,h(h({},e.options||{}),I&&{authToken:I}),{fromProvider:!0}):!0}catch{return!1}}),e.retryConfig||{retryCount:0,retryDelay:0}))&&(yield this.docService?.setDocuments({documents:l,options:s,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!v}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return J(this,null,function*(){try{if(e){let t=yield fc(e,e?.userId??"");localStorage.setItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return J(this,null,function*(){try{let t=localStorage.getItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield t1(t,e?.userId??""):null}catch(t){return this.loggingService.catch("Error in getUserFromStorage: ",t),null}})}setIsPrivateCommentsEnabled(e){try{this.isPrivateCommentsEnabled$.next(e)}catch(t){this.loggingService.catch("Error in setIsPrivateCommentsEnabled: ",t)}}getIsPrivateCommentsEnabled(){return this.isPrivateCommentsEnabled$.value}getIsPrivateCommentsEnabled$(){return this.isPrivateCommentsEnabled$.asObservable()}updateUserWithColorAndTextColor(e){return J(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e??{})),i=yield this.getUserFromStorage(t);return!i||Object.keys(i).length===0?(delete t?.color,delete t?.textColor,t):(i?.color&&(t.color=i?.color),i?.textColor&&(t.textColor=i?.textColor),t)}catch(t){return this.loggingService.catch("Error in updateUserWithColorAndTextColor: ",t),e}})}updateUserIfRequired(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserIfRequired","color: green;");try{let t=yield this.getUserFromStorage(e),i={};e.color&&e.color!==t?.color&&(i.color=e.color),e.textColor&&e.textColor!==t?.textColor&&(i.textColor=e.textColor),Object.keys(i).length>0&&e.clientOrganizationId&&this.docService?.addUserInfoToOrganization({organizationId:e.clientOrganizationId,user:y(h({},i),{userId:e.userId})})}catch(t){this.loggingService.catch("Error in updateUserIfRequired: ",t)}})}initializeClient(e,t,i,a,l){return J(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=ed(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let s=yield Cr(this.afAuth).pipe(ut(1)).toPromise().catch(v=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),s){let v=yield Hm(s,!0).catch(A=>null);if(!v)return;let{user:u,firebaseConfig:_,advancedQueries:I}=v.claims;s?.uid!==e?.userSnippylyId||e?.groupId!==u?.groupId||e?.organizationId!==u?.organizationId||t?.forceReset||!a&&e?.organizationId&&!this.forceReLoggedIn||this.forceReLoginRequiredForAdvancedQueries(e)||this.forceReLoginRequiredForRegion(e,_)||this.forceReLoginRequiredForCommentViews(e)?(localStorage.setItem(N.LOCAL_STORAGE.VELT_USER_FORCE_RE_LOGGED_IN,"true"),localStorage.setItem(N.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED,"true"),this.forceReLoggedIn=!0,yield this.signOutUser("internal")):(this.loggingService.log("%c[WB] Calling FUNCTION: reinitializeCurrentUser","color: green;"),this.loggingService.log("Keeping user"),yield this.updateUserIfRequired(e),this.validateOrganizationId(e),this.setFirebaseConfig(_),this.setAdvancedQueries(I),u&&(this.providedUser.isAdmin=!!u.isAdmin),this.initializeSignedInUser(s,a,e),d=!1,this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:"auto",forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l}))}if(d){this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_TRIGGERED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l},!0,e.userSnippylyId,e.userId);let v=Gr(this.functions,Wr({url:En.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=fa(),_=(yield v({apiKey:this.apiKey,user:e,version:u,authToken:t?.authToken}))?.data;if(_.error){if(this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_FAILED,y(h({apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,message:_.error,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)},_),{source:l}),!0,e.userSnippylyId,e.userId),_.error&&typeof _.error=="string")if(_.error?.toLowerCase()?.includes("token expired"))if(this.tokenExpiredErrorCount++,this.tokenExpiredErrorCount<=this.TOKEN_EXPIRED_ERROR_COUNT_LIMIT){let I={code:"token_expired",message:"Token expired",error:_?.error,source:_?.source};this.coreActionsService.triggerAction(tt.ERROR,I)}else{let I={code:"too_many_retries",message:"Token expired. Too many retries.",error:_?.error,source:_?.source};this.coreActionsService.triggerAction(tt.ERROR,I),this.analyticsService.trackEvent(Y.Events.Core.SDK_JWT_EXPIRED_RETRY_EXCEEDED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,source:l},!0,e.userSnippylyId,e.userId)}else{let I=_;this.coreActionsService.triggerAction(tt.ERROR,I)}throw _}else this.tokenExpiredErrorCount=0;if(this.analyticsService.trackEvent(Y.Events.Core.SDK_VALIDATE_CLIENT_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e),source:l},!0,e.userSnippylyId,e.userId),this.validateOrganizationId(e),_.firebaseConfig){this.setFirebaseConfig(_.firebaseConfig),yield this.signInWithCustomToken(e,_.token),this.loggingService.log("new signed in user",this.afAuth.currentUser);let I=yield Hm(this.afAuth.currentUser,!0).catch(B=>null);if(!I)return;let{user:A,advancedQueries:M}=I.claims;this.setAdvancedQueries(M),this.providedUser.isAdmin=!!A?.isAdmin,this.initializeSignedInUser(this.afAuth.currentUser,a,e)}}this.initializeClientToken=0,this.lastLoggedInUserData={user:e,userOptions:t,initializeClientToken:i,autoLogin:a},this.checkForPendingLogin()}return e}catch(s){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",s),t?.throwError?Promise.reject(s):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=fa();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=fa();if(e){let t=e.split("."),i=parseInt(t[0]||"0"),a=parseInt(t[1]||"0"),l=parseInt(t[2]||"0");if(i>=4&&a>=5)return i===4&&a===5&&l===0?!e.toLowerCase().includes("beta"):!0}return!1}catch(e){return this.loggingService.catch("Error in isVersion4Point5: ",e),!1}}forceReLoginRequiredForAdvancedQueries(e){try{let t=this.isVersionGreaterThanOrEqualTo4(),i=!1;try{let a=localStorage.getItem(N.LOCAL_STORAGE.VELT_ADVANCED_QUERIES);a&&(i=JSON.parse(a)?.advancedQueriesEnabled)}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForAdvancedQueries: ",t),!1}}forceReLoginRequiredForCommentViews(e){try{let t=this.isVersion4Point5(),i=!1;try{let a=localStorage.getItem(N.LOCAL_STORAGE.VELT_COMMENT_VIEWS_MIGRATED);a&&(i=JSON.parse(a))}catch(a){this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",a)}return!!(t&&e.organizationId&&!i)}catch(t){return this.loggingService.catch("Error in forceReLoginRequiredForCommentViews: ",t),!1}}forceReLoginRequiredForRegion(e,t){try{return!!(this.isVersionGreaterThanOrEqualTo4()&&e.organizationId&&!t?.region)}catch(i){return this.loggingService.catch("Error in forceReLoginRequiredForRegion: ",i),!1}}checkForPendingLogin(){this.pendingUserLogin&&this.initializeClient(this.pendingUserLogin,this.userOptions$?.value||{},new Date().getTime(),void 0,this.pendingUserLoginSource)}setFirebaseConfig(e){this.loggingService.log("%c[WB] Calling FUNCTION: setFirebaseConfig","color: green;");try{this.firebaseConfig$.value||this.firebaseConfig$.next({firebaseOptions:h(h({},En.firebaseConfig),e)})}catch(t){this.loggingService.catch("Error in setFirebaseConfig: ",t)}}getFirebaseConfig$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.asObservable()}getFirebaseConfig(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirebaseConfig","color: green;"),this.firebaseConfig$.value}setAdvancedQueries(e){this.loggingService.log("%c[WB] Calling FUNCTION: setAdvancedQueries","color: green;");try{e&&typeof e=="object"&&localStorage.setItem(N.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 Cn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ge(()=>this.getAdvancedQueriesEnabled()),Xn(()=>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;"),Cr(this.afAuth).pipe(be(e=>e?this.user$.asObservable():se(null)),kt(Jt))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=h(h({},this.providedUser),e),t){let i=h(h({},t),e);this.updateUserInternally(i)}}catch(t){this.loggingService.catch("Error in updateUser: ",t)}}signInWithCustomToken(e,t,i="manual"){this.loggingService.log("%c[WB] Calling FUNCTION: signInWithCustomToken","color: green;");try{return Dde(this.afAuth,t).then(a=>(this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_SUCCESS,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,user:this.getUserWithoutContacts(e)}),a)).catch(a=>(this.analyticsService.trackEvent(Y.Events.Core.SDK_USER_AUTH_FAILED,{apiKey:this.apiKey,clientUserId:e.userId,snippylyUserId:e.userSnippylyId,authType:i,forceReset:this.userOptions$.value?.forceReset,message:a.message,user:this.getUserWithoutContacts(e)}),a))}catch(a){return this.loggingService.catch("Error in signInWithCustomToken: ",a),Promise.reject(a)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache","color: green;");try{this.setIsPrivateCommentsEnabled(!1),this.activityService?.setActivityFeatureConfig({immutable:!1,isEnabled:!1})}catch(e){this.loggingService.catch("Error in clearCache: ",e)}}resetServicesCache(){this.loggingService.log("%c[WB] Calling FUNCTION: resetServicesCache in AuthService","color: green;");try{this.crdtService?.flushAllEditorActivities(),this.clearCache(),this.commonDbService?.unsubscribeFromObservables(),this.activityService?.destroy(),this.docService?.clearCacheOnUserCascade(),this.contactService?.clearCache(),this.iamService?.clearCache(),this.areaService?.clearCache(),this.commentService?.clearCache(),this.reactionService?.clearCache(),this.recorderAnnotationService?.clearCache(),this.viewsService?.clearCache()}catch(e){this.loggingService.catch("Error in resetServicesCache: ",e)}}initializeSignedInUser(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: initializeSignedInUser","color: green;");try{let a=new ra;a.userSnippylyId=e.uid,a.type="signedIn",i&&(a=h(h({},a),i)),this.setUserToStorage(a),this.mergeUserWithProvidedUserData(a,t)}catch(a){this.loggingService.catch("Error in initializeSignedInUser: ",a)}}mergeUserWithProvidedUserData(e,t){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: mergeUserWithProvidedUserData","color: green;");try{e.userId=this.providedUser?.userId||e.userId;let i=null;if(this.usersService?.externalUserDataProviderAvailable()){let a=at(),l=xc.IDENTIFY;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:gi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let s=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});s&&s[e.userId]&&(i=JSON.parse(JSON.stringify(s[e.userId]||{}))),e=h(h({},e),i||{})}e.name=i?i?.name:this.providedUser?.name||e.name,e.clientUserName=i?i?.clientUserName:this.providedUser?.clientUserName||e.clientUserName,e.photoUrl=i?i?.photoUrl:this.providedUser?.photoUrl||e.photoUrl,e?.photoUrl===void 0&&(e.photoUrl=null),e.email=i?i?.email:this.providedUser?.email||e.email,e.color=i?.color||this.providedUser?.color||this.getUserAvatarColor(e.userId),e.textColor=i?.textColor||this.providedUser?.textColor||this.getUserTextColor(e.userId),e.initial=i?.initial||this.providedUser?.initial||e.initial||e.name?.charAt(0).toUpperCase()||e.email?.charAt(0).toUpperCase(),e.contacts=this.providedUser?.contacts||e.contacts,e.plan=this.providedUser?.plan||e.plan,e.groupId=this.providedUser?.groupId||e.groupId,e.clientGroupId=this.providedUser?.clientGroupId||e.clientGroupId,e.clientOrganizationId=this.providedUser?.clientOrganizationId||e.clientOrganizationId,e.organizationId=this.providedUser?.organizationId||e.organizationId,e.isAdmin=this.providedUser?.isAdmin,e.isReadOnly=this.providedUser?.isReadOnly,e.isAnonymous=this.providedUser?.isAnonymous,e.isGuest=this.providedUser?.isGuest,this.updateUserInternally(e)}catch(i){this.loggingService.catch("Error in mergeUserWithProvidedUserData: ",i)}})}updateUserInternally(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserInternally","color: green;");try{let t=Object.assign({},e);delete t.contacts,this.analyticsService.identifyUser(e.userSnippylyId,t,{forceReset:this.userOptions$.value?.forceReset}),this.getPlanDetailsCalled||this.getPlanDetailsFromDb();let i=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=bl({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let v=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:oo.IDENTIFY,organizationId:e.clientOrganizationId}}],u=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:v}}),l=this.userPermissionService?.onResourceAccessRequired({requests:v,uniqueId:u,userId:e.userId,methodName:oo.IDENTIFY,fromCache:!1})??Promise.resolve()}let[s,d]=yield Promise.allSettled([a,l]);s.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!s.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(s.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",s.reason),this.afAuth.currentUser&&(this.user$.next(e),this.updateUserToFirebase(e))}catch(t){this.loggingService.catch("Error in updateUserInternally: ",t)}})}updateUserToFirebase(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserToFirebase","color: green;");try{let t=JSON.parse(JSON.stringify(e)),i=y(h({},t),{lastUpdated:new Date})}catch(t){this.loggingService.catch("Error in updateUserToFirebase: ",t)}}getPlanDetailsFromDb(){return J(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield Gr(this.functions,Wr({url:En.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:fa(),sdkType:this.configService.getSdkType()});return t?.data?.isPlanExpired&&(this.analyticsService.trackEvent(Y.Events.Core.SDK_PLAN_EXPIRED),this.configService.getSF()||console.warn("Velt SDK plan has expired.")),this.planDetails$.next(t?.data||{planInfo:null,isPlanExpired:!1}),t}catch(e){return this.loggingService.catch("Error in getPlanDetailsFromDb: ",e),this.planDetails$.next({planInfo:null,isPlanExpired:!1}),Promise.resolve(null)}})}isPlanExpired$(){return this.planDetails$.pipe($e(e=>!!e),ge(e=>!!e?.isPlanExpired))}isPlanExpired(){return this.planDetails$.getValue()?.isPlanExpired}addPreSignOutFuction(e,t){try{this.preSignOutFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreSignOutFuction: ",i)}}setUserOrganization(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganization","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===e?.organizationId?(t.metadata=e,this.userOrganization$.next(t)):this.userOrganization$.next(null)}catch(t){this.loggingService.catch("Error in setUserOrganization: ",t)}}setOrganizationUserGroups(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setUserOrganizationGroups","color: green;");let t=JSON.parse(JSON.stringify(this.userOrganization$.value||{}));this.getUser()?.organizationId===t?.metadata?.organizationId&&(t.groups=e,this.userOrganization$.next(t))}catch(t){this.loggingService.catch("Error in setUserOrganizationGroups: ",t)}}getUserOrganization$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOrganization$","color: green;"),this.getUser$().pipe(be(e=>e?this.userOrganization$.asObservable().pipe(ge(t=>t?.metadata?.organizationId===e.organizationId?t:null)):se(null)))}signOutUser(e="internal"){return J(this,null,function*(){try{e==="external"&&this.onRetrySubscription?.unsubscribe(),this.userPermissionService?.revokeAccessOnUserLogout(),this.analyticsService.trackEvent(Y.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 Cr(this.afAuth).pipe(ut(1)).toPromise().catch(i=>null);if(t){this.resetServicesCache(),this.user$.next(null);for(let[i,a]of this.preSignOutFunctions)try{yield a(t)}catch(l){this.loggingService.catch(`Error in signOutUser ${i} function: `,l)}return this.user$.next(null),yield qu(1e3),Ode(this.afAuth).catch(i=>{this.loggingService.catch("Error in signOutUser:",i)})}else return Promise.resolve()}catch(t){this.loggingService.catch("Error in signOutUser: ",t)}})}isFeatureAllowed(e){return Ao(this.config,this.user$.value,e)}getUserWithoutContacts(e){try{if(e){let t=JSON.parse(JSON.stringify(e));return delete t.contacts,t}else return null}catch(t){return this.loggingService.catch("Error in getUserWithoutContacts: ",t),null}}getUserForClient(e){try{return Uo(e)}catch(t){return this.loggingService.catch("Error in getUserForClient: ",t),null}}getUserAvatarColor(e){try{return e?this.avatarService.generateUserColor(Qn(e)):"#625DF5"}catch{return"#625DF5"}}getUserTextColor(e){try{return"#FFFFFF"}catch{return"#FFFFFF"}}setOptionalPropertiesToUsers(e){try{e.forEach(t=>{try{t?.color||(t.color=this.getUserAvatarColor(t?.userId)),t?.textColor||(t.textColor=this.getUserTextColor(t?.userId)),!t?.initial&&(t?.name||t?.email)&&(t.initial=t.name?.charAt(0).toUpperCase()||t.email?.charAt(0).toUpperCase())}catch{}})}catch{}}};o.\u0275fac=function(t){return new(t||o)(X(eo),X(Nt),X(sv),X(tr),X(Be),X(Do),X(st),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $n=(()=>{let o=class o{constructor(e,t,i){this.authService=e,this.configService=t,this.loggingService=i,this.db$=new Se(null);try{this.authService.getFirebaseConfig$().subscribe(a=>{if(a){let l=this.configService.getProxyConfig(),s=a.firebaseOptions.databaseURL;l?.v1DbHost&&s&&(s=wN(s,l.v1DbHost),l?.forceLongPolling&&Kq());let d=I_(void 0,s);l?.v1DbHost&&s&&this.lockDatabaseHost(d),this.db$.next(d)}},a=>{this.loggingService.catch("Error in DatabaseService constructor: ",a)})}catch(a){this.loggingService.catch("Error in DatabaseService constructor:",a)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(e){try{let i=e?._repo?.repoInfo_;if(i){let a=i.host;Object.defineProperty(i,"host",{get:()=>a,set:()=>{},configurable:!0}),i.internalHost=a}}catch(t){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",t)}}};o.\u0275fac=function(t){return new(t||o)(X(qe),X(Nt),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var RL=class{};var rl=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new Se(null),this.commentAnnotationById$=new Se({}),this.fieldsToRemove=[],this.additionalFields=[],this.getCommentAnnotationById=a=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",l);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove),a.config?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]))})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",a)}}getProvider(){try{let e=this.commentAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",e)}}resolveCommentAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:e}}),_(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],B=y(h({},e),{commentAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.commentAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.commentAnnotationById$.next(h(h({},this.commentAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=h(h({},l),e.commentAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(e.commentAnnotation),eventType:e.eventType,commentId:e.commentId}),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let a=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let l=this.commentAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.commentAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:v,event:Io.COMMENT_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:v,event:Io.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:I,commentAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):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}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}setCommentAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting comment annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.commentAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",t)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new Se(null),this.reactionAnnotationById$=new Se({}),this.getReactionAnnotationById=a=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",l);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",a)}}getProvider(){try{let e=this.reactionAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",e)}}resolveReactionAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:e}}),_(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],B=y(h({},e),{reactionAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.reactionAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.reactionAnnotationById$.next(h(h({},this.reactionAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=h(h({},l),e);let s={reactionAnnotation:e,event:Io.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Ai(()=>i?.config?.saveConfig?.url?ji(i.config.saveConfig.url,i.config.saveConfig.headers,s,!1):i?.save?.(s)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return d&&d.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(d?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:d,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(e),eventType:s.event}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let a=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let l=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=t??l?.[e]?.metadata,d=s?ti(s):void 0,v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.reactionAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:v,event:Io.REACTION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:v,event:Io.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:I,reactionAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):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 t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.reactionAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",t)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zs=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(a){this.loggingService.catch("Error in AttachmentResolverService constructor:",a)}}getProvider(e){try{let t=e||"default";return this.providers.get(t)||void 0}catch(t){this.loggingService.catch("Error in AttachmentResolverService getProvider:",t);return}}getRetrySaveConfig(e){let t=e||"default";return this.retrySaveConfigs.get(t)||this.defaultRetryConfig}getRetryDeleteConfig(e){let t=e||"default";return this.retryDeleteConfigs.get(t)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(e,t,i,a){return J(this,null,function*(){try{let l=new FormData;l.append("file",i);let s={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(s));let d={};t&&Object.entries(t).forEach(([_,I])=>{_.toLowerCase()!=="content-type"&&(d[_]=I)});let v=yield fetch(e,{method:"POST",headers:d,body:l});return v.ok?{data:(yield v.json())?.data??{},success:!0,statusCode:200}:(it.catch(`Error in makeAttachmentConfigBasedRequest: ${v.status} ${v.statusText}`),{data:{},success:!1,statusCode:v.status})}catch(l){return it.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let a=this.getProvider(i);if(!this.attachmentDataProviderAvailable(i))throw new Error("Attachment save data provider not available");let l=this.getRetrySaveConfig(i),s=t||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Ai(()=>J(this,null,function*(){if(a?.config?.saveConfig?.url){let v=e.attachment,{file:u}=v,_=Oh(v,["file"]);return this.makeAttachmentConfigBasedRequest(a.config.saveConfig.url,a.config.saveConfig.headers,u,{attachment:_,event:e.eventType,metadata:e.attachment.metadata})}return a?.save?.({attachment:e.attachment,event:e.eventType,metadata:e.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",l);if(d?.statusCode!==200){this.loggingService.catch(d?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{error:d,request:e}});return}return this.analyticsService.trackEvent(Y.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:e.attachment.attachmentId,eventType:e.eventType}),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Ic.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,s,d){return J(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let v=this.getProvider(a);if(!this.attachmentDataProviderAvailable(a))throw new Error("Attachment delete data provider not available");let u=t?h({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0,_=this.getRetryDeleteConfig(a),I=i||at();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Ai(()=>{if(v?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE};return ji(v.config.deleteConfig.url,v.config.deleteConfig.headers,M,!1)}return v?.delete?.({attachmentId:e,metadata:u,event:Io.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",_);return A?.statusCode!==200?(this.loggingService.catch(A?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{error:A,attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:e}),this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:I,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:_.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!0})}catch(v){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",v);let u=this.getRetryDeleteConfig(a),_=i||at(),I=t?h({apiKey:t.apiKey??null,documentId:t.documentId??null,organizationId:t.organizationId??null},t.folderId&&{folderId:t.folderId}):void 0;return this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:Ic.DELETE_ATTACHMENT,source:"internal",payload:{error:v,attachmentId:e,metadata:I}}),{revertOnFailure:u.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(e,t="default"){try{if(e){this.loggingService.log(`Setting attachment data provider for scope: ${t}`);let i=e.config,a=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],l=[];if(a.forEach(({method:s,configKey:d})=>{let v=i?.[d]?.url,u=s in e&&typeof e[s]=="function";!v&&!u&&l.push(s)}),l.length>0){let s=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(s);return}else this.providers.set(t,e),e.config?.saveRetryConfig&&this.retrySaveConfigs.set(t,e.config.saveRetryConfig),e.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(t,e.config.deleteRetryConfig)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(e){try{let t=e||"default";return this.providers.has(t)}catch(t){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",t),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ol=(()=>{let o=class o{constructor(e,t,i,a){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.attachmentResolverService=a,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.recorderAnnotationDataProvider$=new Se(null),this.recorderAnnotationById$=new Se({}),this.additionalFields=[],this.uploadChunks=!1,this.getRecorderAnnotationById=l=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[l]:void 0}catch(s){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",s);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(l=>{l&&(l.config?.resolveTimeout&&(this.resolveTimeout=l.config.resolveTimeout),l.config?.saveRetryConfig&&(this.retrySaveConfig=l.config.saveRetryConfig),l.config?.deleteRetryConfig&&(this.retryDeleteConfig=l.config.deleteRetryConfig),l.config?.getRetryConfig&&(this.retryGetConfig=l.config.getRetryConfig),l.config?.additionalFields&&(this.additionalFields=l.config.additionalFields||[]),this.uploadChunks=l.uploadChunks??!1)})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",l)}}getProvider(){try{let e=this.recorderAnnotationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",e);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",e)}}resolveRecorderAnnotations(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:e}}),_(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],B=y(h({},e),{recorderAnnotationIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.recorderAnnotationById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.recorderAnnotationById$.next(h(h({},this.recorderAnnotationById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let i=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=h(h({},l),e.recorderAnnotation);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(s?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(e.recorderAnnotation),eventType:e.eventType}),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let a=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let l=this.recorderAnnotationById$.getValue(),d=l?.[e]?.metadata??(t?ti(t):void 0),v=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:v}});let _=h({},l);delete _?.[e],this.recorderAnnotationById$._value=_;let I=yield Ai(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:v,event:Io.RECORDER_ANNOTATION_DELETE};return ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:v,event:Io.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return I&&I.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(I?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:I,recorderAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:e.toString()}),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:v}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||at(),s=t?ti(t):void 0;return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:oi.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),se(void 0)}}getAnnotationById(e){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[e]:void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",t);return}}getAdditionalFields(){try{return this.additionalFields}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",e),this.additionalFields}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(e){try{if(e){this.loggingService.log("Setting recorder annotation data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else e.storage&&this.attachmentResolverService.setAttachmentDataProvider(e.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",t)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st),X(zs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ct=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=s,this.commentResolverService=d,this.reactionResolverService=v,this.recorderResolverService=u,this.coreActionsService=_,this.functions=I,this.documentPaths$=new Se(null),this.docContext$=new Se(null),this.documentIds$=new Se([]),this.organizationConfig$=new Se(null),this.firestorePaths$=new Se(null),this.location$=new Se(null),this.excludedLocationIds$=new Se([]),this.organizationMetadata$=new Se(null),this.documentMetadata$=new Se(null),this.locationMetadata$=new Se(null),this.customerMetadata$=new Se(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Se({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Se({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new lt,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(VB(()=>Js(this.currentDebounceTime))).subscribe({next:A=>J(this,null,function*(){try{yield this.setDocumentIdImpl(A.documentId,A.clientOrganizationId,A.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:A=>{this.loggingService.catch("Error in setDocumentId subscription:",A),this.queueSize--}}),this.databaseService.getDb().pipe($e(A=>!!A),ut(1)).subscribe(A=>{A&&(this.db=A)}),this.configService.getApiKey$().subscribe(A=>{if(this.apiKey=A,this.apiKey){if(!this.isCustomDocId){let M=NN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>J(this,null,function*(){if(A&&(this.analyticsService.updateDefaultProperties({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&A?.organizationId&&this.documentPaths$.value?.organizationId!==A?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(M=>({id:M.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),A?.organizationId&&A?.clientOrganizationId)){let M={organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId};this.getOrganizationConfig()||this.organizationConfig$.next({organizationId:A?.organizationId,clientOrganizationId:A?.clientOrganizationId}),yield this.updateOrganizationMetadata(M)}})),this.documentPaths$.subscribe(A=>{let M={documentId:A?.documentId,clientDocumentId:A?.clientDocumentId,folderId:A?.folderId,allDocuments:A?.allDocuments,veltFolderId:A?.veltFolderId};A?.organizationId&&(M.organizationId=A.organizationId,M.clientOrganizationId=A.clientOrganizationId),this.analyticsService.updateDefaultProperties(M),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(A=>{this.analyticsService.updateDefaultProperties({clientLocation:A?.location,locationId:A?.locationId})}),this.organizationMetadata$.subscribe(A=>{this.authService.setUserOrganization(A?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe($e(A=>!!A),ut(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(A){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}},A=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",A)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(A){this.loggingService.catch("Error in DocService constructor:",A)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId}:null}catch(e){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",e),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.organizationConfig$.next(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(e=>({id:e.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(e=>e.location)].filter(e=>e!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(e){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",e)}}setUsersService(e){try{this.usersService=e}catch(t){this.loggingService.catch("Error in setUsersService:",t)}}setCommonDbService(e){try{this.commonDbService=e}catch(t){this.loggingService.catch("Error in setCommonDbService:",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in setUserPermissionService:",t)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in setCommentService:",t)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let e=NN(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=NN(location.href);this.currentUrl!==e&&(this.currentUrl=e,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},e=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",e)})}catch(e){this.loggingService.catch("Error in onWindowClick: ",e)}}setDocument(l){return J(this,arguments,function*({documentId:e,documentMetadata:t,options:i,source:a="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),a==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,documentMetadata:t,methodName:"setDocument",source:a}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:a,payload:{documentId:e,documentMetadata:t,options:i}}),yield this.setDocumentsImpl({documents:[{id:e,metadata:t}],options:h({organizationId:t?.organizationId},i??{}),source:a})}catch(s){this.loggingService.catch("Error in DocService setDocument:",s)}})}shouldSetDocumentsAgain(e,t={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&e.length===this.pendingDocumentIds.length&&e.every(u=>this.pendingDocumentIds.includes(u.id))&&Mr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(v=>v.clientDocumentId),s=RN(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(v=>l.includes(v.id))||!Mr(s,t)||i!==a}catch(i){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",i),!0}}getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:t=!1}){try{let i=[];return e.forEach(a=>{let l=a.id,s=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:s,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return J(this,arguments,function*({documents:e,options:t,source:i="internal",skipPermissionValidation:a=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:e,options:t,methodName:"setDocuments",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(i){return J(this,arguments,function*({document:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:yl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(s=>s.clientDocumentId);if(!l.includes(e.id)){let s=[...l.map(v=>({id:v})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:s,setClientDocumentMetadataMap:!0});this.documentIds$.next(d)}yield this.setDocumentIdImpl(e.id,this.documentPaths$.value?.clientOrganizationId,a)}catch(a){this.loggingService.catch("Error in DocService setRootDocument:",a)}})}setDocContext(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let t=JSON.parse(JSON.stringify(e??null));this.docContext$.next(t)}catch(t){this.loggingService.catch("Error in setDocContext: ",t)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(kt(Jt))}getProcessedDocContext(){return The(this.getDocContext())}filterRelevantDocuments(a){return J(this,arguments,function*({options:e,documentIds:t,skipPermissionValidation:i=!1}){try{let l=this.authService.getUser();return!l||!this.commonDbService?.shouldUseFirestore()||(t=yield this.fetchDocumentsFromFolder(e,t,l),yield this.handlePermissionProvider(e,t,l),t=yield this.filterDocumentsByPermissions(e,t,l,i),t=t.slice(0,50)),t}catch(l){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",l),t}})}fetchDocumentsFromFolder(e,t,i){return J(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield bl({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(s=>{t.find(d=>d.clientDocumentId===s.id)||t.push({documentId:mi(s.id),clientDocumentId:s.id})})}catch(a){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",a)}return t})}buildPermissionRequests(e,t,i){try{let a=[];return e.organizationId&&e.organizationId!==i.clientOrganizationId&&a.push({userId:i.userId,resource:{id:e.organizationId,type:oa.ORGANIZATION,source:oo.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}}),t&&t.forEach(l=>{a.push({userId:i.userId,resource:{id:l.clientDocumentId,type:oa.DOCUMENT,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&BN({input:e?.context}).forEach(s=>{let d=JSON.stringify(s.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:oo.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:s}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let i=e.data.filter(a=>a.type===oa.CONTEXT&&a.hasAccess).map(a=>a.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(i??"nil"))),i?.length){let a=t.filter(s=>i.includes(s.resource.id)).map(s=>s.resource.context).filter(s=>!!s),l=whe({input:a});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(l??"nil"))),l?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(l??"nil"))),this.setDocContext(l))}}catch(i){this.loggingService.catch("Error in processAccessibleContexts:",i)}}handlePermissionProvider(e,t,i){return J(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil")));let a=this.buildPermissionRequests(e,t,i),l=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let s=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:oo.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(s??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(s,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return J(this,null,function*(){if(a)return t;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(e??"nil")),"documentIds:",JSON.parse(JSON.stringify(t??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil"))),!(e?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(e,t,i);let s=this.currentValidationToken,d=[...t];return s&&this.validatePermissionsInBackground(e,t,i,s),d})}validateAndFilterPermissions(e,t,i){return J(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(v=>v.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),e?.folderId&&l?.[i.userId]?.folders?.[e?.folderId]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let s=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([v,u])=>{u?.errorCode===bo.PERMISSION_DENIED&&s.add(v)}),s.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...s].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...s],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(v=>!s.has(v.clientDocumentId));return d.length===0&&t.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),d}catch(a){return this.loggingService.catch("Error in validateAndFilterPermissions:",a),t}})}validatePermissionsInBackground(e,t,i,a){let l=e?.organizationId??i?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:l,documentIds:t.map(s=>s.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(s=>{if(this.currentValidationToken===a&&s){this.userPermissionService?.setCurrentUserPermissions(s);let d=[];Object.entries(s?.[i.userId]?.documents??{}).forEach(([v,u])=>{u?.errorCode===bo.PERMISSION_DENIED&&d.push(v)}),l&&s?.[i.userId]?.organization?.[l]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&s?.[i.userId]?.folders?.[e?.folderId]?.errorCode===bo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0),d.length>0&&(this.loggingService.catch(`User does not have access to documents: ${d.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(d,i,a))}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(e,t,i){try{if(this.currentValidationToken!==i)return;let a=this.documentPaths$.value;this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:e,userId:t.userId,timestamp:new Date().getTime()});let l=this.documentIds$.value||[],s=l.filter(d=>!e.includes(d.clientDocumentId));s.length!==l.length&&(s.length>0?this.setDocuments({documents:s.map(d=>({id:d.clientDocumentId})),options:{organizationId:a?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(tt.ERROR,{event:Y.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:e,userId:t.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(a){this.loggingService.catch("Error in handleDeniedDocumentAccess:",a)}}addUserInfoToOrganization(l){return J(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let s=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield bl({data:h({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:s,userId:a??t?.userId??""})}catch(s){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",s)}})}setDocumentsImpl(l){return J(this,arguments,function*({documents:e,options:t,source:i,skipPermissionValidation:a=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(e??"nil")),"options:",JSON.parse(JSON.stringify(t??"nil"))),!this.shouldSetDocumentsAgain(e,RN(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let s=at();this.currentValidationToken=s;let d=this.getDocumentIdsFromDocuments({documents:e,setClientDocumentMetadataMap:!0});if(d?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let v=this.authService.getUser();if(!v){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(_=>_.id),this.pendingOptions=RN(t)??{},this.documentPaths$.value?.organizationId&&t?.organizationId&&this.documentPaths$.value?.organizationId!==t?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let u=t?.organizationId??v?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:v}),d=yield this.filterRelevantDocuments({options:t,documentIds:d,skipPermissionValidation:a}),this.documentIds$.next(d),d?.length){let _=d[0]?.clientDocumentId;t?.rootDocumentId&&d.find(I=>I.clientDocumentId===t?.rootDocumentId)&&(_=t?.rootDocumentId),yield this.debounceSetDocuments({documentId:_,clientOrganizationId:t?.organizationId,options:t})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(s){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(a){return J(this,arguments,function*({documentId:e,clientOrganizationId:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:e,clientOrganizationId:t,methodName:"setDocumentId",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:yl.SET_DOCUMENT_ID,source:i,payload:{documentId:e,clientOrganizationId:t}}),yield this.setDocumentsImpl({documents:[{id:e}],options:{organizationId:t},source:i})}catch(l){this.loggingService.catch("Error in setDocumentId:",l);return}})}debounceSetDocuments(a){return J(this,arguments,function*({documentId:e,clientOrganizationId:t,options:i}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let l=i?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=l;let s=Date.now(),d=s-this.lastSetDocumentIdCallTime,v=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&v>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:e,clientOrganizationId:t,options:i??void 0});return}catch(l){this.loggingService.catch("Error in debounceSetDocuments:",l)}})}setDocumentIdImpl(e,t,i){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let a=this.authService.getUser();if(!a)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let l=this.currentDocumentId;if(this.apiKey){let s=`${Qn(e)}`,d=i?.folderId,v=i?.folderId?Pr(i?.folderId):void 0,u=i?.locationId,_=i?.allDocuments,I=a?.organizationId?t?It(t):a?.organizationId:void 0,A=at(),M=Q1.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let B=at(),q=eS.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,moduleName:q,methodName:ri.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=at(),Ce=tS.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ae,moduleName:Ce,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:B,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(oe=>oe.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:Ce})]),this.currentDocumentId!==s||this.documentPaths$.value?.organizationId!==I){this.loggingService.log("setting new docid"),this.currentDocumentId=s;let oe=new _L,fe=new RL;oe.clientDocumentId=e,fe.clientDocumentId=e,oe.folderId=d,fe.folderId=d,oe.locationId=u,fe.locationId=u,oe.allDocuments=_,fe.allDocuments=_,oe.veltFolderId=v,fe.veltFolderId=v,oe.documentId=s,fe.documentId=s,I&&(oe.organizationId=I,oe.clientOrganizationId=t??a?.clientOrganizationId,fe.organizationId=I,fe.clientOrganizationId=t??a?.clientOrganizationId);let Ie=`${this.apiKey}`,xe=`apiKey/${this.apiKey}`;I&&(Ie=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${oe.organizationId}`,xe=`${xe}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${oe.organizationId}`),fe.organization=`apiKey/${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,fe.document=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,oe.presence=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,oe.cursor=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,oe.comment=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,fe.comment=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,oe.multiThread=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,fe.multiThread=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,oe.tag=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,oe.area=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,fe.area=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AREA}`,oe.arrow=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,oe.selection=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,oe.audioHuddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,oe.huddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,oe.recorder=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,fe.recorder=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,oe.flock=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,oe.syncVideoPlayer=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,oe.liveState=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,oe.liveStateSingleEditorMode=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,oe.reaction=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,fe.reaction=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,oe.crdt=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,fe.crdt=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,oe.customerMetadata=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,oe.views=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,fe.notificationViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,fe.documentViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,fe.locationViews=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,oe.notifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,oe.metadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,oe.users=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,oe.documentIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.workspaceIam=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.groupContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,oe.globalContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,oe.logins=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,oe.userFeedback=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,oe.userReportBugs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,oe.userContactUs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,I&&(oe.organizationMetadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,oe.organizationIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,oe.organizationGroups=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,oe.organizationNotifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,s&&(oe.organizationNotificationsWithDocumentId=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/`,oe.heartbeatByDocument=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${s}/`),oe.organizationNotificationsLastNotificationTimestamp=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,oe.organizationNotificationsUsers=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,oe.heartbeat=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),fe.organizationUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,fe.users=`${xe}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,fe.documentUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,fe.notificationDocs=`${xe}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,fe.notificationUsers=`${xe}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(oe),this.firestorePaths$.next(fe),oe?.clientOrganizationId&&oe?.organizationId&&!(oe?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&oe?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:oe?.organizationId,clientOrganizationId:oe?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),l&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:s,clientDocumentId:e}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:s,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:e}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:yl.UNSET_DOCUMENT_ID,source:e}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocumentImpl({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let i=JSON.parse(JSON.stringify(this.documentIds$.value??[])),a=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),l=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),t&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:i,folderId:a,context:l}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:e}),this.analyticsService.trackEvent(Y.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:e==="external"?"User unset document id":"System unset document id",source:e},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetDocumentImpl: ",i)}}unsetDocuments({source:e,unsetDocumentPaths:t=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:e}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:e,methodName:yl.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:e,unsetDocumentPaths:t})}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(e,t)}catch(i){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",i)}}callPreDocumentIdChangeFunctions(e){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[t,i]of this.preDocumentIdChangeFunctions)try{yield i(e)}catch(a){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",a)}}catch(t){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",t)}})}fetchOrganizationMetadata(e){return J(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig()),this.db&&e?.organizationId){let t=e?.organizationId;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:t,field:"metadata"}}).then(i=>{i&&!i?.errorCode&&this.organizationMetadata$.next(y(h({},this.organizationMetadata$.value),{[t]:i}))}).catch(i=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)})}}catch(t){this.loggingService.catch("Error in fetchOrganizationMetadata: ",t)}})}fetchDocumentMetadata(e){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentMetadata$.value;if(e=e.filter(a=>!i?.[a.documentId]),e?.some(a=>!a?.documentId||!a?.clientDocumentId)||!t)return;if(this.commonDbService?.shouldUseFirestore()){let a=t?.folderId,l=[],s={organizationId:t?.clientOrganizationId,folderId:a},d=[],v=20;for(let _=0;_<e.length;_+=v)d.push(e.slice(_,_+v));d.forEach(_=>{let I=JSON.parse(JSON.stringify(s));I.documentIds=_.map(A=>A.clientDocumentId),l.push(this.fetchDocuments(I))});let u={};l.length>0&&(yield Promise.all(l).then(_=>{_?.forEach(I=>{I?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=A.metadata)})}),this.setAllDocumentMetadata(h(h({},this.documentMetadata$.value),u))}).catch(_=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",_)}))}else i?.[t?.documentId??e?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:t?.organizationId,documentId:t?.documentId??e?.[0]?.documentId,skipObjectValues:!0}}).then(a=>{a?.documentId&&this.setDocumentMetadata(a.documentId,a)}).catch(a=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",a)})}}catch(t){this.loggingService.catch("Error in fetchDocumentMetadata: ",t)}})}fetchLocationMetadata(){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,t=this.documentIds$.value,i=e?.folderId,a=e?.allDocuments,l=[],s={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],v=20;for(let _=0;_<t.length;_+=v)d.push(t.slice(_,_+v));d.forEach(_=>{let I=JSON.parse(JSON.stringify(s));I.documentIds=_.map(A=>A.clientDocumentId),l.push(this.fetchLocations(I))});let u=this.locationMetadata$.value??{};l.length>0&&Promise.all(l).then(_=>{_?.forEach(I=>{I?.forEach(A=>{A?.metadata?.documentId&&(u[A.metadata.documentId]=y(h({},u?.[A.metadata.documentId]??{}),{[A.location.id]:A}))})}),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}).catch(_=>{this.loggingService.catch("Error in fetchLocationMetadata: ",_)})}}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(Xn(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(ge(e=>e?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(e){try{return`${Qn(e)}`}catch(t){return this.loggingService.catch("Error in generateDocumentId: ",t),""}}generateOrganizationId(e){try{return`${It(e)}`}catch(t){return this.loggingService.catch("Error in generateOrganizationId: ",t),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(i){return J(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:void 0,methodName:"setLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,source:t,methodName:yl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return J(this,arguments,function*({locations:e,options:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:e,options:t,methodName:"setLocations",source:i}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.SET_LOCATIONS,source:i,payload:{locations:e,options:t}}),this.setLocationsImpl({locations:e,options:t})}catch(l){this.loggingService.catch("Error in setLocations: ",l)}})}getValidLocations(e){try{let t=[];return e&&Array.isArray(e)&&e.forEach(i=>{if(i&&typeof i=="object"){let a=!0;i?.version&&(!i?.version?.id||!i?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${i?.id}, If you're setting version then add id and name fields to version object.`),a=!1),a&&t.push(i)}}),t}catch(t){this.loggingService.catch("Error in getValidLocations: ",t)}return e}setRootLocation(i){return J(this,arguments,function*({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:e,methodName:"setRootLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:yl.SET_ROOT_LOCATION,source:t,payload:{location:e}});let a=Object.values(this.locations$.value).map(l=>l.location).filter(l=>String(l.id)!==String(e.id));this.setLocationsImpl({locations:[e,...a],options:{rootLocationId:e.id}})}catch(a){this.loggingService.catch("Error in DocService setRootLocation:",a)}})}setLocationsImpl({locations:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),e.length===0)return;if(!this.authService.getUser()){!t?.appendLocation&&e.length>0&&(this.draftLocationMap.options=y(h(h({},this.draftLocationMap.options??{}),t??{}),{rootLocationId:e[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...e],this.draftLocationMap.options=h(h({},this.draftLocationMap.options),t);return}let a=this.getValidLocations(e),l=[],s=[];this.location$.value?.location.id&&s.push(this.location$.value?.location.id),s=[...s,...Object.values(this.locations$.value).map(u=>u.location.id)].filter(u=>u!==void 0);let d;if(t?.rootLocationId&&t?.rootLocationId!==this.location$.value?.location.id&&(d=a.find(u=>u.id===t?.rootLocationId),!d)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${t?.rootLocationId} not found in locations.`);return}if(t?.appendLocation){if(d){let u=Oi(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}}else{d||(d=a[0]);let u=Oi(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}let v=[];return a.slice(t?.appendLocation?0:1).forEach(u=>{if(u.id!==this.location$.value?.location.id){let _=h({},u),I=this.locations$.value;u?.id&&Object.keys(I).forEach(q=>{let ae=I[q];ae.location?.id===u.id&&(_=h(h({},ae.location),u),delete I?.[q])});let A=this.genarateLocationId(_),M={locationId:A,location:_};_.id&&l.push({locationId:A,location:_}),v.push(M);let B=y(h({},I),{[A]:M});this.locations$.next(B)}}),this.updateDocumentLocationMetadata(l),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:yl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),v}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i);return}}addLocation({location:e,source:t="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[e],options:{appendLocation:!0},methodName:"addLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:yl.ADD_LOCATION,source:t,payload:{locations:[e],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[e],options:{appendLocation:!0}})}catch(i){this.loggingService.catch("Error in DocService addLocation:",i);return}}removeLocation({location:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[e],methodName:"removeLocation",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:t,methodName:yl.REMOVE_LOCATION,payload:{locations:[e]}}),e&&this.removeLocationsImpl([e],t)}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}removeLocations({locations:e,source:t="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e,methodName:"removeLocations",source:t}}),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:yl.REMOVE_LOCATIONS,source:t,payload:{locations:e}}),this.removeLocationsImpl(e,t)}catch(i){this.loggingService.catch("Error in removeLocations: ",i)}}removeLocationsImpl(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:e},methodName:"removeLocations",message:"System removed locations",source:t},!0,this.getUserIdForAnalytics()),e?e.forEach(i=>{let a=this.genarateLocationId(i);this.getLocation()?.locationId===a&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==i.id))),this.removeCustomLocation(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}unsetLocationIds(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:yl.UNSET_LOCATION_IDS,source:t,payload:{locationIds:e}}),t==="internal"&&this.analyticsService.trackEvent(Y.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:e},methodName:"unsetLocationIds",message:"System unset location ids",source:t},!0,this.getUserIdForAnalytics()),e?.length?e.forEach(i=>{this.getLocation()?.location.id===i&&(this.location$.next(null),t!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==i))),this.removeCustomLocationId(i)}):(this.location$.next(null),this.locations$.next({}),t!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(tt.INIT_UPDATE,{event:Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:yl.REMOVE_LOCATIONS_SUCCESS,source:t,payload:{locationIds:e}}),this.analyticsService.trackEvent(Y.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:e},source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetLocationIds: ",i)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(e){try{this.excludedLocationIds$.next([...e])}catch(t){this.loggingService.catch("Error in excludeLocationIds: ",t)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(e){return this.loggingService.catch("Error in getExcludedLocationIds$: ",e),se([])}}updateOrganizationMetadata(e){return J(this,null,function*(){try{!e&&this.getOrganizationConfig()&&(e=this.getOrganizationConfig());let t=e?.organizationId,i=this.documentPaths$.value;if(this.db&&t&&i?.documentId){if(this.organizationMetadata$.value?.[t])return;let l=new wL;l.apiKey=this.configService?.getApiKey()??"",l.organizationId=t,l.clientOrganizationId=e?.clientOrganizationId,this.userPermissionService?.hasEditAccess({organizationId:t})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:t,documentId:i?.documentId??""}})),yield this.fetchOrganizationMetadata(e)}}catch(t){this.loggingService.catch("Error in updateOrganizationMetadata: ",t)}})}updateFolderMetadata(){return J(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let e=this.documentPaths$.value;if(!e?.veltFolderId||!e?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:e?.organizationId??"",folderId:e?.veltFolderId??""}}))?.metadata){let i={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:e?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let a=Gr(this.functions,Wr({url:En?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield bl({methodName:"createFolder",data:{type:"createFolder",metadata:i},getSdkProxy:a,userId:this.authService.getUser()?.userId??""})}}}}catch(e){this.loggingService.catch("Error in updateFolderMetadata: ",e)}})}updateDocumentMetadata(){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value;if(e){let t=this.getDocumentIds();t.find(a=>a.documentId===e.documentId)||t.push({documentId:e.documentId??"",clientDocumentId:e.clientDocumentId??""});let i=t.map(a=>J(this,null,function*(){let l=new bL;this.clientDocumentMetadataMap?.[a.clientDocumentId]&&(l=h(h({},this.clientDocumentMetadataMap[a.clientDocumentId]),l)),l.apiKey=this.configService?.getApiKey()??"",l.documentId=a.documentId,l.clientDocumentId=a.clientDocumentId,l.organizationId=e.organizationId,l.clientOrganizationId=e.clientOrganizationId,l.pageInfo=no();let s=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let v=!0,u=this.documentMetadata$.value?.[a.documentId];if(s&&d){let _=this.getDocumentMetadata(a?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:e?.organizationId??"",field:"metadata"}}));_?.clientDocumentId&&!_?.errorCode?_?.folderId&&(_?.folderId!==s||_?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),v=!1):_?.folderId===s?(s&&(l.folderId=s),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${s??""}`),v=!1):(s&&(l.folderId=s),d&&(l.veltFolderId=d))}if(u){let _={};Object.entries(l).forEach(([I,A])=>{_[I]=A}),Mr(_,u)&&(v=!1)}v&&this.userPermissionService?.hasEditAccess({documentId:a?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(l)),properties:{organizationId:e?.organizationId??"",documentId:a?.documentId??""}}))}));yield Promise.allSettled(i),yield this.fetchDocumentMetadata(t)}}}catch(e){this.loggingService.catch("Error in updateDocumentMetadata: ",e)}})}updateDocumentLocationMetadata(e){return J(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(a=>a.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});for(let a of i){let l=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}});l?.errorCode&&(l={});let s=[];for(let d of e){let v=new xL;v.locationId=d?.locationId,v.veltLocationId=YK(d?.location?.id??""),v.location=d?.location,v.pageInfo=no(),v?.pageInfo?.deviceInfo&&delete v?.pageInfo?.deviceInfo;let u=y(h({},l),{[N.FIREBASE_PARTIAL_PATH_LOCATIONS]:y(h({},l[N.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:v})});this.commonDbService?.shouldUseFirestore()||s.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:a?.documentId??"",organizationId:t?.organizationId??""}}));let _=this.locationMetadata$.value;if(_||(_={}),d?.location?.id){let I=_?.[a.documentId],A=I?.[d?.location?.id??""];_&&(I||(_[a.documentId]={}),A||(_[a.documentId][d?.location?.id??""]={}),_[a.documentId][d?.location?.id??""]=y(h({},A),{location:d?.location})),Object.keys(_||{}).length>0&&this.locationMetadata$.next(_)}}yield Promise.allSettled(s)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Oi(e))):0}catch(t){return this.loggingService.catch("Error in genarateLocationId: ",t),0}}removeCustomLocation(e,t="internal"){try{let i=this.genarateLocationId(e),a=this.locations$.value;a[i]&&(delete a[i],this.locations$.next(h({},a)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(l=>l.id!==e.id)))}catch(i){this.loggingService.catch("Error in DocService removeLocation:",i)}}removeCustomLocationId(e,t="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let i=this.locations$.value;Object.entries(i).forEach(([a,l])=>{l.location.id===e&&(delete i[a],this.locations$.next(h({},i)),t!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==e)))})}catch(i){this.loggingService.catch("Error in DocService removeCustomLocationId:",i)}}getLocationByClientLocationId(e){try{let t=this.getLocation()?.location;if(t?.id===e)return t;{let i=this.getLocations();Object.keys(i).forEach(a=>{let l=i[a];l.location?.id===e&&(t=l.location)})}return t}catch(t){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",t);return}}removeLocationIfNotInDom(){try{let e=this.locations$.value,t=document.querySelectorAll(`[${N.ATTRIBUTES.VELT_LOCATION}]`),i=[];t.forEach(a=>{let l=a.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(l){let s=JSON.parse(l),d=this.genarateLocationId(s);i.push(d)}}),Object.keys(e).forEach(a=>{let l=e[a];i.includes(l.locationId)||delete e[a]}),this.locations$.next(h({},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(N.ATTRIBUTES.VELT_LOCATION)?t=e:t=e.closest(`[${N.ATTRIBUTES.VELT_LOCATION}]`),t){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(i){let a=JSON.parse(i);return{locationId:this.genarateLocationId(a),location:a}}}return null}catch(t){return this.loggingService.catch("Error in DocService getLocationFromElement:",t),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let e={};return document.querySelectorAll(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(i=>{if(i.getAttribute(N.ATTRIBUTES.VELT_LOCATION)){let a=this.getLocationFromElement(i);a?.locationId&&(e[a.locationId]={element:i,location:a})}else if(i.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID)){let a=i.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID);if(a){let l=this.getLocationByClientLocationId(a);l?.locationId&&(e[l.locationId]={element:i,location:l});let s={id:a},d=this.genarateLocationId(s);e[a]={element:i,location:{locationId:d,location:s}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${N.ATTRIBUTES.VELT_LOCATION}], [${N.ATTRIBUTES.VELT_LOCATION_ID}]`),t){if(t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION)){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION);if(i)return JSON.parse(i)}else if(t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID)){let i=t?.getAttribute(N.ATTRIBUTES.VELT_LOCATION_ID);if(i)return{id:i}}}return null}catch(t){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",t),null}}getAdditionalDocumentIdFromElement(e){try{return e?.closest(`[${N.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(N.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(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),kt(Jt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(e=>e||{}),kt(Jt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},t={},i=this.documentPaths$.value?.veltFolderId,a=this.documentPaths$.value?.allDocuments;if(i&&a)Object.values(e).forEach(l=>{l?.documentId&&l?.veltFolderId===i&&(t[l.documentId]=l)});else{let l=this.documentIds$.value;if(l?.length)l.forEach(s=>{let d=e?.[s.documentId];d&&(t[s.documentId]=d)});else if(this.documentPaths$.value?.documentId){let s=e?.[this.documentPaths$.value?.documentId];s&&(t[this.documentPaths$.value?.documentId]=s)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),kt(Jt))}setDocumentMetadata(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let i=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));i[e]=t,this.documentMetadata$.next(i)}catch(i){this.loggingService.catch("Error in DocService setDocumentMetadata:",i)}}setAllDocumentMetadata(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(e)}catch(t){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",t)}}getOrganizationMetadata(e){return this.organizationMetadata$.value?.[e]||null}getOrganizationMetadata$(e){return this.organizationMetadata$.asObservable().pipe(ge(t=>t?.[e]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ge(e=>e||{}),kt(Jt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(kt(Jt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(i){this.loggingService.catch("Error in DocService getMetadataFromType:",i);return}}getDefaultMetadata({clientDocumentId:e,documentId:t}){try{let i=this.documentPaths$.value;if(!i)return;let a=e||i.clientDocumentId,l=t||i.documentId,s=this.getDocumentMetadata(l);if(!s)return;let d=s?.folderId,v=s?.veltFolderId;return h(h({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),v?{veltFolderId:v}:{})}catch(i){this.loggingService.catch("Error in DocService getDefaultMetadata:",i);return}}getBaseMetadata(e,t){try{let i,a;t?.element?i=this.getAdditionalDocumentIdFromElement(t.element)||void 0:t?.clientDocumentId&&(i=t.clientDocumentId),i&&(a=this.generateDocumentId(i));let l=this.getMetadataFromType(e,t),s=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||s||{};return d.sdkVersion=fa(),d}catch(i){return this.loggingService.catch("Error in DocService getBaseMetadata:",i),{}}}getServerId({documentId:e,organizationId:t}){try{return e&&(e=this.generateDocumentId(e)),t&&(t=this.generateOrganizationId(t)),{documentId:e,organizationId:t}}catch(i){return this.loggingService.catch("Error in DocService getServerId:",i),null}}fetchDocuments(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchDocuments:",t),[]}})}fetchLocations(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(e?.folderId){let l=Pr(e?.folderId);i.push(ft("metadata.veltFolderId","==",l))}return e?.documentIds?.length&&!e?.allDocuments&&i.push(ft("metadata.documentId","in",e?.documentIds?.map(l=>this.generateDocumentId(l)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(e?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(t){return this.loggingService.catch("Error in DocService fetchLocations:",t),[]}})}updateDocuments(e){return J(this,null,function*(){try{if(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,documents:a,folderId:l}=e;if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let s=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],v=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=s,u.clientOrganizationId=i,u.clientDocumentId=u.documentId;let _=mi(u.documentId);u.documentId=_,u.apiKey=this.configService.getApiKey()??void 0,(l||this.documentPaths$.value?.folderId)&&(u.folderId=l||this.documentPaths$.value?.folderId,u.veltFolderId=Pr(l||this.documentPaths$.value?.folderId||""));let I=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=v?.[_];M?v[_]=h(h({},M),u):v[_]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:_,organizationId:s,field:"metadata"}});if(A?.errorCode&&(A={}),A&&A.apiKey&&A.folderId&&l&&A.folderId!=u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists with different folderId: ${A.folderId}`);continue}if(A&&A.apiKey&&!A.folderId&&u.folderId){this.loggingService.catch(`Error in updateDocuments: document ${u.clientDocumentId} already exists, move this document to folder with REST API`);continue}I(),u&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:u?.documentId??""})&&d.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{organizationId:s,documentId:_}}))}yield Promise.all(d),this.setAllDocumentMetadata(v)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,locations:a,documentIds:l}=e;if((!l||l.length===0)&&(l=this.documentIds$.value.map(u=>u.clientDocumentId)??[],l.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!a||a.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let s=l.map(u=>mi(u)),d=[],v=this.locationMetadata$.value;v||(v={}),s.forEach(u=>{a.forEach(_=>{let I=this.location$.value;if(_?.id===I?.location?.id&&this.location$.next({locationId:I?.locationId,location:_}),_?.id){delete _?.metadata;let A=YK(_.id),M=v?.[u],B=M?.[_.id];v&&(M||(v[u]={}),B||(v[u][_.id]={}),v[u][_.id]=y(h({},B),{location:_})),_&&this.commonDbService&&d.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:_})),properties:{organizationId:Pa(i),documentId:u,id:A}}))}})}),yield Promise.all(d),Object.keys(v||{}).length>0&&this.locationMetadata$.next(v)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return J(this,null,function*(){try{if(!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!e?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let a=[],l=this.generateOrganizationId(e?.organizationId);if(e?.folderId){let s=Pr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}}),i&&(i=[i]),a=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ft("metadata.veltParentFolderId","==",s)],folderId:s,apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}})}else i=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:l,documentId:this.documentPaths$.value?.documentId}});return{data:i,parentFolders:a}}catch(t){return this.loggingService.catch("Error in DocService getFoldersRequest:",t),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(be(e=>e?this.documentPaths$.pipe(be(t=>t?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:t.documentId,organizationId:t.organizationId,isCollection:!1}}).pipe(ge(i=>i?.data?.docIamConfig??i?.data),kt((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):se(null))):se(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?zr.RESTRICTED:zr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:zr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),zr.PUBLIC}}changeDocumentAccessType(e){return J(this,null,function*(){try{let t=this.documentPaths$.value;if(t){let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",field:"docIamConfig"}});if(i?.errorCode)return;switch(delete i.documentAccessType,i.features||(i.features={}),i.features.all||(i.features.all={}),e){case zr.PUBLIC:i.features.all.restricted=!1;break;case zr.RESTRICTED:i.features.all.restricted=!0,i.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(i)),properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??""}})}}catch(t){this.loggingService.catch("Error in DocService changeDocumentAccessType:",t)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(e){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",e),""}}setUIState(e){try{this.uiState.next(h(h({},this.uiState.value),e))}catch(t){this.loggingService.catch("Error in DocService setUIState:",t)}}getUIState$(){return this.uiState.asObservable()}};o.\u0275fac=function(t){return new(t||o)(X(st),X(qe),X($n),X(Be),X(Nt),X(k),X(rl),X(Gs),X(ol),X(tr),X(Do))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var An=(()=>{let o=class o{constructor(e,t,i,a,l){this.analyticsService=e,this.authService=t,this.coreActionsService=i,this.docService=a,this.loggingService=l,this.resolveOrganizationUsers=new Se(!0),this.resolveFolderUsers=new Se(!0),this.resolveDocumentUsers=new Se(!0),this.unresolvedUsers=new Se([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new Bn,this.userDataProvider$=new Se(null),this.anonymousUserDataProvider$=new Se(null),this.userIdByEmailCache={},this.userById$=new Se({}),this.userByIdCalled$=new Se({}),this.pendingResolutions=new Set,this.getUserById=s=>{try{return this.userById$.value?.[s]}catch(d){this.loggingService.catch("Error in UsersService getUserById:",d);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe($e(s=>!!s),be(()=>this.getUnresolvedUsers$().pipe($e(s=>s.length>0),Qr(300),ut(20),be(s=>{let d=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:d,isCollection:!0,useQuery:!0,firestoreQuery:[_r(ft("user.userId","in",s.slice(0,20)))]}}).pipe(ge(v=>v?.data),ln(v=>{if(v&&typeof v=="object"){delete v.undefined,delete v.null;let u=Object.values(v??{});this.setUserByIds(u.map(I=>I.user));let _=s.filter(I=>!u.some(A=>A.user.userId===I));_.length!==s.length&&this.setUnresolvedUsers(_)}})):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)}}setContactService(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=e}catch(t){this.loggingService.catch("Error in UsersService setContactService:",t)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(e){this.loggingService.catch("Error in UsersService ngOnDestroy:",e)}}isResolverForFeatureDisabled(e){let t=this.userDataProvider$.getValue();try{switch(e){case"allOrganizationUsers":return t?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return t?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return t?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(v){return J(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:s,moduleName:d}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let u=!1;if(i&&(u=this.isResolverForFeatureDisabled(i)),u)return{};{let _={},I=[],A={};if(e?.forEach(M=>{let B=this.getUserById(M);B?_[M]=B:this.userByIdCalled$.getValue()[M]?t&&I.push(M):(I.push(M),this.userByIdCalled$.next(y(h({},this.userByIdCalled$.getValue()),{[M]:!0})))}),I.length>0){let M=s||at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:gi.RESOLVE_USERS,source:"internal",payload:{userIds:I,organizationId:a,feature:i,forceResolve:t,skipUserCheck:l,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let B={};try{let q,ae=new Promise((Ce,oe)=>{q=setTimeout(()=>{oe(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)});B=yield Promise.race([this.getUsersFromDB({userIds:I,organizationId:a,skipUserCheck:l}).finally(()=>{clearTimeout(q)}),ae]),this.analyticsService.trackEvent(Y.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:I}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{result:B,userIds:I,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(q){this.loggingService.catch("Error in UsersService resolveUsers getUsers:",q,{userIds:I}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:M,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:q,userIds:I,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{I?.forEach(q=>{if(!B[q]){let ae=new Set([...this.getUnresolvedUsers(),q]);this.unresolvedUsers.next(Array.from(ae)),B[q]={userId:q,name:`User ${q}`}}})}Object.entries(B).forEach(([q,ae])=>{ae&&(_[q]=B?.[q],A[q]=B?.[q])})}return Object.keys(A).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(A)),this.userById$.next(h(h({},this.userById$.getValue()),A))),_}}catch(u){this.loggingService.catch("Error in UsersService resolveUsers:",u);let _=s||at();return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:gi.RESOLVE_USERS,moduleName:d,source:"internal",payload:{error:u,userIds:e,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(e){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",e),[]}}setUnresolvedUsers(e){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(e)){let t=JSON.parse(JSON.stringify(e));this.unresolvedUsers.next(t)}}catch(t){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",t)}}getUsersFromDB(a){return J(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let l=this.userDataProvider$.getValue();if(l){if(l.config?.getConfig?.url){if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),{};let u={organizationId:t,userIds:e},_=yield ji(l.config.getConfig.url,l.config.getConfig.headers,u,!0);return _.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${_.statusCode}. Message: ${_.message||"Unknown error"}`),{}):_.data??{}}let v=yield l.get(e);if(v&&typeof v=="object"&&"success"in v&&"statusCode"in v&&typeof v.success=="boolean"&&typeof v.statusCode=="number"){let u=v;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return v}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let s=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(s.flat());let d={};return s.forEach(v=>{v.forEach(u=>{u?.user?.userId&&(d[u.user.userId]=u.user)})}),d}catch(l){return this.loggingService.catch("Error in UsersService getUsersFromDB:",l),{}}})}getUsersFromDBWithBatching(a){return J(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let v=0;v<e.length;v+=30)l.push(e.slice(v,v+30));let s=l.map((v,u)=>J(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",v)],skipUserCheck:i}}))||[]}catch(_){return this.loggingService.catch(`Error in batch ${u+1}:`,_),[]}}));return yield Promise.all(s)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return J(this,arguments,function*({userIds:e,organizationId:t,resourceIds:i}){try{if(!e?.length||!i?.length)return[];let l=[];for(let M=0;M<e.length;M+=30)l.push(e.slice(M,M+30));let s=[];for(let M=0;M<i.length;M+=30)s.push(i.slice(M,M+30));let d=[],v=0,u=(M,B)=>J(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[_r(ft("userId","in",M),ft("veltResourceId","in",B))]}}))??[])||[]}catch(q){return this.loggingService.catch(`Error in batch ${v+1}:`,q),[]}});for(let M of l)for(let B of s)d.push(u(M,B)),v++;return(yield Promise.all(d)).flat().filter((M,B,q)=>B===q.findIndex(ae=>ae.userId===M.userId&&ae.resourceId===M.resourceId))}catch(l){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",l),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),this.userById$.asObservable().pipe(kt(Jt))}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(i=>{t[i.userId]=h(h({},t?.[i.userId]??{}),i)}),this.userById$.next(t)}catch(t){this.loggingService.catch("Error in UsersService setUserByIds:",t)}}setUserDataProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let t=e.config?.getConfig?.url,i="get"in e&&typeof e.get=="function";if(!t&&!i){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(e),e.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),e.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),e.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(t){this.loggingService.catch("Error in UsersService setUserDataProvider:",t)}}setAnonymousUserDataProvider(e){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in e)||typeof e.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",t)}}resolveUserIdsByEmail(i){return J(this,arguments,function*({emails:e,uniqueId:t}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!e?.length)return{};let a=this.anonymousUserDataProvider$.getValue();if(!a||typeof a.resolveUserIdsByEmail!="function")return{};let l=[...new Set(e.filter(oe=>!!oe))];if(l.length===0)return{};let s={},d=[];if(l.forEach(oe=>{let fe=this.userIdByEmailCache[oe];fe?s[oe]=fe:d.push(oe)}),d.length===0)return s;let v=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",_=this.docService.getDocumentPaths()?.folderId||"",I={organizationId:v,documentId:u,folderId:_,emails:d},A=t||at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:v,documentId:u,folderId:_}});let M=a.config?.resolveTimeout||this.resolveTimeout,B,q=new Promise((oe,fe)=>{B=setTimeout(()=>{fe(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},Ce=J(this,null,function*(){try{let oe=yield Ai(()=>a.resolveUserIdsByEmail(I),"resolveUserIdsByEmail",ae);return oe?.statusCode===200&&oe?.data?oe.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${oe?.statusCode}. Message: ${oe?.message||"Unknown error"}`),{})}finally{clearTimeout(B)}});try{let oe=yield Promise.race([Ce,q]);return Object.entries(oe).forEach(([fe,Ie])=>{Ie&&(this.userIdByEmailCache[fe]=Ie,s[fe]=Ie,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:Ie,name:fe,email:fe},currentUserId:this.authService.getUser()?.userId??""}).catch(xe=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",xe)}))}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:oe,emails:d}}),s}catch(oe){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",oe),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:oe,emails:d}}),s}}catch(a){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",a),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",e),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(e){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(st),X(qe),X(tr),X(ct),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var yp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return it.error("Error in isTestingDb:",r),!1}}};var cv=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=s,this.attachmentResolverService=d,this.coreActionsService=v,this.notificationActionTypeMap={[At.NEWLY_ADDED]:Io.COMMENT_ANNOTATION_ADD,[At.ADDED]:Io.COMMENT_ADD,[At.UPDATED]:Io.COMMENT_UPDATE,[At.DELETED]:Io.COMMENT_DELETE}}setNotificationService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",t)}}setUserPermissionService(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=e}catch(t){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",t)}}getUserIdsToResolveFromComments(e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let t=new Set;for(let i of e){if(i?.from?.userId&&t.add(i?.from?.userId),i?.comments)for(let a of i?.comments){if(a?.from?.userId&&t.add(a?.from?.userId),a?.to)for(let l of a?.to)l?.userId&&t.add(l?.userId);if(a?.taggedUserContacts)for(let l of a?.taggedUserContacts)l?.userId&&t.add(l?.userId)}if(i?.assignedTo?.userId&&t.add(i?.assignedTo?.userId),i?.resolvedByUserId&&t.add(i?.resolvedByUserId),i?.subscribedUsers)for(let a of Object.values(i?.subscribedUsers))a.user.userId&&t.add(a.user.userId);if(i?.unsubscribedUsers)for(let a of Object.values(i?.unsubscribedUsers))a.user.userId&&t.add(a.user.userId)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",t),[]}}mergeCommentWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.comments)for(let t of e?.comments){if(t?.from?.userId){let a=this.usersService.getUserById(t?.from?.userId);a&&(t.from=a)}t?.to&&(t.to=t?.to?.map(a=>{if(a?.userId){let l=this.usersService.getUserById(a?.userId);if(l)return h(h({},a),l)}return a})),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(a=>{if(a?.contact){let l=this.usersService.getUserById(a?.contact?.userId);l&&(a.contact=l,(l?.name||l?.email)&&(a.text=`@${l?.name||l?.email}`))}return a}));let i=t?.taggedUserContacts?.filter((a,l,s)=>s.findIndex(d=>d.text===a.text)===l)||[];i.sort((a,l)=>(l.text?.length||0)-(a.text?.length||0)),i.forEach(a=>{if(a?.text){let l=new RegExp(Qc(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(Qc(`@User ${a.userId}`),"g")),t.commentText=t.commentText?.replaceAll(l,a.text),t.commentHtml=t.commentHtml?.replaceAll(l,a.text)}})}if(e?.assignedTo?.userId){let t=this.usersService.getUserById(e?.assignedTo?.userId);t&&(e.assignedTo=t)}if(e?.resolvedByUserId){let t=this.usersService.getUserById(e?.resolvedByUserId);t&&(e.resolvedByUser=t)}if(e?.subscribedUsers)for(let t of Object.values(e?.subscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.subscribedUsers?.id?.user&&(e.subscribedUsers.id.user=i)}if(e?.unsubscribedUsers)for(let t of Object.values(e?.unsubscribedUsers)){let i=this.usersService.getUserById(t.user.userId);i&&e?.unsubscribedUsers?.id?.user&&(e.unsubscribedUsers.id.user=i)}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",t),e}}formatCommentData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),e?.comments?.forEach(t=>{t?.commentText&&t?.commentText?.length>0&&(t.isCommentTextAvailable=!0)}),e?.viewedBy&&delete e.viewedBy,e?.unread!==void 0&&delete e.unread,e?.resolvedByUser!==void 0&&delete e.resolvedByUser,e?.comments&&e.comments.forEach(t=>{t?.reactionAnnotations&&delete t.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.assignedTo?.userId&&(e.assignedTo={userId:e.assignedTo.userId}),e?.subscribedUsers)for(let t of Object.keys(e?.subscribedUsers))e.subscribedUsers[t].user={userId:e?.subscribedUsers[t].user.userId};if(e?.unsubscribedUsers)for(let t of Object.keys(e?.unsubscribedUsers))e.unsubscribedUsers[t].user={userId:e?.unsubscribedUsers[t].user.userId}}return e?.comments&&(e.comments=e?.comments?.map(t=>this.formatCommentThreadData(t))),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",t),e}}mergeStrippedDataWithCommentAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.annotationId),i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=this.commentAnnotationsResolverService.getFieldsToRemove();return t&&(e?.comments?.forEach(l=>{let s=t?.comments?.[l?.commentId];if(s){l.commentHtml=s?.commentHtml,l.commentText=s?.commentText;let d=s?.attachments;i&&d&&l.attachments?.forEach(v=>{let u=v?.attachmentId;d?.[u]&&(v.name=d?.[u]?.name,v.url=d?.[u]?.url)})}}),t?.targetTextRange?.text&&e?.targetTextRange&&(e.targetTextRange.text=t?.targetTextRange?.text),a?.length>0&&a.forEach(l=>{t?.[l]&&(e[l]=t[l])})),e}catch(t){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",t),e}}mergeLocationWithCommentAnnotations(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let i=e?.location?.id,a=e?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.location=l?.location),e}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",i),e}}isCommentsDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let i=this.commentAnnotationsResolverService.getCommentAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",i),!0}}stripCommentsFromAnnotationData({comment:e}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let t=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!t)return e;let i=this.attachmentResolverService.attachmentDataProviderAvailable(),a=new kc;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(s=>(s.isAttachmentResolverUsed=!0,delete s?.name,delete s?.url,s));a.attachments=l}return delete a?.commentHtml,delete a?.commentText,a}catch(t){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",t),e}}resolveTaggedUserEmails(e){return J(this,null,function*(){try{let t=new Set;if(e.comments?.forEach(i=>{i.taggedUserContacts?.forEach(a=>{a?.contact?.email&&!a?.userId&&t.add(a.contact.email)}),i.to?.forEach(a=>{a?.email&&!a?.userId&&t.add(a.email)})}),t.size>0){let i=at();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(t)}});let a=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(t),uniqueId:i});Object.keys(a).length>0&&e.comments?.forEach(l=>{l.taggedUserContacts?.forEach(s=>{if(s?.contact?.email&&!s?.userId){let d=a[s.contact.email];if(d){let v=s.text;if(v){let u=Qc(v),_=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(_,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(_,`{{${d}}}`))}s.userId=d,s.contact.userId=d,delete s.contact?.email,delete s.contact?.visibility,s.text=""}}}),l.to=l.to?.map(s=>{if(s?.email&&!s?.userId){let d=a[s.email];if(d)return delete s?.email,delete s?.visibility,y(h({},s),{userId:d})}return s})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return J(this,arguments,function*({data:e,actionType:t,commentId:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),e=yield this.resolveTaggedUserEmails(e),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let l=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),v;t&&(v=this.notificationActionTypeMap?.[t]);let u={},_=null,I=!1;if(e&&e.annotationId){let M=e.annotationId;if(u[M]=h(h(h(h({annotationId:M,metadata:ti(e.metadata??{}),comments:{}},e?.from&&{from:e?.from}),e?.assignedTo&&{assignedTo:e?.assignedTo}),e?.resolvedByUserId&&{resolvedByUserId:e?.resolvedByUserId}),e?.targetTextRange?.text&&{targetTextRange:{text:e?.targetTextRange?.text}}),delete e?.targetTextRange?.text,s?.length>0&&s.forEach(q=>{e?.[q]&&(u[M][q]=e[q],delete e[q])}),d?.length)for(let q of d)e?.[q]!==void 0&&(u[M][q]=JSON.parse(JSON.stringify(e[q])));e.comments?.forEach(q=>{if(q.commentId){let ae;l&&(ae={},q.attachments?.forEach(Ce=>{ae[Ce.attachmentId]={attachmentId:Ce.attachmentId,name:Ce.name,url:Ce.url}})),u[M].comments[q.commentId]=h(h(h(h(h(h({commentId:q.commentId},q?.commentHtml&&{commentHtml:q?.commentHtml}),q?.commentText&&{commentText:q?.commentText}),ae&&{attachments:ae}),q?.from&&{from:q?.from}),q?.to&&{to:q?.to}),q?.taggedUserContacts&&{taggedUserContacts:q?.taggedUserContacts})}}),I=this.isCommentsDataChanged(u[M],M);let B=new Br;Object.assign(B,e),B.comments=e.comments?.map(q=>this.stripCommentsFromAnnotationData({comment:q}))||[],_=B}let A=_?.comments?.find(M=>M.commentId===i);return A?.isDraft&&(v=_?.comments?.length&&_?.comments?.length>0?Io.COMMENT_ADD:Io.COMMENT_ANNOTATION_ADD),{strippedData:I&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:_,eventType:v}}catch(l){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",l),{strippedData:null,originalData:null}}})}formatCommentThreadData(e){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to&&(e.to=e?.to?.map(i=>i?.userId?{userId:i.userId}:i)),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(i=>i?.contact?.userId?y(h({},i),{contact:{userId:i.contact.userId}}):i));let t=e?.taggedUserContacts?.filter((i,a,l)=>l.findIndex(s=>s.text===i.text)===a)||[];t.sort((i,a)=>(a.text?.length||0)-(i.text?.length||0)),t.forEach(i=>{if(i?.text&&i?.contact?.userId){let a=new RegExp(Qc(i.text),"g");e.commentText=e.commentText?.replaceAll(a,l=>`{{${i.userId}}}`),e.commentHtml=e.commentHtml?.replaceAll(a,l=>`{{${i.userId}}}`)}}),t.forEach(i=>{i?.text&&i?.contact?.userId&&(i.text="")})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",t),e}}getDeniedForYouUsers(t){return J(this,arguments,function*({extraData:e}){try{let i=Object.values(e?.annotationData?.subscribedUsers||{}).map(l=>l.user.userId)??[],a=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&i.length){let l=e?.metadata?.clientDocumentId,s=e?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?e?.annotationData?.context?.access:null,d=[];i.forEach(_=>{if(d.push({userId:_,resource:{id:l,type:oa.DOCUMENT,source:oo.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:s?{access:s}:void 0}}),s){let I=JSON.stringify(s);d.push({userId:_,resource:{id:I,type:oa.CONTEXT,source:oo.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:s}}})}});let v=at();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:oo.SET_NOTIFICATIONS,uniqueId:v,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:v,methodName:oo.SET_NOTIFICATIONS});u?.success&&u?.data?.length&&u.data.forEach(_=>{_.hasAccess||a.push(_.userId)})}return a}catch(i){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",i),[]}})}handleCommentEncryption(s){return J(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let d=DN(this.authService.getFirebaseConfig()?.firebaseOptions),v=Gr(this.functions,Wr({url:En.cloudFunction?.[d]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3});if(i){i=this.notificationService?.processNotificationData(i),i.annotationData=e;let M=i?.targetAnnotationData?.commentId;if(M){let B=e?.comments?.find(q=>q?.commentId===M);B&&(i.targetAnnotationData=B)}try{let B=yield this.stripCommentAnnotationData({data:i.annotationData,actionType:i?.actionType??At.NEWLY_ADDED});B?.originalData&&(i.annotationData=this.formatCommentData(B.originalData)),i?.targetAnnotationData&&(i.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:i.targetAnnotationData})))}catch(B){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",B)}}let u=yp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),_=yield this.getDeniedForYouUsers({extraData:i}),I={path:t??"",data:e??{},dbId:u??"",notificationData:i||void 0,notificationURL:En.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:fa(),deniedForYouUsers:_,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield fc(I,this.authService.getUser()?.userId??"");yield v({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(qe),X(Do),X(Nt),X(rl),X(zs),X(tr))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var NL=(()=>{let o=class o{constructor(e,t,i,a,l,s){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=s}getUserIdsToResolveFromReactions(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i?.from?.userId),i?.reactions?.length)for(let a of i?.reactions)a?.from?.userId&&t.add(a?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}handleReactionEncryption(a){return J(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=DN(this.authService.getFirebaseConfig()?.firebaseOptions),s=Gr(this.functions,Wr({url:En.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=yp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),v=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:fa()},_=yield fc(u,v);yield s({veltData:_})}catch(l){this.loggingService.catch("Error in handleReactionEncryption:",l)}})}mergeReactionWithUser(e){try{if(this.usersService.userDataProviderAvailable()){if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.reactions?.length){for(let t of e?.reactions)if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}}}return e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",t),e}}formatReactionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e.reactions=e?.reactions?.map(t=>(this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t)),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",t),e}}isReactionDataChanged(e,t){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t);return i?!Mr(e,i):!0}catch(i){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",i),!0}}stripReactionAnnotationData(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:e,strippedData:null};let t={};if(e&&e.annotationId){let i=e.annotationId;if(t[i]=h({annotationId:i,metadata:ti(e.metadata??{}),icon:e.icon},e?.from&&{from:e?.from}),!this.isReactionDataChanged(t[i],i))return{strippedData:null,originalData:e};delete e?.icon,e.isReactionResolverUsed=!0}return{strippedData:t,originalData:e}}catch(t){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",t),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(e){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return e;let t=this.reactionAnnotationsResolverService.getReactionAnnotationById(e?.annotationId);return t&&t.icon&&(e.icon=t.icon),e}catch(t){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(qe),X(Do),X(Nt),X(Gs))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kp=(()=>{let o=class o{constructor(e,t,i,a){this.authService=e,this.loggingService=t,this.usersService=i,this.recorderAnnotationsResolverService=a}getUserIdsToResolveFromRecorders(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId),i?.transcription?.from?.userId&&t.add(i?.transcription?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in RecorderUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeRecorderWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}if(e?.transcription?.from?.userId){let t=this.usersService.getUserById(e?.transcription?.from?.userId);t&&(e.transcription.from=t)}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeRecorderWithUser:",t),e}}formatRecorderData(e,t){try{return e.transcription=e?.transcription?y(h({},e.transcription),{lastUpdated:t}):void 0,this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.transcription?.from?.userId&&(e.transcription.from={userId:e.transcription.from.userId})),e}catch(i){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderData:",i),e}}formatRecorderDataForWhisperTranscription(e){try{return this.usersService.userDataProviderAvailable()&&e?.fromUser?.userId&&(e.fromUser={userId:e.fromUser?.userId}),e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService formatRecorderDataForWhisperTranscription:",t),e}}encryptRecorderAnnotation(e){return J(this,null,function*(){try{return yield fc(e,this.authService.getUser()?.userId??"")}catch(t){this.loggingService.catch("Error in RecorderUtilsService encryptRecorderAnnotation:",t);return}})}stripRecorderAnnotationData({data:e,actionType:t}){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())return{strippedData:null,originalData:e};let i=e?.annotationId;if(!i)return{strippedData:null,originalData:e};let a=this.recorderAnnotationsResolverService.getAdditionalFields(),l={annotationId:i,metadata:ti(e.metadata??{})};if(e?.from&&(l.from=JSON.parse(JSON.stringify(e.from))),e?.transcription&&(l.transcription=JSON.parse(JSON.stringify(e.transcription))),e?.attachment!==void 0&&(l.attachment=e.attachment?JSON.parse(JSON.stringify(e.attachment)):null),e?.attachments?.length&&(l.attachments=JSON.parse(JSON.stringify(e.attachments))),e?.chunkUrls&&Object.keys(e.chunkUrls).length>0&&(l.chunkUrls=JSON.parse(JSON.stringify(e.chunkUrls))),e?.recordingEditVersions){let d={};for(let[v,u]of Object.entries(e.recordingEditVersions)){let _=Number(v),I={};u?.from&&(I.from=JSON.parse(JSON.stringify(u.from))),u?.attachment!==void 0&&(I.attachment=u.attachment?JSON.parse(JSON.stringify(u.attachment)):null),u?.attachments?.length&&(I.attachments=JSON.parse(JSON.stringify(u.attachments))),u?.transcription&&(I.transcription=JSON.parse(JSON.stringify(u.transcription))),Object.keys(I).length>0&&(d[_]=I)}Object.keys(d).length>0&&(l.recordingEditVersions=d)}if(e?.isUrlAvailable!==void 0&&(l.isUrlAvailable=e.isUrlAvailable),a?.length)for(let d of a)e?.[d]!==void 0&&(l[d]=JSON.parse(JSON.stringify(e[d])));if(e?.from?.userId&&(e.from={userId:e.from.userId}),delete e.transcription,e?.attachments?.length&&(e.attachments=e.attachments.map(d=>({attachmentId:d?.attachmentId,name:d?.name,bucketPath:d?.bucketPath}))),e.attachment=null,e?.chunkUrls&&(e.chunkUrls={}),e?.recordingEditVersions)for(let[,d]of Object.entries(e.recordingEditVersions))d?.from?.userId&&(d.from={userId:d.from.userId}),d.attachment=null,d?.attachments?.length&&(d.attachments=d.attachments.map(v=>({attachmentId:v?.attachmentId,name:v?.name,bucketPath:v?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let s;return t===Hl.ADDED?s=Io.RECORDER_ANNOTATION_ADD:t===Hl.UPDATED?s=Io.RECORDER_ANNOTATION_UPDATE:t===Hl.DELETED&&(s=Io.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:s}}catch(i){return this.loggingService.catch("Error in RecorderUtilsService stripRecorderAnnotationData:",i),{strippedData:null,originalData:e}}}mergeStrippedDataWithRecorderAnnotation(e){try{if(!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e?.annotationId)return e;let t=this.recorderAnnotationsResolverService.getAnnotationById(e.annotationId);if(!t)return e;if(t.from&&(e.from=t.from),t.transcription&&(e.transcription=t.transcription),t.attachments?.length&&(e.attachments=t.attachments),t.attachment!==void 0&&(e.attachment=t.attachment),t.chunkUrls&&Object.keys(t.chunkUrls).length>0&&(e.chunkUrls=t.chunkUrls),t.recordingEditVersions&&e.recordingEditVersions)for(let[i,a]of Object.entries(t.recordingEditVersions)){let l=Number(i);e.recordingEditVersions[l]&&(a.from&&(e.recordingEditVersions[l].from=a.from),a.attachment!==void 0&&(e.recordingEditVersions[l].attachment=a.attachment),a.attachments?.length&&(e.recordingEditVersions[l].attachments=a.attachments),a.transcription&&(e.recordingEditVersions[l].transcription=a.transcription))}return e}catch(t){return this.loggingService.catch("Error in RecorderUtilsService mergeStrippedDataWithRecorderAnnotation:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(qe),X(k),X(An),X(ol))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var xp=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Se(null),this.activityById$=new Se({}),this.fieldsToRemove=[],this.getActivityById=a=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in ActivityResolverService getActivityById:",l);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.saveRetryConfig&&(this.retrySaveConfig=a.config.saveRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove))})}catch(a){this.loggingService.catch("Error in ActivityResolverService constructor:",a)}}getProvider(){try{let e=this.activityDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in ActivityResolverService getProvider:",e);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(e){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",e)}}resolveActivities(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let ae=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:e}}),_(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=[...new Set(e.activityIds||[])],B=y(h({},e),{activityIds:M});J(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:B}});let Ce=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(oe=>s?{}:(v(),oe&&oe.statusCode!==200?(this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:oe,request:B}}),this.loggingService.catch(oe?.message??"Error in ActivityResolverService resolveActivities:"),{}):oe?.data)).catch(oe=>{throw v(),oe});try{A=(yield Ce)||{},this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let oe={};Object.entries(A).forEach(([fe,Ie])=>{let xe=this.activityById$.value?.[fe];xe?xe&&JSON.stringify(xe)!==JSON.stringify(Ie)&&(oe[fe]=Ie):oe[fe]=Ie}),Object.keys(oe).length>0&&this.activityById$.next(h(h({},this.activityById$.getValue()),oe)),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:oe,request:B}}),u(oe)}catch(oe){let fe=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:fe,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:oe,request:B}}),s||_(oe),u(A)}}else v(),u({})}catch(ae){v();let Ce=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:us.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let i=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let a=t||at();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{request:e}});let l=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=h(h({},l),e.activity);let s=yield Ai(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return ji(i.config.saveConfig.url,i.config.saveConfig.headers,d,!1)}return i?.save?.({activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(s?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{error:s,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(e.activity),event:e.event}),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ActivityResolverService saveActivity:",i);let a=t||at();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:us.SAVE_ACTIVITY,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),se(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(e){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",e),this.fieldsToRemove}}setActivityDataProvider(e){try{if(e){this.loggingService.log("Setting activity data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.activityDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",t)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mS=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=s,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=v,this.activityResolverService=u}getActivityDisplayMessage(e){try{switch(e.featureType){case"comment":return this.getCommentDisplayMessage(e);case"recorder":return this.getRecorderDisplayMessage(e);case"reaction":return this.getReactionDisplayMessage(e);case"crdt":return this.getCrdtDisplayMessage(e);case"custom":return e.displayMessageTemplate&&e.displayMessageTemplateData?this.resolveTemplate(e.displayMessageTemplate,e.displayMessageTemplateData):"";default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",t),""}}resolveTemplate(e,t){try{return e.replace(/\{\{([\w.]+)\}\}/g,(i,a)=>{let l=a.split(".").reduce((s,d)=>{if(s!=null&&typeof s=="object")return s[d]},t);return l!=null?String(l):""})}catch(i){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",i),e}}buildActivityDataFromExtraData(e){try{let{feature:t,extraData:i}=e;if(!i?.actionType)return null;switch(t){case"comment":return this.buildCommentActivityData({commentAnnotation:i.annotationData,targetComment:i.targetAnnotationData,actionType:i.actionType,otherFields:i});case"recorder":return this.buildRecorderActivityData(i);case"reaction":return this.buildReactionActivityData(i);default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",t),null}}stripActivityPII(e){return J(this,null,function*(){try{let t=JSON.parse(JSON.stringify(e));if(delete t.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:t};t.actionUser?.userId&&(t.actionUser={userId:t.actionUser.userId}),t.changes&&this.stripUsersFromChanges(t.changes),t.displayMessageTemplateData&&this.stripUsersFromTemplateData(t.displayMessageTemplateData);let i=this.extractCommentChangesForResolver(t),a=this.extractFeatureEntityDataForResolver(t);yield this.stripFeatureSpecificPII(t);let l=this.extractActivityResolverData(t);return i&&(l?l.changes=h(h({},l.changes),i.changes):l=i),a&&(l?(a.entityData!==void 0&&(l.entityData=a.entityData),a.entityTargetData!==void 0&&(l.entityTargetData=a.entityTargetData)):l=a),l&&(t.isActivityResolverUsed=!0),{strippedActivity:t,activityResolverData:l}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",t),{strippedActivity:e}}})}mergeActivityWithUser(e){try{if(!this.usersService.userDataProviderAvailable())return e;if(e=JSON.parse(JSON.stringify(e)),e.actionUser?.userId){let t=this.usersService.getUserById(e.actionUser.userId);t&&(e.actionUser=t)}return e.changes&&this.rehydrateUsersInChanges(e.changes),e.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(e.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(e),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",t),e}}mergeActivityWithFeatureData(e){try{switch(e.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(e);case"reaction":return this.mergeActivityWithReactionData(e);case"recorder":return this.mergeActivityWithRecorderData(e);default:return e}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",t),e}}getUserIdsToResolveFromActivities(e){try{let t=new Set;for(let i of e){if(i.actionUser?.userId&&t.add(i.actionUser.userId),i.changes)for(let a of Object.values(i.changes))a&&(this.extractUserIdFromValue(a.from,t),this.extractUserIdFromValue(a.to,t));if(i.displayMessageTemplateData)for(let a of Object.values(i.displayMessageTemplateData))this.extractUserIdFromValue(a,t);this.extractFeatureSpecificUserIds(i,t)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",t),[]}}getEntityIdsToResolveFromActivities(e,t){try{let i=new Set;for(let a of e)if(!(t&&a.featureType!==t))switch(a.featureType){case"comment":case"reaction":case"recorder":a.targetEntityId&&i.add(a.targetEntityId);break}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",i),[]}}stripFeatureSpecificPII(e){return J(this,null,function*(){try{switch(e.featureType){case"comment":yield this.stripCommentPII(e);break;case"reaction":this.stripReactionPII(e);break;case"recorder":this.stripRecorderPII(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",t)}})}extractActivityResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let t={id:e.id},i=!1;if(e.featureType==="custom"){let a=this.activityResolverService.getFieldsToRemove();for(let l of a)l in e&&e[l]!==void 0&&(t[l]=e[l],delete e[l],i=!0)}return e.metadata&&(t.metadata=ti(e.metadata)),i?t:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",t);return}}extractCommentChangesForResolver(e){try{return!this.activityResolverService.activityDataProviderAvailable()||e.featureType!=="comment"||!e.changes?.commentText?void 0:{id:e.id,changes:{commentText:e.changes.commentText},metadata:e.metadata?ti(e.metadata):void 0}}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",t);return}}extractFeatureEntityDataForResolver(e){try{if(!this.activityResolverService.activityDataProviderAvailable()||!e.entityData)return;let t=e.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),i=e.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!t&&!i)return;let a={id:e.id,metadata:e.metadata?ti(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let s=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}if(i){let s=this.reactionUtilsService.stripReactionAnnotationData(l);if(s?.strippedData){let d=Object.keys(s.strippedData)[0];d&&(a.entityData=s.strippedData[d])}}return a.entityData?a:void 0}catch(t){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",t);return}}mergeActivityWithResolverData(e){try{if(!this.activityResolverService.activityDataProviderAvailable())return e;let t=this.activityResolverService.getActivityById(e.id);if(!t)return e;t.changes&&(e.changes||(e.changes={}),Object.assign(e.changes,t.changes)),t.entityData!==void 0&&(e.entityData=t.entityData),t.entityTargetData!==void 0&&(e.entityTargetData=t.entityTargetData),t.displayMessageTemplateData&&(e.displayMessageTemplateData||(e.displayMessageTemplateData={}),Object.assign(e.displayMessageTemplateData,t.displayMessageTemplateData));let i=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[a,l]of Object.entries(t))!i.has(a)&&l!==void 0&&(e[a]=l);return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",t),e}}rehydrateFeatureSpecificUserData(e){try{switch(e.featureType){case"comment":this.rehydrateCommentUserData(e);break;case"reaction":this.rehydrateReactionUserData(e);break;case"recorder":this.rehydrateRecorderUserData(e);break}}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",t)}}getCommentDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case qr.ANNOTATION_ADD:return`${t} added a comment`;case qr.COMMENT_ADD:return`${t} replied to a comment`;case qr.COMMENT_UPDATE:return`${t} edited a comment`;case qr.COMMENT_DELETE:return`${t} deleted a comment`;case qr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case qr.STATUS_CHANGE:{let i=e.changes?.status,a=i?.from?.name,l=i?.to?.name;return a&&l?`${t} changed status from ${a} to ${l}`:`${t} changed the status`}case qr.PRIORITY_CHANGE:{let i=e.changes?.priority,a=i?.to;if(!a)return`${t} removed the priority`;let l=typeof a=="object"?a?.name:String(a),s=i?.from,d=s&&typeof s=="object"?s?.name:s?String(s):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case qr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case qr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case qr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case qr.APPROVE:return`${t} approved the comment`;case qr.ACCEPT:return`${t} accepted a suggestion`;case qr.REJECT:return`${t} rejected a suggestion`;case qr.REACTION_ADD:return`${t} reacted to a comment`;case qr.REACTION_DELETE:return`${t} removed a reaction`;case qr.SUBSCRIBE:return`${t} subscribed to the thread`;case qr.UNSUBSCRIBE:return`${t} unsubscribed from the thread`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",t),""}}getRecorderDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case mO.RECORDING_ADD:return`${t} added a recording`;case mO.RECORDING_DELETE:return`${t} deleted a recording`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",t),""}}getReactionDisplayMessage(e){try{let t=e.actionUser?.name??"Someone";switch(e.actionType){case vO.REACTION_ADD:return`${t} added a reaction`;case vO.REACTION_DELETE:return`${t} removed a reaction`;default:return""}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",t),""}}getCrdtDisplayMessage(e){try{let t=e.actionUser?.name??"Someone",a=e.entityData?.editCount??0,l=e.targetEntityId??"unknown";return`${t} made ${a} edit${a!==1?"s":""} to editor ${l}`}catch(t){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",t),""}}stripCommentPII(e){return J(this,null,function*(){try{let t=yield this.commentUtilsService.stripCommentAnnotationData({data:e.entityData,actionType:e.eventType??At.NEWLY_ADDED});t?.originalData&&(e.entityData=this.commentUtilsService.formatCommentData(t.originalData)),e.entityTargetData&&(e.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:e.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&e.changes?.commentText&&delete e.changes.commentText}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",t)}})}rehydrateCommentUserData(e){try{e.entityData&&this.commentUtilsService.mergeCommentWithUser(e.entityData),e.entityTargetData&&(this.rehydrateUserInObject(e.entityTargetData,"from"),this.rehydrateUsersInArray(e.entityTargetData,"to"),this.rehydrateUsersInArray(e.entityTargetData,"taggedUserContacts"))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",t)}}stripReactionPII(e){try{if(!e.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(e.entityData),e.entityData=this.reactionUtilsService.formatReactionData(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",t)}}rehydrateReactionUserData(e){try{if(!e.entityData)return;this.reactionUtilsService.mergeReactionWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",t)}}stripRecorderPII(e){try{if(!e.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.recorderUtilsService.stripRecorderAnnotationData({data:e.entityData});return}let t=e.entityData;if(this.usersService.userDataProviderAvailable()){t.from&&typeof t.from=="object"&&"userId"in t.from&&(t.from={userId:t.from.userId});let i=t.transcription;i?.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",t)}}rehydrateRecorderUserData(e){try{if(!e.entityData)return;this.recorderUtilsService.mergeRecorderWithUser(e.entityData)}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",t)}}mergeActivityWithCommentAnnotationData(e){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e.targetEntityId);if(!t)return e;let i=e.entityData?.comments;if(Array.isArray(i))for(let a of i){let l=a?.commentId;if(l==null)continue;let s=t.comments?.[String(l)];s&&(s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml))}if(e.targetSubEntityId&&e.entityTargetData){let a=t.comments?.[e.targetSubEntityId];if(a){let l=e.entityTargetData;a.commentText&&(l.commentText=a.commentText),a.commentHtml&&(l.commentHtml=a.commentHtml)}}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",t),e}}mergeActivityWithReactionData(e){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",t),e}}mergeActivityWithRecorderData(e){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!e.targetEntityId||!e.entityData||this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(e.entityData),e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",t),e}}buildCommentActivityData(e){try{let{commentAnnotation:t,targetComment:i,actionType:a,otherFields:l}=e,s=t,d=i,v=a===At.DELETED&&l?.isAnnotationDelete?qr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!v)return null;let u=s?.annotationId;if(!u)return null;let _=d?.commentId,I=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:v,targetEntityId:u,eventType:a,targetSubEntityId:_??null,changes:Object.keys(I).length>0?I:void 0,entityData:t,entityTargetData:i??void 0}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",t),null}}mapCommentStatusToActionType(e){try{switch(e){case At.NEWLY_ADDED:return qr.ANNOTATION_ADD;case At.ADDED:return qr.COMMENT_ADD;case At.UPDATED:return qr.COMMENT_UPDATE;case At.DELETED:return qr.COMMENT_DELETE;case At.STATUS_CHANGED:return qr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return qr.PRIORITY_CHANGE;case At.ASSIGNED:return qr.ASSIGN;case At.ACCESS_MODE_CHANGED:return qr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return qr.CUSTOM_LIST_CHANGE;case At.APPROVED:return qr.APPROVE;case At.ACCEPTED:return qr.ACCEPT;case At.REJECTED:return qr.REJECT;case At.REACTION_ADDED:return qr.REACTION_ADD;case At.REACTION_DELETED:return qr.REACTION_DELETE;case At.SUBSCRIBED:return qr.SUBSCRIBE;case At.UNSUBSCRIBED:return qr.UNSUBSCRIBE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",t),null}}buildRecorderActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapRecorderStatusToActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"recorder",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",t),null}}mapRecorderStatusToActionType(e){try{switch(e){case Hl.ADDED:return mO.RECORDING_ADD;case Hl.DELETED:return mO.RECORDING_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",t),null}}buildReactionActivityData(e){try{let t=e.annotationData,i=e.actionType,a=this.mapReactionActionType(i);if(!a)return null;let l=t?.annotationId;return l?{featureType:"reaction",actionType:a,targetEntityId:l,entityData:t}:null}catch(t){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",t),null}}mapReactionActionType(e){try{switch(e){case"add":return vO.REACTION_ADD;case"delete":return vO.REACTION_DELETE;default:return null}}catch(t){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",t),null}}buildCommentChanges(e,t,i){try{let a={};switch(e){case At.NEWLY_ADDED:case At.ADDED:a.commentText={from:null,to:t?.commentText??null};break;case At.UPDATED:a.commentText={from:i?.oldCommentText??null,to:t?.commentText??null};break;case At.DELETED:a.commentText={from:t?.commentText??null,to:null};break;case At.STATUS_CHANGED:a.status={from:i?.oldStatus??null,to:i?.newStatus??null};break;case At.PRIORITY_CHANGED:a.priority={from:i?.oldPriority??null,to:i?.newPriority??null};break;case At.ASSIGNED:{a.assignedTo={from:i?.oldAssignedTo??null,to:i?.newAssignedTo??null};break}case At.ACCESS_MODE_CHANGED:a.accessMode={from:i?.oldAccessMode??null,to:i?.newAccessMode??null};break;case At.CUSTOM_LIST_CHANGED:a.customList={from:i?.oldCustomList??null,to:i?.newCustomList??null};break}return a}catch(a){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",a),{}}}extractFeatureSpecificUserIds(e,t){try{switch(e.featureType){case"comment":this.extractCommentActivityUserIds(e,t);break;case"reaction":this.extractReactionActivityUserIds(e,t);break;case"recorder":this.extractRecorderActivityUserIds(e,t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",i)}}extractCommentActivityUserIds(e,t){try{if(e.entityData){let i=this.commentUtilsService.getUserIdsToResolveFromComments([e.entityData]);for(let a of i)t.add(a)}if(e.entityTargetData){let i=e.entityTargetData;if(this.extractUserIdFromValue(i.from,t),Array.isArray(i.to))for(let a of i.to)this.extractUserIdFromValue(a,t);if(Array.isArray(i.taggedUserContacts))for(let a of i.taggedUserContacts)this.extractUserIdFromValue(a,t)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",i)}}extractReactionActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.reactionUtilsService.getUserIdsToResolveFromReactions([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",i)}}extractRecorderActivityUserIds(e,t){try{if(!e.entityData)return;let i=this.recorderUtilsService.getUserIdsToResolveFromRecorders([e.entityData]);for(let a of i)t.add(a)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",i)}}stripUsersFromChanges(e){try{for(let t of Object.keys(e)){let i=e[t];i&&(i.from=this.stripUserIfPresent(i.from),i.to=this.stripUserIfPresent(i.to))}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",t)}}stripUserIfPresent(e){try{return e&&typeof e=="object"&&"userId"in e?{userId:e.userId}:e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",t),e}}stripUsersFromTemplateData(e){try{for(let t of Object.keys(e)){let i=e[t];i&&typeof i=="object"&&"userId"in i&&(e[t]={userId:i.userId})}}catch(t){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",t)}}rehydrateUsersInChanges(e){try{for(let t of Object.values(e))t&&(t.from=this.rehydrateIfUser(t.from),t.to=this.rehydrateIfUser(t.to))}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",t)}}rehydrateIfUser(e){try{if(e&&typeof e=="object"&&"userId"in e){let t=e.userId;return this.usersService.getUserById(t)??e}return e}catch(t){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",t),e}}rehydrateUsersInTemplateData(e){try{for(let t of Object.keys(e))e[t]=this.rehydrateIfUser(e[t])}catch(t){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",t)}}rehydrateUserInObject(e,t){try{let i=e[t];if(i&&typeof i=="object"&&"userId"in i){let a=i.userId,l=this.usersService.getUserById(a);l&&(e[t]=l)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",i)}}rehydrateUsersInArray(e,t){try{let i=e[t];Array.isArray(i)&&(e[t]=i.map(a=>this.rehydrateIfUser(a)))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",i)}}extractUserIdFromValue(e,t){try{if(e&&typeof e=="object"&&"userId"in e){let i=e.userId;typeof i=="string"&&t.add(i)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",i)}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An),X(cv),X(NL),X(kp),X(rl),X(Gs),X(ol),X(xp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var dv=class{constructor({apiKey:o,documentId:r,organizationId:e,folderId:t,veltFolderId:i,clientDocumentId:a,clientOrganizationId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.folderId=t,this.veltFolderId=i,this.clientDocumentId=a,this.clientOrganizationId=l,a&&(this.documentId=mi(a)),l&&(this.organizationId=Pa(l)),t&&(this.folderId=t,this.veltFolderId=Pr(t)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`${this.apiKey}`;this.organizationId&&(o=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${o}/${N.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${o}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${o}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${o}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${o}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${o}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${o}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${N.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 LL=class{constructor({apiKey:o,documentId:r,organizationId:e,clientDocumentId:t,clientOrganizationId:i,folderId:a,veltFolderId:l}){this.paths={},this.apiKey=o,this.documentId=r,this.organizationId=e,this.veltFolderId=l,t&&(this.documentId=mi(t)),i&&(this.organizationId=Pa(i)),a&&(this.folderId=a,this.veltFolderId=Pr(a)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let o=`apiKey/${this.apiKey}`;this.paths.activities=`${o}/${N.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.organizationId&&(o=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=o,this.paths.folder=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${o}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${o}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${o}/${N.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${o}/${N.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${o}/${N.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${N.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${o}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${N.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(o){throw{type:"DocumentPaths",message:o,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Rbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromAreaAnnotations(e){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",t),[]}}mergeAreaWithUser(e){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",t),e}}formatAreaData(e){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Nbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromArrowAnnotations(e){try{this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: getUserIdsToResolveFromArrowAnnotations","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ArrowUtilsService getUserIdsToResolveFromArrowAnnotations:",t),[]}}mergeArrowWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: mergeArrowWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService mergeArrowWithUser:",t),e}}formatArrowData(e){try{return this.loggingService.log("%c[WB] Calling ArrowUtilsService FUNCTION: formatArrowData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in ArrowUtilsService formatArrowData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Fbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromUserIamData(e){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let t=new Set;if(e?.length)for(let i of e)i?.user?.userId&&t.add(i?.user?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",t),[]}}mergeUserIamWithUser(e){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);if(t){let i=t;e?.user&&typeof e.user=="object"&&(i=h(h({},i),e.user)),e=y(h({},e),{user:i})}}return e}catch(t){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromCursorUsers(e){try{this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: getUserIdsToResolveFromCursorUsers","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in CursorUtilsService getUserIdsToResolveFromCursorUsers:",t),[]}}mergeCursorUserWithUser(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: mergeCursorUserWithUser","color: green;"),this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService mergeCursorUserWithUser:",t),e}}formatCursorUserData(e){try{if(this.loggingService.log("%c[WB] Calling CursorUtilsService FUNCTION: formatCursorUserData","color: green;"),this.usersService.userDataProviderAvailable()){let t=["userId","comment","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","targetElement","position","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in CursorUtilsService formatCursorUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var UL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromHuddleAttendees(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleAttendees","color: green;");let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleAttendees:",t),[]}}mergeHuddleAttendeeWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleAttendeeWithUser","color: green;"),e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleAttendeeWithUser:",t),e}}formatHuddleAttendeeData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","userSnippylyId","state","timestamp","initialHuddleMode","streamMetadata","initialHuddleType","huddleOnCursorMode"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleAttendeeData:",t),e}}getUserIdsToResolveFromHuddleMessages(e){try{this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: getUserIdsToResolveFromHuddleMessages","color: green;");let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in HuddleUtilsService getUserIdsToResolveFromHuddleMessages:",t),[]}}mergeHuddleMessageWithUser(e){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: mergeHuddleMessageWithUser","color: green;"),e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService mergeHuddleMessageWithUser:",t),e}}resolveUsersFromHuddleMessages(e){return J(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: resolveUsersFromHuddleMessages","color: green;"),this.usersService.userDataProviderAvailable()){let t=this.getUserIdsToResolveFromHuddleMessages(e),i=at(),a=xc.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_USERS_FROM_HUDDLE_MESSAGES,moduleName:a,source:"internal",payload:{userIds:t}});let l=yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a});for(let s of e)s?.from?.userId&&l[s.from.userId]&&(s.from=l[s.from.userId])}return e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService resolveUsersFromHuddleMessages:",t),e}})}formatHuddleMessageData(e){try{return this.loggingService.log("%c[WB] Calling HuddleUtilsService FUNCTION: formatHuddleMessageData","color: green;"),this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e}catch(t){return this.loggingService.catch("Error in HuddleUtilsService formatHuddleMessageData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var VL=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(e){try{let t=new Set;return e?.updatedBy&&t.add(e?.updatedBy?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",t),[]}}mergeLiveStateCustomWithUser(e){try{if(e?.updatedBy?.userId){let t=this.usersService.getUserById(e?.updatedBy?.userId);t&&(e.updatedBy=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",t),e}}formatLiveStateCustomData(e){try{return this.usersService.userDataProviderAvailable()&&e?.updatedBy&&(e.updatedBy={userId:e.updatedBy.userId}),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",t),e}}getUserIdsToResolveFromLiveStateCustoms(e){try{let t=new Set;for(let i of e)i?.updatedBy?.userId&&t.add(i?.updatedBy?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",t),[]}}getUserIdsToResolveFromLiveStates(e){try{let t=new Set;return e?.default?.singleEditorMode?.editor?.userId&&t.add(e?.default?.singleEditorMode?.editor?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",t),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(e){try{let t=new Set;return e?.editor?.userId&&t.add(e?.editor?.userId),e?.requestEditorAccess?.user?.userId&&t.add(e?.requestEditorAccess?.user?.userId),Array.from(t)}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",t),[]}}mergeLiveStateWithUser(e){try{if(e?.default?.singleEditorMode?.editor?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.editor?.userId);t&&(e.default.singleEditorMode.editor=t)}if(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);t&&(e.default.singleEditorMode.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",t),e}}mergeSingleEditorLiveStateDataWithUser(e){try{if(e?.editor?.userId){let t=this.usersService.getUserById(e?.editor?.userId);t&&(e.editor=t)}if(e?.requestEditorAccess?.user?.userId){let t=this.usersService.getUserById(e?.requestEditorAccess?.user?.userId);t&&(e.requestEditorAccess.user=t)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",t),e}}resolveAndMergeSingleEditorLiveStateDataWithUser(e){return J(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=at(),a=xc.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:gi.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:a,source:"internal",payload:{userIds:t}}),yield this.usersService.resolveUsers({userIds:t,uniqueId:i,moduleName:a}),this.mergeSingleEditorLiveStateDataWithUser(e)}return e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",t),e}})}formatLiveStateSingleEditorModeData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.editor?.userId&&(e.editor={userId:e.editor.userId}),e?.requestEditorAccess?.user?.userId&&(e.requestEditorAccess.user={userId:e.requestEditorAccess.user.userId})),e}catch(t){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",t),e}}mergeLiveStateCustomsWithUsers(e){try{for(let t of e)if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return e}catch(t){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Bbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromMultiThreads(e){try{let t=new Set;for(let i of e)i?.from?.userId&&t.add(i?.from?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",t),[]}}mergeMultiThreadWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",t),e}}formatMultiThreadData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.commentAnnotationsMap&&(e.commentAnnotationsMap=null)),e}catch(t){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mv=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Se(null),this.notificationById$=new Se({}),this.inFlightRequests=new Map,this.getNotificationById=a=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[a]:void 0}catch(l){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",l);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(a=>{a&&(a.config?.resolveTimeout&&(this.resolveTimeout=a.config.resolveTimeout),a.config?.deleteRetryConfig&&(this.retryDeleteConfig=a.config.deleteRetryConfig),a.config?.getRetryConfig&&(this.retryGetConfig=a.config.getRetryConfig))})}catch(a){this.loggingService.catch("Error in NotificationResolverService constructor:",a)}}getProvider(){try{let e=this.notificationDataProvider$.getValue();return e||void 0}catch(e){this.loggingService.catch("Error in NotificationResolverService getProvider:",e);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(e){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",e)}}resolveNotifications(a){return J(this,arguments,function*({request:e,uniqueId:t,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let l,s=!1,d=!1,v=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){s=!0,v();let Ie=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:e}}),_(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let I=this.getProvider();if(!I)return v(),u({});let A={},M=this.notificationById$.getValue()||{},B=[...new Set(e.notificationIds||[])],q=[],ae=[],Ce=[];for(let Ie of B)M[Ie]||(this.inFlightRequests.has(Ie)?(q.push(this.inFlightRequests.get(Ie)),ae.push(Ie)):Ce.push(Ie));let oe=y(h({},e),{notificationIds:Ce});J(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),Ce.length>0){let Ie=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:oe}});let xe,ye=new Promise(Re=>{xe=Re});for(let Re of Ce)this.inFlightRequests.set(Re,ye.then(Ue=>Ue?.[Re]));let Oe=Ai(()=>I?.config?.getConfig?.url?ji(I.config.getConfig.url,I.config.getConfig.headers,oe,!0):I?.get?.(oe)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Re=>s?{}:(v(),Re&&Re.statusCode!==200?(this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Re,request:oe}}),this.loggingService.catch(Re?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Re?.data)).catch(Re=>{throw v(),Re});try{A=(yield Oe)||{},xe(A);for(let Ue of Ce)this.inFlightRequests.delete(Ue);this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:Ce});let Re={};Object.entries(A).forEach(([Ue,ze])=>{let Ge=this.notificationById$.value?.[Ue];Ge?Ge&&JSON.stringify(Ge)!==JSON.stringify(ze)&&(Re[Ue]=ze):Re[Ue]=ze}),Object.keys(Re).length>0&&this.notificationById$.next(h(h({},this.notificationById$.getValue()),Re)),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:Ie,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Re,request:oe}}),u(Re)}catch(Re){xe({});for(let ze of Ce)this.inFlightRequests.delete(ze);let Ue=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ue,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Re,request:oe}}),s||_(Re),u(A)}}else v(),u({})}catch(Ie){v();let xe=t||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:xe,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ie,request:oe}}),_(Ie)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let s=t||at();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Sl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return J(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let a=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let l=i||at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let s=this.notificationById$.getValue(),d=h({},s);delete d?.[e],this.notificationById$._value=d;let v={notificationId:e,organizationId:t},u=yield Ai(()=>a?.config?.deleteConfig?.url?ji(a.config.deleteConfig.url,a.config.deleteConfig.headers,v,!1):a?.delete?.(v)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=s),this.loggingService.catch(u?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:u,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:e}),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",a);let l=i||at();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:Sl.DELETE_NOTIFICATION,source:"internal",payload:{error:a,notificationId:e,organizationId:t}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):se(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),se(void 0)}}setNotificationDataProvider(e){try{if(e){this.loggingService.log("Setting notification data provider");let t=e.config,i=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(i.forEach(({method:l,configKey:s})=>{let d=t?.[s]?.url,v=l in e&&typeof e[l]=="function";!d&&!v&&a.push(l)}),a.length>0){let l=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(l);return}else this.notificationDataProvider$.next(e)}}catch(t){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",t)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(e){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",e),!1}}};o.\u0275fac=function(t){return new(t||o)(X(tr),X(k),X(st))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jL=(()=>{let o=class o{constructor(e,t,i,a,l,s,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=s,this.notificationResolverService=d}getUserIdsToResolveFromNotifications(e){try{let t=new Set;for(let i of e){let{notification:a}=i;switch(a?.actionUser?.userId&&t.add(a?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.actionUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.actionUser?.userId),a?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&t.add(a?.displayHeadlineMessageTemplateData?.recipientUser?.userId),a?.notificationSource){case"comment":if(a?.notificationSourceData){let l=this.commentUtilsService.getUserIdsToResolveFromComments([a?.notificationSourceData]);for(let s of l)t.add(s)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),i=e?.raw?.targetAnnotationData?.commentId,a=t?.comments?.[i]?.commentText,l=t?.comments?.[i]?.commentHtml;return a&&l&&e?.raw?.notificationSource==="comment"&&(e.notification.displayBodyMessageTemplate=a,e.raw.targetAnnotationData.commentText=a,e.raw.targetAnnotationData.commentHtml=l),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",t),e}}mergeLocationWithNotification(e,t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let i=e?.notification?.notificationSourceData?.location?.id,a=e?.notification?.notificationSourceData?.metadata?.documentId;if(!i||!a)return e;let l=t?.[a]?.[i];return l&&(e.notification.notificationSourceData.location=l?.location,e?.raw?.annotationData?.location&&(e.raw.annotationData.location=l?.location)),e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",i),e}}mergeNotificationWithUser(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:t}=e;if(t?.actionUser?.userId){let i=this.usersService.getUserById(t?.actionUser?.userId);i&&(t.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.actionUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.actionUser?.userId);i&&(t.displayHeadlineMessageTemplateData.actionUser=i)}if(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let i=this.usersService.getUserById(t?.displayHeadlineMessageTemplateData?.recipientUser?.userId);i&&(t.displayHeadlineMessageTemplateData.recipientUser=i)}switch(t?.notificationSource){case"comment":t?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(t?.notificationSourceData);break}return e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",t),e}}formatNotification(e,t){try{switch(typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),this.usersService.userDataProviderAvailable()&&e?.actionUser&&(e.actionUser={userId:e.actionUser.userId}),e.notificationSource){case"comment":this.commentUtilsService.formatCommentData(e.annotationData),this.commentUtilsService.formatCommentThreadData(e.targetAnnotationData);break;case"recorder":this.recorderUtilsService.formatRecorderData(e.annotationData,t);break}return e}catch(i){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",i),e}}getTargetAnnotationIdsFromNotifications(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let t=[];return Object.values(e).forEach(i=>{i?.notification?.targetAnnotationId&&i?.raw?.notificationSource==="comment"&&t.push(i.notification.targetAnnotationId)}),t}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",t),[]}}handleNotificationEncryption(t){return J(this,arguments,function*({data:e}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let i="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield fc(e,i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",i),e}})}getCustomNotificationIdsToResolve(e){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let t=new Set,i=Array.isArray(e)?e:Object.values(e||{});for(let a of i)if(a?.raw?.notificationSource==="custom"){let l=a?.notification?.id||a?.notificationId;l&&t.add(l)}return Array.from(t)}catch(t){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",t),[]}}mergeResolvedNotificationData(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||e?.raw?.notificationSource!=="custom")return e;let t=e?.notification?.id||e?.notificationId;if(!t)return e;let i=this.notificationResolverService.getNotificationById(t);if(!i)return e;let a=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let l of a)i[l]!==void 0&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]));return Object.keys(i).forEach(l=>{!a.includes(l)&&l!=="notificationId"&&(e.notification&&(e.notification[l]=i[l]),e.raw&&(e.raw[l]=i[l]))}),e.notification&&(e.notification.isNotificationResolverUsed=!0),e}catch(t){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(cv),X(kp),X(k),X(An),X(qe),X(rl),X(mv))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var $be=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromPresenceUsers(e){try{let t=new Set;for(let i of e)i?.userId&&t.add(i?.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in PresenceUtilsService getUserIdsToResolveFromPresenceUsers:",t),[]}}mergePresenceUserWithUser(e){try{if(this.usersService.userDataProviderAvailable()&&e?.userId){let t=this.usersService.getUserById(e?.userId);t&&(e=h(h({},e),t))}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService mergePresenceUserWithUser:",t),e}}formatPresenceUserData(e){try{if(this.usersService.userDataProviderAvailable()){let t=["userId","onlineStatus","userSnippylyId","color","textColor","timestamp","type","selections","documentParamsId","documentParams","locationId","location","isReadOnly","isAnonymous","pageInfo"];Object.keys(e).forEach(i=>{t.includes(i)||(e[i]=null)})}return e}catch(t){return this.loggingService.catch("Error in PresenceUtilsService formatPresenceUserData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromSelections(e){try{let t=new Set;for(let i of e)i?.user?.userId&&t.add(i.user.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",t),[]}}mergeSelectionWithUser(e){try{if(e?.user?.userId){let t=this.usersService.getUserById(e?.user?.userId);t&&(e.user=t)}return e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",t),e}}formatSelectionData(e){try{return this.usersService.userDataProviderAvailable()&&e?.user?.userId&&(e.user={userId:e.user.userId}),e}catch(t){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Gbe=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.usersService=t}getUserIdsToResolveFromTags(e){try{let t=new Set;for(let i of e)if(i?.from?.userId&&t.add(i.from.userId),i?.to?.length)for(let a of i.to)a?.userId&&t.add(a.userId);return Array.from(t)}catch(t){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",t),[]}}mergeTagWithUser(e){try{if(e?.from?.userId){let t=this.usersService.getUserById(e?.from?.userId);t&&(e.from=t)}return e?.to?.length&&(e.to=e.to.map(t=>{if(t?.userId){let i=this.usersService.getUserById(t?.userId);i&&(t=i)}return t})),e}catch(t){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",t),e}}formatTagData(e){try{return this.usersService.userDataProviderAvailable()&&(e?.from?.userId&&(e.from={userId:e.from.userId}),e?.to?.length&&(e.to=e.to.map(t=>(t?.userId&&(t={userId:t.userId}),t)))),e}catch(t){return this.loggingService.catch("Error in TagUtilsService formatTagData:",t),e}}};o.\u0275fac=function(t){return new(t||o)(X(k),X(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var od=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I,A,M,B,q,ae,Ce,oe,fe,Ie,xe,ye,Oe,Re){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=s,this.cursorUtilsService=d,this.huddleUtilsService=v,this.liveStateUtilsService=u,this.loggingService=_,this.multiThreadUtilsService=I,this.notificationUtilsService=A,this.presenceUtilsService=M,this.reactionUtilsService=B,this.recorderUtilsService=q,this.selectionUtilsService=ae,this.tagUtilsService=Ce,this.usersService=oe,this.docService=fe,this.commentAnnotationsResolverService=Ie,this.reactionAnnotationsResolverService=xe,this.recorderAnnotationsResolverService=ye,this.notificationResolverService=Oe,this.activityResolverService=Re}getErrorForGetRequests({feature:e,error:t}){try{switch(e){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(t?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",i),null}}getFirestorePath({feature:e,properties:t,documentPaths:i,apiKey:a}){try{if(!a)return;let{documentId:l,organizationId:s,folderId:d}=t;s||(s=i?.organizationId);let v=new LL({apiKey:a,documentId:l?`${l}`:"",organizationId:s?`${s}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&v?.userConfig?`${v?.userConfig}/${t?.userId}${t?.documentId?`/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return v?.permissionsUsers?`${v?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&v?.comment?`${v?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&v?.comment?`${v?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&v?.multiThread?`${v?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&v?.multiThread?`${v?.multiThread}`:void 0;case"crdt":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return v?.lastNotificationTimestamp?`${v?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&v?.lastNotificationTimestamp?`${v?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&v?.activities?`${v?.activities}/${t?.id}`:void 0;case"allActivities":return v?.activities?`${v?.activities}`:void 0;case"allLastActivityTimestamp":return v?.lastActivityTimestamp?`${v?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&v?.lastActivityTimestamp?`${v?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&v?.area?`${v?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&v?.area?`${v?.area}`:void 0;case"allDocuments":return v?.document?`${v?.document}`:void 0;case"allLocations":return v?.location?`${v?.location}`:void 0;case"allFolders":return v?.folder?`${v?.folder}`:void 0;case"folder":return v?.folder&&t.folderId?`${v?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&v?.documentUsers?`${v?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&v?.reaction?`${v?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&v?.reaction?`${v?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&v?.recorder?`${v?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&v?.document?`${v?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return v?.organization?`${v?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&v?.document?`${v?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&v?.folder?`${v?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&v?.location&&t?.id?`${v?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&v?.documentUsers?`${v?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return v?.users?`${v?.users}`:void 0;case"allFolderUsers":return v?.users?`${v?.users}`:void 0;case"allOrganizationGroups":return v?.organizationGroups?`${v?.organizationGroups}`:void 0;case"allOrganizationUsers":return v?.users?`${v?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&v?.notificationViews?`${v?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&v?.documentViews?`${v?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&v?.documentViews?`${v?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&v?.locationViews?`${v?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&v?.locationViews?`${v?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&v?.docNotification?`${v?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&v?.docNotification?`${v?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&v?.notificationUsers?`${v?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&v?.notificationUsers?`${v?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${e}`)}}catch(l){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",l);return}}getFirestoreCollectionGroupPath(e){try{switch(e){case"allComments":return N.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return N.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return N.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return N.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return N.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return N.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return N.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return N.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${e}`)}}catch(t){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",t);return}}getDocumentPath({feature:e,properties:t,defaultDocumentPaths:i,apiKey:a,useFirestore:l}){try{if(!a)return;let{documentId:s,organizationId:d}=t;d||(d=i?.organizationId);let v=new dv({apiKey:a,documentId:s?`${s}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&v?.userConfig?`${v?.userConfig}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&v?.comment?`${v?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&v?.globalContacts?`${v?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&v?.globalContacts?`${v?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&v?.groupContacts?`${v?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&v?.groupContacts?`${v?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&v?.logins?`${v?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&v?.logins?`${v?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&v?.logins?`${v?.logins}${t?.userId}`:void 0;case"customerMetadata":return v?.customerMetadata?`${v?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&v?.arrow?`${v?.arrow}`:void 0;case"arrow":return t?.documentId&&v?.arrow&&t.id?`${v?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&v?.cursor?`${v?.cursor}`:void 0;case"cursor":return t?.documentId&&v?.cursor&&t.id?`${v?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&v?.flock&&t.id?`${v?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&v?.flock&&t.id?`${v?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&v?.huddle?`${v?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&v?.huddle?`${v?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&v?.huddle?`${v?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&v?.huddle?`${v?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&v?.huddle&&t.id?`${v?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&v?.liveState?`${v?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&v?.liveState?`${v?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&v?.liveState&&t?.id?`${v?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&v?.liveStateSingleEditorMode?`${v?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&v?.liveState?`${v?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&v?.liveState?`${v?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&v?.liveState&&t?.id?`${v?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&v?.presence&&t?.userId?`${v?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&v?.presence?`${v?.presence}`:void 0;case"workspaceIam":return v?.workspaceIam?`${v?.workspaceIam}`:void 0;case"selection":return t?.documentId&&v?.selection&&t?.userId?`${v?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&v?.selection?`${v?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&v?.syncVideoPlayer?`${v?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&v?.tag?`${v?.tag}`:void 0;case"tag":return t?.documentId&&v?.tag&&t?.id?`${v?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&v?.userContactUs?`${v?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&v?.userFeedback?`${v?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&v?.userReportBugs?`${v?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&v?.comment?`${v?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&v?.multiThread?`${v?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&v?.crdt?`${v?.crdt}`:void 0;case"crdtData":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&v?.crdt&&t?.id&&t?.versionId?`${v?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&v?.crdt&&t?.id&&t?.messageId?`${v?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&v?.crdt&&t?.id?`${v?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&v?.multiThread?`${v?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&v?.organizationNotificationsLastNotificationTimestamp?`${v?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&v?.organizationNotificationsLastNotificationTimestamp?`${v?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&v?.documentIam?`${v?.documentIam}`:void 0;case"allDocuments":return!l&&v?.docs&&t?.documentId?`${v?.docs}/${t?.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&v?.area?`${v?.area}`:void 0;case"area":return!l&&t?.id&&v?.area?`${v?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&v?.folder?`${v?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&v?.documentIam?`${v?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&v?.documentIam?`${v?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&v?.documentIam?`${v?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&v?.organizationGroups?`${v?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&v?.organizationIam?`${v?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&v?.reaction?`${v?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&v?.reaction?`${v?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&v?.recorder?`${v?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&v?.recorder?`${v?.recorder}`:void 0;case"organizationMetadata":return!l&&v?.organizationMetadata?`${v?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&v?.heartbeat?`${v?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return v?.heartbeat?`${v?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&v?.heartbeatByDocument?`${v?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return v?.heartbeatByDocument?`${v?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&v?.documentIam?`${v?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&v?.metadata?`${v?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&v?.views?`${v?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&v?.views?`${v?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&v?.views?`${v?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&v?.views?`${v?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&v?.views?`${v?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&v?.views?`${v?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&v?.views?`${v?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&v?.views?`${v?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&v?.views?`${v?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&v?.views?`${v?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&v?.organizationNotificationsWithDocumentId?`${v?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&v?.organizationNotificationsWithDocumentId?`${v?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&v?.organizationNotificationsUsers?`${v?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&v?.organizationNotificationsUsers?`${v?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",s);return}}resolveAnnotations(i){return J(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=at(),l=Q1.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.RESOLVE_COMMENT_ANNOTATIONS,moduleName:l,source:"internal",payload:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let a=at(),l=eS.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:l,source:"internal",payload:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let a=at(),l=tS.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:l,source:"internal",payload:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:e,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:a,moduleName:l})}break}default:break}}catch(a){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${t}`,a)}})}formatResponse(_){return J(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:s=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:v=!1,shouldRecorderResolverAwait:u=!1}){try{if(this.usersService.userDataProviderAvailable()){let I=[];switch(e){case"allAreas":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(t)));break}case"allArrows":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.arrowUtilsService.getUserIdsToResolveFromArrowAnnotations(Object.values(t)));break}case"allCursors":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.cursorUtilsService.getUserIdsToResolveFromCursorUsers(Object.values(t)));break}case"allComments":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(t)));break}case"allDocumentUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allFolderUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allOrganizationUsers":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(t)));break}case"allMultiThreads":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(t)));break}case"allDocNotifications":{t&&typeof t=="object"&&(I=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Array.isArray(t)?t:Object.values(t)));break}case"allUserNotifications":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.notificationUtilsService.getUserIdsToResolveFromNotifications(Object.values(t)));break}case"allPresence":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.presenceUtilsService.getUserIdsToResolveFromPresenceUsers(Object.values(t)));break}case"allRecorders":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.recorderUtilsService.getUserIdsToResolveFromRecorders(Object.values(t)));break}case"allReactions":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(t)));break}case"allTags":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(t)));break}case"allHuddleAttendees":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.huddleUtilsService.getUserIdsToResolveFromHuddleAttendees(Object.values(t)));break}case"liveStateCustom":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(t));break}case"allLiveStateCustoms":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(t)));break}case"allLiveStates":{t&&typeof t=="object"&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(t));break}case"liveStateSingleEditorMode":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(t));break}case"allSelections":{t&&typeof t=="object"&&!Array.isArray(t)&&(I=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(t)));break}case"allActivities":{t&&typeof t=="object"&&(I=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(t)?t:Object.values(t)));break}default:I=[]}if(I?.length){let A=at(),M=xc.GET_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:gi.FORMAT_RESPONSE,source:"internal",moduleName:M,payload:{userIds:I,feature:e,forceResolve:a}}),i?yield this.usersService.resolveUsers({userIds:I,forceResolve:a,feature:e,uniqueId:A,moduleName:M}):this.usersService.resolveUsers({userIds:I,forceResolve:a,feature:e,uniqueId:A,moduleName:M})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let I=[];switch(e){case"allDocNotifications":case"allUserNotifications":{t&&typeof t=="object"&&(I=this.notificationUtilsService.getCustomNotificationIdsToResolve(t),I=I.filter(A=>!this.notificationResolverService.getNotificationById(A)));break}default:I=[]}if(I?.length){let A=at(),M=fQ.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:Sl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:s}}),s?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.notificationResolverService.resolveNotifications({request:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let I=[];switch(e){case"allDocNotifications":{if(t&&typeof t=="object"){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);I=[...I,...A],I=I.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allUserNotifications":{if(t&&typeof t=="object"&&!Array.isArray(t)){let A=this.notificationUtilsService.getTargetAnnotationIdsFromNotifications(t);I=[...I,...A],I=I.filter(M=>!this.commentAnnotationsResolverService.getCommentAnnotationById(M))}break}case"allActivities":{if(t&&typeof t=="object"){let A=Array.isArray(t)?t:Object.values(t),M=this.activityUtilsService.getEntityIdsToResolveFromActivities(A,"comment");I=[...I,...M],I=I.filter(B=>!this.commentAnnotationsResolverService.getCommentAnnotationById(B))}break}default:I=[]}if(I?.length){let A=at(),M=Q1.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ni.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldCommentAnnotationsResolverAwait:l}}),l?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:A,moduleName:M})}}if(e==="allActivities"&&t&&typeof t=="object"){let I=Array.isArray(t)?t:Object.values(t),A=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let M=[];for(let B of I)B?.id&&!this.activityResolverService.getActivityById(B.id)&&M.push(B.id);if(M.length){let B=at(),q=CQ.GET_ACTIVITIES;this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:us.FORMAT_RESPONSE,moduleName:q,source:"internal",payload:{activityIds:M,organizationId:A,shouldActivityResolverAwait:d}}),d?yield this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.activityResolverService.resolveActivities({request:{activityIds:M,organizationId:A},uniqueId:B,moduleName:q})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(I,"reaction");if(M=M.filter(B=>!this.reactionAnnotationsResolverService.getAnnotationById(B)),M.length){let B=at(),q=eS.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:v}}),v?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let M=this.activityUtilsService.getEntityIdsToResolveFromActivities(I,"recorder");if(M=M.filter(B=>!this.recorderAnnotationsResolverService.getAnnotationById(B)),M.length){let B=at(),q=tS.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.RESOLVE_RECORDER_ANNOTATIONS,moduleName:q,source:"internal",payload:{recorderAnnotationIds:M,organizationId:A,shouldRecorderResolverAwait:u}}),u?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:M,organizationId:A},uniqueId:B,moduleName:q})}}}return t}catch(I){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",I),t}})}mergeCommentAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(l),i),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeStrippedDataWithNotification(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",i),e}}mergeActivityResolverWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable())switch(t){case"allActivities":return Array.isArray(e)?e.map(i=>this.activityUtilsService.mergeActivityWithResolverData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",i),e}}mergeNotificationsWithResolvedData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(t){case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeResolvedNotificationData(l),i),{}):Array.isArray(e)?e.map(i=>this.notificationUtilsService.mergeResolvedNotificationData(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",i),e}}mergeNotificationsWithResolvedData$({data:e,feature:t}){try{return this.notificationResolverService.getNotificationsById$().pipe(ge(()=>{let i=this.mergeNotificationsWithResolvedData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),se(e)}}mergeReactionAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(t){case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",i),e}}mergeRecorderAnnotationsWithData({data:e,feature:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(t){case"allRecorders":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(l),i),{}):e;case"allActivities":return this.mergeActivitiesWithFeatureData(e);default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",i),e}}mergeActivitiesWithFeatureData(e){return Array.isArray(e)?e.map(t=>this.activityUtilsService.mergeActivityWithFeatureData(t)):e}mergeLocationMetadataWithData({data:e,feature:t,locationMetadata:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),i&&typeof i=="object"&&!Array.isArray(i))switch(t){case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(s,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,s])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(s,i),a),{}):e;default:return e}return e}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",a),e}}mergeUsersWithData({feature:e,data:t}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(e){case"allAreas":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.areaUtilsService.mergeAreaWithUser(l),i),{}):t;case"allArrows":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.arrowUtilsService.mergeArrowWithUser(l),i),{}):t;case"allCursors":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.cursorUtilsService.mergeCursorUserWithUser(l),i),{}):t;case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.commentUtilsService.mergeCommentWithUser(l),i),{}):t;case"allDocumentUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allFolderUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allOrganizationUsers":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.contactUtilsService.mergeUserIamWithUser(l),i),{}):t;case"allMultiThreads":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.multiThreadUtilsService.mergeMultiThreadWithUser(l),i),{}):t;case"allDocNotifications":return t&&typeof t=="object"?t?.map(i=>this.notificationUtilsService.mergeNotificationWithUser(i)):t;case"allUserNotifications":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.notificationUtilsService.mergeNotificationWithUser(l),i),{}):t;case"allPresence":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.presenceUtilsService.mergePresenceUserWithUser(l),i),{}):t;case"allRecorders":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.recorderUtilsService.mergeRecorderWithUser(l),i),{}):t;case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.reactionUtilsService.mergeReactionWithUser(l),i),{}):t;case"allTags":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.tagUtilsService.mergeTagWithUser(l),i),{}):t;case"allHuddleAttendees":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.huddleUtilsService.mergeHuddleAttendeeWithUser(l),i),{}):t;case"liveStateCustom":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(t):t;case"allLiveStateCustoms":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(l),i),{}):t;case"allLiveStates":return t&&typeof t=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(t):t;case"liveStateSingleEditorMode":return t&&typeof t=="object"&&!Array.isArray(t)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(t):t;case"allSelections":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[a,l])=>(i[a]=this.selectionUtilsService.mergeSelectionWithUser(l),i),{}):t;case"allActivities":return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithUser(i)):t;default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",i),t}}mergeCommentAnnotationsWithData$({data:e,feature:t}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ge(()=>{let i=this.mergeCommentAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),se(e)}}mergeReactionAnnotationsWithData$({data:e,feature:t}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ge(()=>{let i=this.mergeReactionAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),se(e)}}mergeRecorderAnnotationsWithData$({data:e,feature:t}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ge(()=>{let i=this.mergeRecorderAnnotationsWithData({data:e?.data??{},feature:t}),a=this.mergeUsersWithData({feature:t,data:i??{}});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),se(e)}}mergeUsersWithData$({feature:e,data:t}){try{return this.usersService.getUserById$().pipe(ge(()=>{let i=this.mergeUsersWithData({feature:e,data:t?.data??{}});return typeof i=="object"?{data:JSON.parse(JSON.stringify(i)),operation:t?.operation??null}:{data:i,operation:t?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),se(t)}}mergeLocationMetadataWithData$({data:e,feature:t}){try{return this.docService.getLocationMetadata$().pipe(ge(i=>{let a=this.mergeLocationMetadataWithData({data:e?.data??{},feature:t,locationMetadata:i});return typeof a=="object"?{data:JSON.parse(JSON.stringify(a)),operation:e?.operation??null}:{data:a,operation:e?.operation??null}}),kt(Jt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),se(e)}}handleDataStripping(l){return J(this,arguments,function*({feature:e,data:t,actionType:i,commentId:a}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),e){case"comment":return yield this.commentUtilsService.stripCommentAnnotationData({data:t,actionType:i,commentId:a});case"reaction":return this.reactionUtilsService.stripReactionAnnotationData(t);case"recorder":return this.recorderUtilsService.stripRecorderAnnotationData({data:t,actionType:i});default:return{originalData:t,strippedData:null}}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",s),{originalData:t,strippedData:null}}})}formatData({feature:e,data:t,properties:i,offset:a,isRealtimeDb:l}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof t=="object"&&(t=JSON.parse(JSON.stringify(t)));let s=new Date().getTime()+a;switch(e){case"documentAccessType":return delete t?.users,{docIamConfig:t};case"organizationMetadata":case"documentMetadata":return l?t:{metadata:t};case"documentCommentMetadata":return t;case"cursor":return this.cursorUtilsService.formatCursorUserData(t);case"comment":return this.commentUtilsService.formatCommentData(t);case"area":return this.areaUtilsService.formatAreaData(t);case"arrow":return this.arrowUtilsService.formatArrowData(t);case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(t);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(t);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(t);case"reaction":return this.reactionUtilsService.formatReactionData(t);case"recorder":return this.recorderUtilsService.formatRecorderData(t,s);case"notificationViewsTimestamp":return{views:{[i.user??""]:t}};case"documentUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"documentDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"documentMetadataViews":return l?t:{metadata:t};case"huddleMessage":return this.huddleUtilsService.formatHuddleMessageData(t);case"locationMetadataViews":return l?t:{metadata:t};case"locationUsersViews":return l?t:{users:{[i.user??""]:{[i.date??""]:t}}};case"locationDayViews":return l?t:{day:{[i.date??""]:{[i.user??""]:t}}};case"locationViews":return l?t:{location:t};case"docNotificationViews":return l?t:{views:t.views};case"userNotificationViews":return l?t:{views:t.views};case"presence":return this.presenceUtilsService.formatPresenceUserData(t);case"selection":return this.selectionUtilsService.formatSelectionData(t);case"tag":return this.tagUtilsService.formatTagData(t);default:return t}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",s),t}}modifyAndSetData(l){return J(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let s=yield this.modifyData({feature:e,data:t});i.next({data:s,operation:a})}catch(s){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",s)}})}isDataAlreadyProcessedInLocalCache({feature:e,change:t,cache:i}){try{if(e==="allReactions"||e==="allComments"){if(t.type==="removed")return!Object.keys(i??{}).includes(t.doc.id);if(i?.[t.doc.id]){let a=t.doc.data(),l=i?.[t.doc.id];return a?.lastUpdated===l?.lastUpdated}}return!1}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",a),!1}}modifyData(i){return J(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)?y(h({},e),{metadata:e?.metadata??{documentId:t?.documentId,organizationId:t?.organizationId,apiKey:t?.apiKey}}):e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",i),e}}setDataInLocal(d){return J(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:s=null}){try{let u={comment:"allComments",reaction:"allReactions"}[e];if(!u)return null;let _=t?.metadata?.documentId,I=t?.metadata?.veltFolderId;return Object.keys(i).filter(A=>A.includes(u)&&(!_||A.includes(_)||I&&A.includes(I))).forEach(A=>{let M=i[A]?.subject?.getValue()??{};a==="DELETE"?l&&M?.data?.[l]&&(delete M?.data?.[l],i[A]?.subject&&i[A].subject.next({data:M?.data,operation:s})):i[A]?.subject?.next({data:y(h({},M?.data),{[t?.annotationId]:t}),operation:s})}),null}catch(v){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",v),null}})}handleCommentEncryption(s){return J(this,arguments,function*({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l}){try{return yield this.commentUtilsService.handleCommentEncryption({data:e,firestorePath:t,extraData:i,eventType:a,metadata:l})}catch(d){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",d),e}})}handleReactionEncryption(a){return J(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:e,firestorePath:t,eventType:i})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",l),e}})}rtdbDefaultTransactionCallback(e,t){try{let i=h({},e||{});return Object.entries(t).forEach(([a,l])=>{l==null?delete i[a]:i[a]=l}),i}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",i),e}}};o.\u0275fac=function(t){return new(t||o)(X(mS),X(Rbe),X(Nbe),X(cv),X(Fbe),X(tr),X(Lbe),X(UL),X(VL),X(k),X(Bbe),X(jL),X($be),X(NL),X(kp),X(Hbe),X(Gbe),X(An),X(ct),X(rl),X(Gs),X(ol),X(mv),X(xp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zbe=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{Cn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe($e(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,s])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||En?.firebaseLogLevel||"silent";wJ(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=yp.getFirestoreProdDbName(l,a.firebaseOptions),v=this.configService.getProxyConfig();if(v?.v2DbHost){let u={host:v.v2DbHost,ssl:!0};v.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,s&&(u.localCache=dQ({tabManager:mQ()}));try{this.firestore$.next(dL(Bl(),u,d))}catch(_){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",_),this.firestore$.next(K1(d))}}else if(s)try{let u=Bl(),_=dL(u,{localCache:dQ({tabManager:mQ()})},d);this.firestore$.next(_)}catch{this.firestore$.next(K1(d))}else this.firestore$.next(K1(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||K1("DocumentIdDb");if(e){let t=cO(e,"generateDocumentId");return X1(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(X(Nt),X(qe),X(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tn=(()=>{let o=class o{constructor(e,t,i,a,l,s,d,v,u,_,I,A,M,B){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=s,this.databaseService=d,this.configService=v,this.docService=u,this.usersService=_,this.commentAnnotationsResolverService=I,this.reactionAnnotationsResolverService=A,this.recorderAnnotationsResolverService=M,this.notificationResolverService=B,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(q=>{if(q){this.db=q;let ae=Ur(q,".info/serverTimeOffset");this.offsetListener=mg(ae,Ce=>{let oe=Ce.val();this.offset=oe})}})),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(q=>{q&&(this.firestore=q)}))}setActivityService(e){this.activityService=e}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(e=>{e?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([e,t])=>{t?.subject?.complete(),t?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(e){this.loggingService.catch("Error in unsubscribeFromObservables:",e)}}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.offsetListener&&this.offsetListener(),this.unsubscribeFromObservables()}setupOnDisconnect(e,t){return J(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return ms(i).update(t)}return Promise.resolve()}catch(i){return this.loggingService.catch("Error in setupOnDisconnect:",i),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(e){Cn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe($e(([t,i])=>!!t),ut(1),ln(([t,i])=>{e({db:t,firestore:i})})).subscribe({error:t=>{this.loggingService.catch("Error in CommonDbService subscription: ",t)}})}performDatabaseOperation(e,t,i,a,l,s){return J(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>J(this,[u],function*({db:d,firestore:v}){let _;t?.skipFirestore||(_=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}));let I=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!d){this.loggingService.warn(`%c[WB] No database or firestore found for ${e}`,"color: red;");return}try{let A,M;try{I&&(A=Ur(d,`${I}`))}catch{this.loggingService.catch("Error in dbRef")}try{_?.includes("/organizations")&&v&&_&&(M=X1(v,`${_}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:_}),s&&s({firestoreAvailable:!!v})}catch(A){this.loggingService.catch(`Error in ${e} operation: `,A),l&&l(A)}}))}catch(d){this.loggingService.catch("Error in performDatabaseOperation:",d)}})}setData(d){return J(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,v=>J(this,null,function*(){if(v.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Wf(v.dbRef,()=>JSON.parse(JSON.stringify(u))):yield qf(v.dbRef,JSON.parse(JSON.stringify(u)))}try{if(v.firestoreRef&&v.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:_,originalData:I,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,B=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:s?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:v.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(_,B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:I,firestorePath:v.firestorePath??""}))}else if(e==="recorder"){let M=null,B=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:_,eventType:A},B)),I&&(M?.isSuccess||M===null)&&this.firestore&&(yield pQ(this.firestore,q=>J(this,null,function*(){q.set(v.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield hQ(v.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(v){this.loggingService.catch(`Error in setData for ${e}`,v)}})}updateData(d){return J(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:s}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,s),this.performDatabaseOperation(e,i,v=>J(this,null,function*(){if(v.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Wf(v.dbRef,_=>{let I;return i?.rtdbTransactionCallback?I=i.rtdbTransactionCallback(_,u):I=this.commonDbUtilsService.rtdbDefaultTransactionCallback(_,u),JSON.parse(JSON.stringify(I))}):yield k8(v.dbRef,JSON.parse(JSON.stringify(u)))}try{if(v.firestoreRef&&v.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:v.data,properties:i,offset:this.getOffset()});typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)));let{strippedData:_,originalData:I,eventType:A}=yield this.commonDbUtilsService.handleDataStripping({feature:e,data:u,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,B=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:s?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:s?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:v.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(_,B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:I,firestorePath:v.firestorePath??""}))}else if(e==="recorder"){let M=null,B=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:oi.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I}}),_&&(M=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:_,eventType:A},B)),I&&(M?.isSuccess||M===null)&&this.firestore&&(yield pQ(this.firestore,q=>J(this,null,function*(){q.set(v.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield hQ(v.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(v){this.loggingService.catch(`Error in updateData for ${e}`,v)}})}createActivityFromExtraData(e,t){try{if(!t?.actionType||!this.activityService)return;let i=this.activityUtilsService.buildActivityDataFromExtraData({feature:e,extraData:t});i&&this.activityService.createActivity(i)}catch(i){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",i)}}deleteData(s){return J(this,arguments,function*({feature:e,properties:t,callback:i,errorCallback:a,extraData:l}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${e}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:e,observablesCache:this.observablesCache,eventType:"DELETE",id:t?.id,operation:{type:"removed",ids:[t?.id]}}),this.createActivityFromExtraData(e,l),this.performDatabaseOperation(e,t,d=>J(this,null,function*(){d.dbRef&&(yield y8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let v=null,u=at();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let v=null,u=at();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let v=null,u=at();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:oi.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),v=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(v?.isSuccess||v===null)&&(yield gL(d.firestoreRef))}else if(e==="userNotification"){let v=null,u=at();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:Sl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),v=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(v?.isSuccess||v===null)&&(yield gL(d.firestoreRef))}else yield gL(d.firestoreRef)}catch(v){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,v)}}),void 0,a,i)}catch(d){this.loggingService.catch(`Error in deleteData for ${e}`,d)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(e){return this.loggingService.catch("Error in shouldUseFirestore:",e),!1}}generateDocumentId(){try{let e=this.firestoreService.generateFirestoreDocumentId();return e||(e=at()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),at()||"noDocumentId"}}queryData(i){return J(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 J(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let i=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),[];try{let a=cO(this.firestore,i);t?.useCollectionGroup&&(a=vQ(this.firestore,i));let l=t?.firestoreQuery??[],s=uQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield mbe(s).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,v),null));return d?d.data().count:0}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,d),0}else try{let d=yield gbe(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let v=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:v})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),v}}catch(d){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,d),[]}}catch(a){return this.loggingService.catch(`Error in Firestore query for ${e}:`,a),[]}}catch(i){return this.loggingService.catch(`Error in Firestore query for ${e}:`,i),[]}})}handleRtdbQuery(e,t){return J(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let i=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No database path found for ${e}`),[];try{let a=Ur(this.db,i),l=t?.rtdbQuery??[],s=oY(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield tY(s).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let v=d.val();return v?t?.skipObjectValues?v:Object.values(v??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return J(this,arguments,function*({feature:e,properties:t}){try{let a=this.shouldUseFirestore();if(t?.skipFirestore&&(a=!1),!e||!t)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(a&&this.firestore){let l=this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No firestore path found for ${e}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};let s=yield vbe(X1(this.firestore,l)).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,v),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:v})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=s.data();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,s),{}}}if(this.db){let l=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!l)return this.loggingService.warn(`[WB] No database path found for ${e}`),{};try{if(!this.authService.getUser())return{};let s=yield tY(Ur(this.db,l)).catch(v=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,v),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:v})));if(s){if(s?.errorCode)return s}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=s.val();return t?.field?d?.[t.field]??{}:d??{}}catch(s){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,s),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return Cn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe($e(l=>!!l))]).pipe($e(([l,s])=>l?i&&!s?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),be(([l,s])=>{try{if(i&&s){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,s).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.firestoreSubscriptions[a]=u}return new Ht(v=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>v.next(_),_=>v.error(_),()=>v.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.firestoreSubscriptions[a]?.unsubscribe(),delete this.firestoreSubscriptions[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache[a]))}})}else if(l){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleRealtimeDbListener(e,t,l).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.rtdbSubscriptions[a]=u}return new Ht(v=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>v.next(_),_=>v.error(_),()=>v.complete());return this.observablesCache[a].count+=1,()=>{u?.unsubscribe(),this.observablesCache[a]&&(this.observablesCache[a].count-=1,this.observablesCache[a].count<=0&&(this.rtdbSubscriptions[a]?.unsubscribe(),delete this.rtdbSubscriptions?.[a],this.observablesCache[a]?.subject?.complete(),delete this.observablesCache?.[a]))}})}return se({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),se({})}}),Vh(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${e} and key ${a}`)}))}handleFirestoreListener(e,t,i){let a=t?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(e):this.commonDbUtilsService.getFirestorePath({feature:e,properties:t,documentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()}),l=`${e}-${JSON.stringify(t)}`;return a?new Ht(s=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,s,t):this.setupDocumentListener(i,a,e,s,t);return()=>{s.complete(),s.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(be(s=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:s})),be(s=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:s,feature:e}):se(s)),be(s=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:s,feature:e}):se(s)),be(s=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:s,feature:e}):se(s)),kt(Jt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),se({}))}setupCollectionListener(e,t,i,a,l){let s=`${i}-${JSON.stringify(l)}`,d=cO(e,t);if(l?.useCollectionGroup&&(d=vQ(e,t)),l?.useQuery&&l?.firestoreQuery){let _=l?.firestoreQuery??[];d=uQ(d,..._)}let v=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),gQ(d,_=>{try{let I=JSON.parse(JSON.stringify(this.observablesCache[s]?.subject?.getValue()?.data??{})),A=null,M=!1;_?.docChanges()?.length?_.docChanges().forEach(B=>{["allComments","allReactions","allRecorders"].includes(i)&&!v&&B.type!=="removed"&&u.push(B.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:B,cache:this.observablesCache[s]?.subject?.getValue()?.data??{}})||(M=!0,Object.assign(I,this.handleCollectionChange(B,I)),B.type==="removed"&&(A||(A={type:B.type,ids:[]}),A.ids.push(B.doc.id)))}):M=!0,M&&(["allComments","allReactions","allRecorders"].includes(i)&&u?.length&&(this.commonDbUtilsService.resolveAnnotations({data:u,feature:i}),u=[]),this.commonDbUtilsService.modifyAndSetData({feature:i,data:I,subscriber:a,operation:A})),v=!1}catch(I){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,I),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(I,i,a)}},_=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,_),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(l??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(_,i,a)})}handleCollectionChange(e,t){switch(e.type){case"added":case"modified":t[e.doc.id]=e.doc.data();break;case"removed":delete t?.[e.doc.id];break}return t}setupDocumentListener(e,t,i,a,l){let s=X1(e,t);return gQ(s,d=>{try{let v=d.data()||{};l?.field&&(v=v?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:v,subscriber:a,operation:null})}catch(v){this.handleListenerError(v,i,a)}},d=>this.handleListenerError(d,i,a))}handleListenerError(e,t,i){this.loggingService.catch(`Firestore listener error for ${t}:`,e)}handleRealtimeDbListener(e,t,i){let a=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${e}`),se({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let s=t?.rtdbQuery??[];l=oY(l,...s)}return this.objectValFromChildEvents(l,e).pipe(Xn(s=>(this.loggingService.catch(`RTDB listener error for ${e}:`,s),se({}))),ge(s=>(s===null&&(s={}),s&&typeof s=="object"?Object.entries(s??{}).reduce((v,[u,_])=>(v[u]=this.commonDbUtilsService.addMetadata(_,t),v),{}):this.commonDbUtilsService.addMetadata(s,t))),be(s=>this.commonDbUtilsService.modifyData({feature:e,data:s})),be(s=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:s}),operation:null})))))}pushData(a){return J(this,arguments,function*({feature:e,properties:t,data:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${e}`,"color: green;"),this.performDatabaseOperation(e,t,l=>J(this,null,function*(){if(l.dbRef){let s=S8(l.dbRef);yield qf(s,JSON.parse(JSON.stringify(l.data)))}}),i)}catch(l){this.loggingService.catch(`Error in pushData for ${e}`,l)}})}streamChildAdded({feature:e,properties:t,afterTs:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${e}`,"color: green;"),new Ht(a=>{let l=null,s=!1,d=({db:v})=>{if(!v||s||!this.authService.getUser())return;let u=this.commonDbUtilsService.getDocumentPath({feature:e,properties:t,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:t.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!u)return;let I=Ur(v,u),A=!1,M=ae=>{try{let Ce=ae.val();if(A){if(i!=null&&Ce?.timestamp!=null&&Ce.timestamp<=i)return;a.next(Ce)}}catch(Ce){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,Ce)}},B=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(Ce){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,Ce)}};rY(I,M,B);let q=mg(I,()=>{A=!0},B,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),yD(I,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{s=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),se(null)}}objectValFromChildEvents(e,t){return new Ht(i=>{let a={},l=!1,s=null,d=B=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,B),i.error(B)}catch{}},v=B=>{try{if(!Mr(B,s)){let q=JSON.parse(JSON.stringify(B));s=q,i.next(q)}}catch{}},u=B=>{try{B.key&&(a[B.key]=B.val(),l&&v(h({},a)))}catch{}},_=B=>{try{B.key&&(a[B.key]=B.val(),l&&v(h({},a)))}catch{}},I=B=>{try{B.key&&(delete a[B.key],l&&v(h({},a)))}catch{}},A=B=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};s=q,i.next(q),l=!0}}catch{}};rY(e,u,d),Lve(e,_,d),Uve(e,I,d);let M=mg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),yD(e,"child_added",u),yD(e,"child_changed",_),yD(e,"child_removed",I)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(X(mS),X(qe),X(od),X(tr),X(k),X(zbe),X($n),X(Nt),X(ct),X(An),X(rl),X(Gs),X(ol),X(mv))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vv=(()=>{let o=class o{static uniquifySvgIds(e){let t=`v${++o.idCounter}`,i=/\bid="([^"]+)"/g,a=[],l;for(;(l=i.exec(e))!==null;)a.push(l[1]);let s=e;for(let d of a){let v=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;s=s.replace(new RegExp(`\\bid="${v}"`,"g"),`id="${u}"`),s=s.replace(new RegExp(`url\\(#${v}\\)`,"g"),`url(#${u})`),s=s.replace(new RegExp(`href="#${v}"`,"g"),`href="#${u}"`)}return s}constructor(e,t,i){this.domService=e,this.loggingService=t,this.sanitizer=i,this.emojis={},this.emojisSignal=De({}),this.rawSvgs={};try{this.loggingService.log("%c[WB] Creating CLASS: EmojiService","color: blue;"),Object.keys(o.Icons).forEach(a=>{let l=o.Icons[a];this.rawSvgs[a]=l,this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(l)))}),Object.keys(o.GIF_PATHS).forEach(a=>{let l=`<img src="${o.GIF_PATHS[a]}" alt="${a}" />`;this.emojis[a]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(l))}),this.emojisSignal.set(h({},this.emojis))}catch(a){this.loggingService.catch("Error in EmojiService constructor: ",a)}}getEmoji(e){try{let t=this.rawSvgs[e];return t?this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(t))):this.emojis[e]}catch{return""}}getEmojiFromIconUrl(e){try{return this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(`<img src="${e}" alt="emoji" />`))}catch{return""}}getEmojiFromIconEmoji(e,t){try{let i=`<span class="velt-emoji-icon velt-emoji-icon--emoji">${e}</span>`;return t&&(i=`<span class="velt-emoji-icon velt-emoji-icon--emoji" emoji-id=${t}>${e}</span>`),this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(i))}catch{return""}}setEmojiList(e){try{this.emojis={},this.rawSvgs={},Object.keys(e).forEach(t=>{let i=e[t];if(i.svg)this.rawSvgs[t]=i.svg,this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeSvg(o.uniquifySvgIds(i.svg)));else if(i.url){let a=`<img src="${i.url}" alt="${t}" />`;this.emojis[t]=this.sanitizer.bypassSecurityTrustHtml(this.domService.sanitizeHtml(a))}else i.emoji&&(this.emojis[t]=this.getEmojiFromIconEmoji(this.domService.sanitizeHtml(i.emoji)))}),this.emojisSignal.set(h({},this.emojis))}catch(t){this.loggingService.catch("Error in EmojiService setEmojiList: ",t)}}};o.idCounter=0,o.Icons={RAISED_HANDS:`<svg width="58" height="57" viewBox="0 0 58 57" fill="none" xmlns="http://www.w3.org/2000/svg">
223
223
  <path d="M35.8477 11.6603L40.4962 5.23427" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
224
224
  <path d="M21.8298 11.617L17.4655 6.02428" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
225
225
  <path d="M28.7568 9.77682L28.7761 1" stroke="#B0BEC5" stroke-width="1.92685" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>