@veltdev/sdk-staging 5.0.2-beta.65 → 5.0.2-beta.66

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 +2 -2
package/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '5.0.2-beta.65';
1
+ var SNIPPYLY_VERSION = '5.0.2-beta.66';
2
2
  Promise.allSettled||(Promise.allSettled=function(t){return Promise.all(t.map(function(r){return Promise.resolve(r).then(function(e){return{status:"fulfilled",value:e}}).catch(function(e){return{status:"rejected",reason:e}})}))});
3
3
 
4
4
  var J3e=Object.create;var r6=Object.defineProperty,X3e=Object.defineProperties,Q3e=Object.getOwnPropertyDescriptor,eOe=Object.getOwnPropertyDescriptors,tOe=Object.getOwnPropertyNames,n6=Object.getOwnPropertySymbols,Hte=Object.getPrototypeOf,uB=Object.prototype.hasOwnProperty,zte=Object.prototype.propertyIsEnumerable,nOe=Reflect.get;var Gte=(n,o,r)=>o in n?r6(n,o,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[o]=r,h=(n,o)=>{for(var r in o||={})uB.call(o,r)&&Gte(n,r,o[r]);if(n6)for(var r of n6(o))zte.call(o,r)&&Gte(n,r,o[r]);return n},y=(n,o)=>X3e(n,eOe(o));var Fh=(n,o)=>{var r={};for(var e in n)uB.call(n,e)&&o.indexOf(e)<0&&(r[e]=n[e]);if(n!=null&&n6)for(var e of n6(n))o.indexOf(e)<0&&zte.call(n,e)&&(r[e]=n[e]);return r};var rOe=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),o6=(n,o)=>{for(var r in o)r6(n,r,{get:o[r],enumerable:!0})},oOe=(n,o,r,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of tOe(o))!uB.call(n,t)&&t!==r&&r6(n,t,{get:()=>o[t],enumerable:!(e=Q3e(o,t))||e.enumerable});return n};var Wte=(n,o,r)=>(r=n!=null?J3e(Hte(n)):{},oOe(o||!n||!n.__esModule?r6(r,"default",{value:n,enumerable:!0}):r,n));var Lh=(n,o,r)=>nOe(Hte(n),r,o);var X=(n,o,r)=>new Promise((e,t)=>{var i=c=>{try{l(r.next(c))}catch(d){t(d)}},a=c=>{try{l(r.throw(c))}catch(d){t(d)}},l=c=>c.done?e(c.value):Promise.resolve(c.value).then(i,a);l((r=r.apply(n,o)).next())});var ste=rOe((Ski,cte)=>{"use strict";var Nt={};Nt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Nt.localCName=Nt.generateIdentifier();Nt.splitLines=function(n){return n.trim().split(`
@@ -219,7 +219,7 @@ This typically indicates that your device does not have a healthy Internet conne
219
219
  `)+`
220
220
  )`}copy(o,r){let e=new n;return e.comparator=this.comparator,e.keyedMap=o,e.sortedSet=r,e}};var oL=class{constructor(){this.fa=new gi(Zt.comparator)}track(o){let r=o.doc.key,e=this.fa.get(r);e?o.type!==0&&e.type===3?this.fa=this.fa.insert(r,o):o.type===3&&e.type!==1?this.fa=this.fa.insert(r,{type:e.type,doc:o.doc}):o.type===2&&e.type===2?this.fa=this.fa.insert(r,{type:2,doc:o.doc}):o.type===2&&e.type===0?this.fa=this.fa.insert(r,{type:0,doc:o.doc}):o.type===1&&e.type===0?this.fa=this.fa.remove(r):o.type===1&&e.type===2?this.fa=this.fa.insert(r,{type:1,doc:e.doc}):o.type===0&&e.type===1?this.fa=this.fa.insert(r,{type:2,doc:o.doc}):an(63341,{At:o,ga:e}):this.fa=this.fa.insert(r,o)}pa(){let o=[];return this.fa.inorderTraversal((r,e)=>{o.push(e)}),o}},X1=class n{constructor(o,r,e,t,i,a,l,c,d){this.query=o,this.docs=r,this.oldDocs=e,this.docChanges=t,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=l,this.excludesMetadataChanges=c,this.hasCachedResults=d}static fromInitialDocuments(o,r,e,t,i){let a=[];return r.forEach(l=>{a.push({type:0,doc:l})}),new n(o,r,rL.emptySet(r),a,e,t,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(o){if(!(this.fromCache===o.fromCache&&this.hasCachedResults===o.hasCachedResults&&this.syncStateChanged===o.syncStateChanged&&this.mutatedKeys.isEqual(o.mutatedKeys)&&yL(this.query,o.query)&&this.docs.isEqual(o.docs)&&this.oldDocs.isEqual(o.oldDocs)))return!1;let r=this.docChanges,e=o.docChanges;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t].type!==e[t].type||!r[t].doc.isEqual(e[t].doc))return!1;return!0}};var HJ=class{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(o=>o.ba())}},zJ=class{constructor(){this.queries=kfe(),this.onlineState="Unknown",this.Da=new Set}terminate(){(function(r,e){let t=cn(r),i=t.queries;t.queries=kfe(),i.forEach((a,l)=>{for(let c of l.wa)c.onError(e)})})(this,new Mt(ht.ABORTED,"Firestore shutting down"))}};function kfe(){return new sv(n=>h0e(n),yL)}function $X(n,o){return X(this,null,function*(){let r=cn(n),e=3,t=o.query,i=r.queries.get(t);i?!i.Sa()&&o.ba()&&(e=2):(i=new HJ,e=o.ba()?0:1);try{switch(e){case 0:i.ya=yield r.onListen(t,!0);break;case 1:i.ya=yield r.onListen(t,!1);break;case 2:yield r.onFirstRemoteStoreListen(t)}}catch(a){let l=jX(a,`Initialization of query '${I1(o.query)}' failed`);return void o.onError(l)}r.queries.set(t,i),i.wa.push(o),o.va(r.onlineState),i.ya&&o.Ca(i.ya)&&HX(r)})}function GX(n,o){return X(this,null,function*(){let r=cn(n),e=o.query,t=3,i=r.queries.get(e);if(i){let a=i.wa.indexOf(o);a>=0&&(i.wa.splice(a,1),i.wa.length===0?t=o.ba()?0:1:!i.Sa()&&o.ba()&&(t=2))}switch(t){case 0:return r.queries.delete(e),r.onUnlisten(e,!0);case 1:return r.queries.delete(e),r.onUnlisten(e,!1);case 2:return r.onLastRemoteStoreUnlisten(e);default:return}})}function ize(n,o){let r=cn(n),e=!1;for(let t of o){let i=t.query,a=r.queries.get(i);if(a){for(let l of a.wa)l.Ca(t)&&(e=!0);a.ya=t}}e&&HX(r)}function aze(n,o,r){let e=cn(n),t=e.queries.get(o);if(t)for(let i of t.wa)i.onError(r);e.queries.delete(o)}function HX(n){n.Da.forEach(o=>{o.next()})}var WJ,xfe;(xfe=WJ||(WJ={})).Fa="default",xfe.Cache="cache";var uO=class{constructor(o,r,e){this.query=o,this.Ma=r,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=e||{}}Ca(o){if(!this.options.includeMetadataChanges){let e=[];for(let t of o.docChanges)t.type!==3&&e.push(t);o=new X1(o.query,o.docs,o.oldDocs,e,o.mutatedKeys,o.fromCache,o.syncStateChanged,!0,o.hasCachedResults)}let r=!1;return this.xa?this.Na(o)&&(this.Ma.next(o),r=!0):this.Ba(o,this.onlineState)&&(this.La(o),r=!0),this.Oa=o,r}onError(o){this.Ma.error(o)}va(o){this.onlineState=o;let r=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,o)&&(this.La(this.Oa),r=!0),r}Ba(o,r){if(!o.fromCache||!this.ba())return!0;let e=r!=="Offline";return(!this.options.ka||!e)&&(!o.docs.isEmpty()||o.hasCachedResults||r==="Offline")}Na(o){if(o.docChanges.length>0)return!0;let r=this.Oa&&this.Oa.hasPendingWrites!==o.hasPendingWrites;return!(!o.syncStateChanged&&!r)&&this.options.includeMetadataChanges===!0}La(o){o=X1.fromInitialDocuments(o.query,o.docs,o.mutatedKeys,o.fromCache,o.hasCachedResults),this.xa=!0,this.Ma.next(o)}ba(){return this.options.source!==WJ.Cache}};var iL=class{constructor(o){this.key=o}},aL=class{constructor(o){this.key=o}},qJ=class{constructor(o,r){this.query=o,this.Ha=r,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=Dr(),this.mutatedKeys=Dr(),this.Xa=C0e(o),this.eu=new rL(this.Xa)}get tu(){return this.Ha}nu(o,r){let e=r?r.ru:new oL,t=r?r.eu:this.eu,i=r?r.mutatedKeys:this.mutatedKeys,a=t,l=!1,c=this.query.limitType==="F"&&t.size===this.query.limit?t.last():null,d=this.query.limitType==="L"&&t.size===this.query.limit?t.first():null;if(o.inorderTraversal((m,u)=>{let _=t.get(m),I=xO(this.query,u)?u:null,A=!!_&&this.mutatedKeys.has(_.key),M=!!I&&(I.hasLocalMutations||this.mutatedKeys.has(I.key)&&I.hasCommittedMutations),B=!1;_&&I?_.data.isEqual(I.data)?A!==M&&(e.track({type:3,doc:I}),B=!0):this.iu(_,I)||(e.track({type:2,doc:I}),B=!0,(c&&this.Xa(I,c)>0||d&&this.Xa(I,d)<0)&&(l=!0)):!_&&I?(e.track({type:0,doc:I}),B=!0):_&&!I&&(e.track({type:1,doc:_}),B=!0,(c||d)&&(l=!0)),B&&(I?(a=a.add(I),i=M?i.add(m):i.delete(m)):(a=a.delete(m),i=i.delete(m)))}),this.query.limit!==null)for(;a.size>this.query.limit;){let m=this.query.limitType==="F"?a.last():a.first();a=a.delete(m.key),i=i.delete(m.key),e.track({type:1,doc:m})}return{eu:a,ru:e,Ds:l,mutatedKeys:i}}iu(o,r){return o.hasLocalMutations&&r.hasCommittedMutations&&!r.hasLocalMutations}applyChanges(o,r,e,t){let i=this.eu;this.eu=o.eu,this.mutatedKeys=o.mutatedKeys;let a=o.ru.pa();a.sort((m,u)=>(function(I,A){let M=B=>{switch(B){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return an(20277,{At:B})}};return M(I)-M(A)})(m.type,u.type)||this.Xa(m.doc,u.doc)),this.su(e),t=t!=null&&t;let l=r&&!t?this.ou():[],c=this.Za.size===0&&this.current&&!t?1:0,d=c!==this.Ya;return this.Ya=c,a.length!==0||d?{snapshot:new X1(this.query,o.eu,i,a,o.mutatedKeys,c===0,d,!1,!!e&&e.resumeToken.approximateByteSize()>0),_u:l}:{_u:l}}va(o){return this.current&&o==="Offline"?(this.current=!1,this.applyChanges({eu:this.eu,ru:new oL,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(o){return!this.Ha.has(o)&&!!this.eu.has(o)&&!this.eu.get(o).hasLocalMutations}su(o){o&&(o.addedDocuments.forEach(r=>this.Ha=this.Ha.add(r)),o.modifiedDocuments.forEach(r=>{}),o.removedDocuments.forEach(r=>this.Ha=this.Ha.delete(r)),this.current=o.current)}ou(){if(!this.current)return[];let o=this.Za;this.Za=Dr(),this.eu.forEach(e=>{this.au(e.key)&&(this.Za=this.Za.add(e.key))});let r=[];return o.forEach(e=>{this.Za.has(e)||r.push(new aL(e))}),this.Za.forEach(e=>{o.has(e)||r.push(new iL(e))}),r}uu(o){this.Ha=o.qs,this.Za=Dr();let r=this.nu(o.documents);return this.applyChanges(r,!0)}cu(){return X1.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,this.Ya===0,this.hasCachedResults)}},aS="SyncEngine",YJ=class{constructor(o,r,e){this.query=o,this.targetId=r,this.view=e}},KJ=class{constructor(o){this.key=o,this.lu=!1}},ZJ=class{constructor(o,r,e,t,i,a){this.localStore=o,this.remoteStore=r,this.eventManager=e,this.sharedClientState=t,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.hu={},this.Pu=new sv(l=>h0e(l),yL),this.Tu=new Map,this.Iu=new Set,this.du=new gi(Zt.comparator),this.Eu=new Map,this.Au=new dO,this.Ru={},this.Vu=new Map,this.mu=K1.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return this.fu===!0}};function lze(n,o,r=!0){return X(this,null,function*(){let e=EL(n),t,i=e.Pu.get(o);return i?(e.sharedClientState.addLocalQueryTarget(i.targetId),t=i.view.cu()):t=yield uCe(e,o,r,!0),t})}function cze(n,o){return X(this,null,function*(){let r=EL(n);yield uCe(r,o,!0,!1)})}function uCe(n,o,r,e){return X(this,null,function*(){let t=yield ZF(n.localStore,As(o)),i=t.targetId,a=n.sharedClientState.addLocalQueryTarget(i,r),l;return e&&(l=yield zX(n,o,i,a==="current",t.resumeToken)),n.isPrimaryClient&&r&&IL(n.remoteStore,t),l})}function zX(n,o,r,e,t){return X(this,null,function*(){n.gu=(u,_,I)=>(function(M,B,q,ae){return X(this,null,function*(){let be=B.view.nu(q);be.Ds&&(be=yield DJ(M.localStore,B.query,!1).then(({documents:Ce})=>B.view.nu(Ce,be)));let re=ae&&ae.targetChanges.get(B.targetId),_e=ae&&ae.targetMismatches.get(B.targetId)!=null,Ie=B.view.applyChanges(be,M.isPrimaryClient,re,_e);return JJ(M,B.targetId,Ie._u),Ie.snapshot})})(n,u,_,I);let i=yield DJ(n.localStore,o,!0),a=new qJ(o,i.qs),l=a.nu(i.documents),c=aO.createSynthesizedTargetChangeForCurrentChange(r,e&&n.onlineState!=="Offline",t),d=a.applyChanges(l,n.isPrimaryClient,c);JJ(n,r,d._u);let m=new YJ(o,r,a);return n.Pu.set(o,m),n.Tu.has(r)?n.Tu.get(r).push(o):n.Tu.set(r,[o]),d.snapshot})}function sze(n,o,r){return X(this,null,function*(){let e=cn(n),t=e.Pu.get(o),i=e.Tu.get(t.targetId);if(i.length>1)return e.Tu.set(t.targetId,i.filter(a=>!yL(a,o))),void e.Pu.delete(o);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(t.targetId),e.sharedClientState.isActiveQueryTarget(t.targetId)||(yield Z1(e.localStore,t.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(t.targetId),r&&J1(e.remoteStore,t.targetId),Q1(e,t.targetId)}).catch(Sp))):(Q1(e,t.targetId),yield Z1(e.localStore,t.targetId,!0))})}function dze(n,o){return X(this,null,function*(){let r=cn(n),e=r.Pu.get(o),t=r.Tu.get(e.targetId);r.isPrimaryClient&&t.length===1&&(r.sharedClientState.removeLocalQueryTarget(e.targetId),J1(r.remoteStore,e.targetId))})}function vze(n,o,r){return X(this,null,function*(){let e=KX(n);try{let t=yield(function(a,l){let c=cn(a),d=_i.now(),m=l.reduce((I,A)=>I.add(A.key),Dr()),u,_;return c.persistence.runTransaction("Locally write mutations","readwrite",I=>{let A=Os(),M=Dr();return c.Os.getEntries(I,m).next(B=>{A=B,A.forEach((q,ae)=>{ae.isValidDocument()||(M=M.add(q))})}).next(()=>c.localDocuments.getOverlayedDocuments(I,A)).next(B=>{u=B;let q=[];for(let ae of l){let be=kHe(ae,u.get(ae.key).overlayedDocument);be!=null&&q.push(new dv(ae.key,be,c0e(be.value.mapValue),wl.exists(!0)))}return c.mutationQueue.addMutationBatch(I,d,q,l)}).next(B=>{_=B;let q=B.applyToLocalDocumentSet(u,M);return c.documentOverlayCache.saveOverlays(I,B.batchId,q)})}).then(()=>({batchId:_.batchId,changes:_0e(u)}))})(e.localStore,o);e.sharedClientState.addPendingMutation(t.batchId),(function(a,l,c){let d=a.Ru[a.currentUser.toKey()];d||(d=new gi(qn)),d=d.insert(l,c),a.Ru[a.currentUser.toKey()]=d})(e,t.batchId,r),yield xp(e,t.changes),yield oS(e.remoteStore)}catch(t){let i=jX(t,"Failed to persist write");r.reject(i)}})}function pCe(n,o){return X(this,null,function*(){let r=cn(n);try{let e=yield zHe(r.localStore,o);o.targetChanges.forEach((t,i)=>{let a=r.Eu.get(i);a&&(dn(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?a.lu=!0:t.modifiedDocuments.size>0?dn(a.lu,14607):t.removedDocuments.size>0&&(dn(a.lu,42227),a.lu=!1))}),yield xp(r,e,o)}catch(e){yield Sp(e)}})}function Ife(n,o,r){let e=cn(n);if(e.isPrimaryClient&&r===0||!e.isPrimaryClient&&r===1){let t=[];e.Pu.forEach((i,a)=>{let l=a.view.va(o);l.snapshot&&t.push(l.snapshot)}),(function(a,l){let c=cn(a);c.onlineState=l;let d=!1;c.queries.forEach((m,u)=>{for(let _ of u.wa)_.va(l)&&(d=!0)}),d&&HX(c)})(e.eventManager,o),t.length&&e.hu.J_(t),e.onlineState=o,e.isPrimaryClient&&e.sharedClientState.setOnlineState(o)}}function mze(n,o,r){return X(this,null,function*(){let e=cn(n);e.sharedClientState.updateQueryState(o,"rejected",r);let t=e.Eu.get(o),i=t&&t.key;if(i){let a=new gi(Zt.comparator);a=a.insert(i,Fa.newNoDocument(i,En.min()));let l=Dr().add(i),c=new iO(En.min(),new Map,new gi(qn),a,l);yield pCe(e,c),e.du=e.du.remove(i),e.Eu.delete(o),YX(e)}else yield Z1(e.localStore,o,!1).then(()=>Q1(e,o,r)).catch(Sp)})}function gze(n,o){return X(this,null,function*(){let r=cn(n),e=o.batch.batchId;try{let t=yield HHe(r.localStore,o);qX(r,e,null),WX(r,e),r.sharedClientState.updateMutationState(e,"acknowledged"),yield xp(r,t)}catch(t){yield Sp(t)}})}function uze(n,o,r){return X(this,null,function*(){let e=cn(n);try{let t=yield(function(a,l){let c=cn(a);return c.persistence.runTransaction("Reject batch","readwrite-primary",d=>{let m;return c.mutationQueue.lookupMutationBatch(d,l).next(u=>(dn(u!==null,37113),m=u.keys(),c.mutationQueue.removeMutationBatch(d,u))).next(()=>c.mutationQueue.performConsistencyCheck(d)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(d,m,l)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(d,m)).next(()=>c.localDocuments.getDocuments(d,m))})})(e.localStore,o);qX(e,o,r),WX(e,o),e.sharedClientState.updateMutationState(o,"rejected",r),yield xp(e,t)}catch(t){yield Sp(t)}})}function WX(n,o){(n.Vu.get(o)||[]).forEach(r=>{r.resolve()}),n.Vu.delete(o)}function qX(n,o,r){let e=cn(n),t=e.Ru[e.currentUser.toKey()];if(t){let i=t.get(o);i&&(r?i.reject(r):i.resolve(),t=t.remove(o)),e.Ru[e.currentUser.toKey()]=t}}function Q1(n,o,r=null){n.sharedClientState.removeLocalQueryTarget(o);for(let e of n.Tu.get(o))n.Pu.delete(e),r&&n.hu.pu(e,r);n.Tu.delete(o),n.isPrimaryClient&&n.Au.zr(o).forEach(e=>{n.Au.containsKey(e)||hCe(n,e)})}function hCe(n,o){n.Iu.delete(o.path.canonicalString());let r=n.du.get(o);r!==null&&(J1(n.remoteStore,r),n.du=n.du.remove(o),n.Eu.delete(r),YX(n))}function JJ(n,o,r){for(let e of r)e instanceof iL?(n.Au.addReference(e.key,o),pze(n,e)):e instanceof aL?(Rt(aS,"Document no longer in limbo: "+e.key),n.Au.removeReference(e.key,o),n.Au.containsKey(e.key)||hCe(n,e.key)):an(19791,{yu:e})}function pze(n,o){let r=o.key,e=r.path.canonicalString();n.du.get(r)||n.Iu.has(e)||(Rt(aS,"New document in limbo: "+r),n.Iu.add(e),YX(n))}function YX(n){for(;n.Iu.size>0&&n.du.size<n.maxConcurrentLimboResolutions;){let o=n.Iu.values().next().value;n.Iu.delete(o);let r=new Zt(ro.fromString(o)),e=n.mu.next();n.Eu.set(e,new KJ(r)),n.du=n.du.insert(r,e),IL(n.remoteStore,new Y1(As(kO(r.path)),e,"TargetPurposeLimboResolution",Ts.ue))}}function xp(n,o,r){return X(this,null,function*(){let e=cn(n),t=[],i=[],a=[];e.Pu.isEmpty()||(e.Pu.forEach((l,c)=>{a.push(e.gu(c,o,r).then(d=>{var m;if((d||r)&&e.isPrimaryClient){let u=d?!d.fromCache:(m=r?.targetChanges.get(c.targetId))===null||m===void 0?void 0:m.current;e.sharedClientState.updateQueryState(c.targetId,u?"current":"not-current")}if(d){t.push(d);let u=EJ.Es(c.targetId,d);i.push(u)}}))}),yield Promise.all(a),e.hu.J_(t),yield(function(c,d){return X(this,null,function*(){let m=cn(c);try{yield m.persistence.runTransaction("notifyLocalViewChanges","readwrite",u=>dt.forEach(d,_=>dt.forEach(_.Is,I=>m.persistence.referenceDelegate.addReference(u,_.targetId,I)).next(()=>dt.forEach(_.ds,I=>m.persistence.referenceDelegate.removeReference(u,_.targetId,I)))))}catch(u){if(!yp(u))throw u;Rt(LX,"Failed to update sequence numbers: "+u)}for(let u of d){let _=u.targetId;if(!u.fromCache){let I=m.Fs.get(_),A=I.snapshotVersion,M=I.withLastLimboFreeSnapshotVersion(A);m.Fs=m.Fs.insert(_,M)}}})})(e.localStore,i))})}function hze(n,o){return X(this,null,function*(){let r=cn(n);if(!r.currentUser.isEqual(o)){Rt(aS,"User change. New user:",o.toKey());let e=yield eCe(r.localStore,o);r.currentUser=o,(function(i,a){i.Vu.forEach(l=>{l.forEach(c=>{c.reject(new Mt(ht.CANCELLED,a))})}),i.Vu.clear()})(r,"'waitForPendingWrites' promise is rejected due to a user change."),r.sharedClientState.handleUserChange(o,e.removedBatchIds,e.addedBatchIds),yield xp(r,e.Bs)}})}function fze(n,o){let r=cn(n),e=r.Eu.get(o);if(e&&e.lu)return Dr().add(e.key);{let t=Dr(),i=r.Tu.get(o);if(!i)return t;for(let a of i){let l=r.Pu.get(a);t=t.unionWith(l.view.tu)}return t}}function Cze(n,o){return X(this,null,function*(){let r=cn(n),e=yield DJ(r.localStore,o.query,!0),t=o.view.uu(e);return r.isPrimaryClient&&JJ(r,o.targetId,t._u),t})}function bze(n,o){return X(this,null,function*(){let r=cn(n);return rCe(r.localStore,o).then(e=>xp(r,e))})}function _ze(n,o,r,e){return X(this,null,function*(){let t=cn(n),i=yield(function(l,c){let d=cn(l),m=cn(d.mutationQueue);return d.persistence.runTransaction("Lookup mutation documents","readonly",u=>m.Xn(u,c).next(_=>_?d.localDocuments.getDocuments(u,_):dt.resolve(null)))})(t.localStore,o);i!==null?(r==="pending"?yield oS(t.remoteStore):r==="acknowledged"||r==="rejected"?(qX(t,o,e||null),WX(t,o),(function(l,c){cn(cn(l).mutationQueue).rr(c)})(t.localStore,o)):an(6720,"Unknown batchState",{wu:r}),yield xp(t,i)):Rt(aS,"Cannot apply mutation batch with id: "+o)})}function Sze(n,o){return X(this,null,function*(){let r=cn(n);if(EL(r),KX(r),o===!0&&r.fu!==!0){let e=r.sharedClientState.getAllActiveQueryTargets(),t=yield Efe(r,e.toArray());r.fu=!0,yield $J(r.remoteStore,!0);for(let i of t)IL(r.remoteStore,i)}else if(o===!1&&r.fu!==!1){let e=[],t=Promise.resolve();r.Tu.forEach((i,a)=>{r.sharedClientState.isLocalQueryTarget(a)?e.push(a):t=t.then(()=>(Q1(r,a),Z1(r.localStore,a,!0))),J1(r.remoteStore,a)}),yield t,yield Efe(r,e),(function(a){let l=cn(a);l.Eu.forEach((c,d)=>{J1(l.remoteStore,d)}),l.Au.jr(),l.Eu=new Map,l.du=new gi(Zt.comparator)})(r),r.fu=!1,yield $J(r.remoteStore,!1)}})}function Efe(n,o,r){return X(this,null,function*(){let e=cn(n),t=[],i=[];for(let a of o){let l,c=e.Tu.get(a);if(c&&c.length!==0){l=yield ZF(e.localStore,As(c[0]));for(let d of c){let m=e.Pu.get(d),u=yield Cze(e,m);u.snapshot&&i.push(u.snapshot)}}else{let d=yield nCe(e.localStore,a);l=yield ZF(e.localStore,d),yield zX(e,fCe(d),a,!1,l.resumeToken)}t.push(l)}return e.hu.J_(i),t})}function fCe(n){return u0e(n.path,n.collectionGroup,n.orderBy,n.filters,n.limit,"F",n.startAt,n.endAt)}function yze(n){return(function(r){return cn(cn(r).persistence).Ps()})(cn(n).localStore)}function kze(n,o,r,e){return X(this,null,function*(){let t=cn(n);if(t.fu)return void Rt(aS,"Ignoring unexpected query state notification.");let i=t.Tu.get(o);if(i&&i.length>0)switch(r){case"current":case"not-current":{let a=yield rCe(t.localStore,f0e(i[0])),l=iO.createSynthesizedRemoteEventForCurrentChange(o,r==="current",ka.EMPTY_BYTE_STRING);yield xp(t,a,l);break}case"rejected":yield Z1(t.localStore,o,!0),Q1(t,o,e);break;default:an(64155,r)}})}function xze(n,o,r){return X(this,null,function*(){let e=EL(n);if(e.fu){for(let t of o){if(e.Tu.has(t)&&e.sharedClientState.isActiveQueryTarget(t)){Rt(aS,"Adding an already active target "+t);continue}let i=yield nCe(e.localStore,t),a=yield ZF(e.localStore,i);yield zX(e,fCe(i),a.targetId,!1,a.resumeToken),IL(e.remoteStore,a)}for(let t of r)e.Tu.has(t)&&(yield Z1(e.localStore,t,!1).then(()=>{J1(e.remoteStore,t),Q1(e,t)}).catch(Sp))}})}function EL(n){let o=cn(n);return o.remoteStore.remoteSyncer.applyRemoteEvent=pCe.bind(null,o),o.remoteStore.remoteSyncer.getRemoteKeysForTarget=fze.bind(null,o),o.remoteStore.remoteSyncer.rejectListen=mze.bind(null,o),o.hu.J_=ize.bind(null,o.eventManager),o.hu.pu=aze.bind(null,o.eventManager),o}function KX(n){let o=cn(n);return o.remoteStore.remoteSyncer.applySuccessfulWrite=gze.bind(null,o),o.remoteStore.remoteSyncer.rejectFailedWrite=uze.bind(null,o),o}var ZX=(()=>{class n{constructor(){this.kind="memory",this.synchronizeTabs=!1}initialize(r){return X(this,null,function*(){this.serializer=kL(r.databaseInfo.databaseId),this.sharedClientState=this.bu(r),this.persistence=this.Du(r),yield this.persistence.start(),this.localStore=this.vu(r),this.gcScheduler=this.Cu(r,this.localStore),this.indexBackfillerScheduler=this.Fu(r,this.localStore)})}Cu(r,e){return null}Fu(r,e){return null}vu(r){return Q0e(this.persistence,new KF,r.initialUser,this.serializer)}Du(r){return new vO(qF.Vi,this.serializer)}bu(r){return new QF}terminate(){return X(this,null,function*(){var r,e;(r=this.gcScheduler)===null||r===void 0||r.stop(),(e=this.indexBackfillerScheduler)===null||e===void 0||e.stop(),this.sharedClientState.shutdown(),yield this.persistence.shutdown()})}}return n.provider={build:()=>new n},n})(),XJ=class extends ZX{constructor(o){super(),this.cacheSizeBytes=o}Cu(o,r){dn(this.persistence.referenceDelegate instanceof YF,46915);let e=this.persistence.referenceDelegate.garbageCollector;return new HF(e,o.asyncQueue,r)}Du(o){let r=this.cacheSizeBytes!==void 0?Kc.withCacheSize(this.cacheSizeBytes):Kc.DEFAULT;return new vO(e=>YF.Vi(e,r),this.serializer)}},lL=class n extends ZX{constructor(o,r,e){super(),this.Mu=o,this.cacheSizeBytes=r,this.forceOwnership=e,this.kind="persistent",this.synchronizeTabs=!1}initialize(o){return X(this,null,function*(){yield Lh(n.prototype,this,"initialize").call(this,o),yield this.Mu.initialize(this,o),yield KX(this.Mu.syncEngine),yield oS(this.Mu.remoteStore),yield this.persistence.ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))})}vu(o){return Q0e(this.persistence,new KF,o.initialUser,this.serializer)}Cu(o,r){let e=this.persistence.referenceDelegate.garbageCollector;return new HF(e,o.asyncQueue,r)}Fu(o,r){let e=new kZ(r,this.persistence);return new yZ(o.asyncQueue,e)}Du(o){let r=X0e(o.databaseInfo.databaseId,o.databaseInfo.persistenceKey),e=this.cacheSizeBytes!==void 0?Kc.withCacheSize(this.cacheSizeBytes):Kc.DEFAULT;return new IJ(this.synchronizeTabs,r,o.clientId,e,o.asyncQueue,cCe(),CF(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(o){return new QF}},QJ=class n extends lL{constructor(o,r){super(o,r,!1),this.Mu=o,this.cacheSizeBytes=r,this.synchronizeTabs=!0}initialize(o){return X(this,null,function*(){yield Lh(n.prototype,this,"initialize").call(this,o);let r=this.Mu.syncEngine;this.sharedClientState instanceof H3&&(this.sharedClientState.syncEngine={Do:_ze.bind(null,r),vo:kze.bind(null,r),Co:xze.bind(null,r),Ps:yze.bind(null,r),bo:bze.bind(null,r)},yield this.sharedClientState.start()),yield this.persistence.ji(e=>X(this,null,function*(){yield Sze(this.Mu.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))})}bu(o){let r=cCe();if(!H3.C(r))throw new Mt(ht.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let e=X0e(o.databaseInfo.databaseId,o.databaseInfo.persistenceKey);return new H3(r,o.asyncQueue,e,o.clientId,o.initialUser)}},JX=(()=>{class n{initialize(r,e){return X(this,null,function*(){this.localStore||(this.localStore=r.localStore,this.sharedClientState=r.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!r.synchronizeTabs),this.sharedClientState.onlineStateHandler=t=>Ife(this.syncEngine,t,1),this.remoteStore.remoteSyncer.handleCredentialChange=hze.bind(null,this.syncEngine),yield $J(this.remoteStore,this.syncEngine.isPrimaryClient))})}createEventManager(r){return(function(){return new zJ})()}createDatastore(r){let e=kL(r.databaseInfo.databaseId),t=(function(a){return new NJ(a)})(r.databaseInfo);return(function(a,l,c,d){return new VJ(a,l,c,d)})(r.authCredentials,r.appCheckCredentials,t,e)}createRemoteStore(r){return(function(t,i,a,l,c){return new jJ(t,i,a,l,c)})(this.localStore,this.datastore,r.asyncQueue,e=>Ife(this.syncEngine,e,0),(function(){return eL.C()?new eL:new AJ})())}createSyncEngine(r,e){return(function(i,a,l,c,d,m,u){let _=new ZJ(i,a,l,c,d,m);return u&&(_.fu=!0),_})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,r.initialUser,r.maxConcurrentLimboResolutions,e)}terminate(){return X(this,null,function*(){var r,e;yield(function(i){return X(this,null,function*(){let a=cn(i);Rt(V0,"RemoteStore shutting down."),a.Ia.add(5),yield IO(a),a.Ea.shutdown(),a.Aa.set("Unknown")})})(this.remoteStore),(r=this.datastore)===null||r===void 0||r.terminate(),(e=this.eventManager)===null||e===void 0||e.terminate()})}}return n.provider={build:()=>new n},n})();var pO=class{constructor(o){this.observer=o,this.muted=!1}next(o){this.muted||this.observer.next&&this.xu(this.observer.next,o)}error(o){this.muted||(this.observer.error?this.xu(this.observer.error,o):ia("Uncaught Error in snapshot listener:",o.toString()))}Ou(){this.muted=!0}xu(o,r){setTimeout(()=>{this.muted||o(r)},0)}};var eX=class{constructor(o){this.datastore=o,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}lookup(o){return X(this,null,function*(){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new Mt(ht.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let r=yield(function(t,i){return X(this,null,function*(){let a=cn(t),l={documents:i.map(u=>lO(a.serializer,u))},c=yield a.Jo("BatchGetDocuments",a.serializer.databaseId,ro.emptyPath(),l,i.length),d=new Map;c.forEach(u=>{let _=OHe(a.serializer,u);d.set(_.key.toString(),_)});let m=[];return i.forEach(u=>{let _=d.get(u.toString());dn(!!_,55234,{key:u}),m.push(_)}),m})})(this.datastore,o);return r.forEach(e=>this.recordVersion(e)),r})}set(o,r){this.write(r.toMutation(o,this.precondition(o))),this.writtenDocs.add(o.toString())}update(o,r){try{this.write(r.toMutation(o,this.preconditionForUpdate(o)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(o.toString())}delete(o){this.write(new F0(o,this.precondition(o))),this.writtenDocs.add(o.toString())}commit(){return X(this,null,function*(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let o=this.readVersions;this.mutations.forEach(r=>{o.delete(r.key.toString())}),o.forEach((r,e)=>{let t=Zt.fromPath(e);this.mutations.push(new nO(t,this.precondition(t)))}),yield(function(e,t){return X(this,null,function*(){let i=cn(e),a={writes:t.map(l=>cO(i.serializer,l))};yield i.Wo("Commit",i.serializer.databaseId,ro.emptyPath(),a)})})(this.datastore,this.mutations),this.committed=!0})}recordVersion(o){let r;if(o.isFoundDocument())r=o.version;else{if(!o.isNoDocument())throw an(50498,{Wu:o.constructor.name});r=En.min()}let e=this.readVersions.get(o.key.toString());if(e){if(!r.isEqual(e))throw new Mt(ht.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(o.key.toString(),r)}precondition(o){let r=this.readVersions.get(o.toString());return!this.writtenDocs.has(o.toString())&&r?r.isEqual(En.min())?wl.exists(!1):wl.updateTime(r):wl.none()}preconditionForUpdate(o){let r=this.readVersions.get(o.toString());if(!this.writtenDocs.has(o.toString())&&r){if(r.isEqual(En.min()))throw new Mt(ht.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return wl.updateTime(r)}return wl.exists(!0)}write(o){this.ensureCommitNotCalled(),this.mutations.push(o)}ensureCommitNotCalled(){}};var tX=class{constructor(o,r,e,t,i){this.asyncQueue=o,this.datastore=r,this.options=e,this.updateFunction=t,this.deferred=i,this.Gu=e.maxAttempts,this.F_=new gO(this.asyncQueue,"transaction_retry")}zu(){this.Gu-=1,this.ju()}ju(){this.F_.g_(()=>X(this,null,function*(){let o=new eX(this.datastore),r=this.Ju(o);r&&r.then(e=>{this.asyncQueue.enqueueAndForget(()=>o.commit().then(()=>{this.deferred.resolve(e)}).catch(t=>{this.Hu(t)}))}).catch(e=>{this.Hu(e)})}))}Ju(o){try{let r=this.updateFunction(o);return!_O(r)&&r.catch&&r.then?r:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(r){return this.deferred.reject(r),null}}Hu(o){this.Gu>0&&this.Yu(o)?(this.Gu-=1,this.asyncQueue.enqueueAndForget(()=>(this.ju(),Promise.resolve()))):this.deferred.reject(o)}Yu(o){if(o.name==="FirebaseError"){let r=o.code;return r==="aborted"||r==="failed-precondition"||r==="already-exists"||!D0e(r)}return!1}};var _p="FirestoreClient",nX=class{constructor(o,r,e,t,i){this.authCredentials=o,this.appCheckCredentials=r,this.asyncQueue=e,this.databaseInfo=t,this.user=Sa.UNAUTHENTICATED,this.clientId=z3.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(e,a=>X(this,null,function*(){Rt(_p,"Received user=",a.uid),yield this.authCredentialListener(a),this.user=a})),this.appCheckCredentials.start(e,a=>(Rt(_p,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(o){this.authCredentialListener=o}setAppCheckTokenChangeListener(o){this.appCheckCredentialListener=o}terminate(){this.asyncQueue.enterRestrictedMode();let o=new Zc;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(()=>X(this,null,function*(){try{this._onlineComponents&&(yield this._onlineComponents.terminate()),this._offlineComponents&&(yield this._offlineComponents.terminate()),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),o.resolve()}catch(r){let e=jX(r,"Failed to shutdown persistence");o.reject(e)}})),o.promise}};function vZ(n,o){return X(this,null,function*(){n.asyncQueue.verifyOperationInProgress(),Rt(_p,"Initializing OfflineComponentProvider");let r=n.configuration;yield o.initialize(r);let e=r.initialUser;n.setCredentialChangeListener(t=>X(null,null,function*(){e.isEqual(t)||(yield eCe(o.localStore,t),e=t)})),o.persistence.setDatabaseDeletedListener(()=>{Og("Terminating Firestore due to IndexedDb database deletion"),n.terminate().then(()=>{Rt("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(t=>{Og("Terminating Firestore due to IndexedDb database deletion failed",t)})}),n._offlineComponents=o})}function wfe(n,o){return X(this,null,function*(){n.asyncQueue.verifyOperationInProgress();let r=yield Ize(n);Rt(_p,"Initializing OnlineComponentProvider"),yield o.initialize(r,n.configuration),n.setCredentialChangeListener(e=>yfe(o.remoteStore,e)),n.setAppCheckTokenChangeListener((e,t)=>yfe(o.remoteStore,t)),n._onlineComponents=o})}function Ize(n){return X(this,null,function*(){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){Rt(_p,"Using user provided OfflineComponentProvider");try{yield vZ(n,n._uninitializedComponentsProvider._offline)}catch(o){let r=o;if(!(function(t){return t.name==="FirebaseError"?t.code===ht.FAILED_PRECONDITION||t.code===ht.UNIMPLEMENTED:!(typeof DOMException<"u"&&t instanceof DOMException)||t.code===22||t.code===20||t.code===11})(r))throw r;Og("Error using user provided cache. Falling back to memory cache: "+r),yield vZ(n,new ZX)}}else Rt(_p,"Using default OfflineComponentProvider"),yield vZ(n,new XJ(void 0));return n._offlineComponents})}function XX(n){return X(this,null,function*(){return n._onlineComponents||(n._uninitializedComponentsProvider?(Rt(_p,"Using user provided OnlineComponentProvider"),yield wfe(n,n._uninitializedComponentsProvider._online)):(Rt(_p,"Using default OnlineComponentProvider"),yield wfe(n,new JX))),n._onlineComponents})}function Eze(n){return XX(n).then(o=>o.syncEngine)}function CCe(n){return XX(n).then(o=>o.datastore)}function cL(n){return X(this,null,function*(){let o=yield XX(n),r=o.eventManager;return r.onListen=lze.bind(null,o.syncEngine),r.onUnlisten=sze.bind(null,o.syncEngine),r.onFirstRemoteStoreListen=cze.bind(null,o.syncEngine),r.onLastRemoteStoreUnlisten=dze.bind(null,o.syncEngine),r})}function wze(n,o,r={}){let e=new Zc;return n.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){return(function(i,a,l,c,d){let m=new pO({next:_=>{m.Ou(),a.enqueueAndForget(()=>GX(i,u));let I=_.docs.has(l);!I&&_.fromCache?d.reject(new Mt(ht.UNAVAILABLE,"Failed to get document because the client is offline.")):I&&_.fromCache&&c&&c.source==="server"?d.reject(new Mt(ht.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):d.resolve(_)},error:_=>d.reject(_)}),u=new uO(kO(l.path),m,{includeMetadataChanges:!0,ka:!0});return $X(i,u)})(yield cL(n),n.asyncQueue,o,r,e)})),e.promise}function Tze(n,o,r={}){let e=new Zc;return n.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){return(function(i,a,l,c,d){let m=new pO({next:_=>{m.Ou(),a.enqueueAndForget(()=>GX(i,u)),_.fromCache&&c.source==="server"?d.reject(new Mt(ht.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):d.resolve(_)},error:_=>d.reject(_)}),u=new uO(l,m,{includeMetadataChanges:!0,ka:!0});return $X(i,u)})(yield cL(n),n.asyncQueue,o,r,e)})),e.promise}function Dze(n,o,r){let e=new Zc;return n.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){try{let t=yield CCe(n);e.resolve((function(a,l,c){return X(this,null,function*(){var d;let m=cn(a),{request:u,ft:_,parent:I}=PHe(m.serializer,mHe(l),c);m.connection.Qo||delete u.parent;let A=(yield m.Jo("RunAggregationQuery",m.serializer.databaseId,I,u,1)).filter(B=>!!B.result);dn(A.length===1,64727);let M=(d=A[0].result)===null||d===void 0?void 0:d.aggregateFields;return Object.keys(M).reduce((B,q)=>(B[_[q]]=M[q],B),{})})})(t,o,r))}catch(t){e.reject(t)}})),e.promise}function bCe(n){let o={};return n.timeoutSeconds!==void 0&&(o.timeoutSeconds=n.timeoutSeconds),o}var Tfe=new Map;var _Ce="firestore.googleapis.com",Dfe=!0,sL=class{constructor(o){var r,e;if(o.host===void 0){if(o.ssl!==void 0)throw new Mt(ht.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=_Ce,this.ssl=Dfe}else this.host=o.host,this.ssl=(r=o.ssl)!==null&&r!==void 0?r:Dfe;if(this.isUsingEmulator=o.emulatorOptions!==void 0,this.credentials=o.credentials,this.ignoreUndefinedProperties=!!o.ignoreUndefinedProperties,this.localCache=o.localCache,o.cacheSizeBytes===void 0)this.cacheSizeBytes=z0e;else{if(o.cacheSizeBytes!==-1&&o.cacheSizeBytes<K0e)throw new Mt(ht.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=o.cacheSizeBytes}PGe("experimentalForceLongPolling",o.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",o.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!o.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:o.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!o.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=bCe((e=o.experimentalLongPollingOptions)!==null&&e!==void 0?e:{}),(function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new Mt(ht.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new Mt(ht.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new Mt(ht.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!o.useFetchStreams}isEqual(o){return this.host===o.host&&this.ssl===o.ssl&&this.credentials===o.credentials&&this.cacheSizeBytes===o.cacheSizeBytes&&this.experimentalForceLongPolling===o.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===o.experimentalAutoDetectLongPolling&&(function(e,t){return e.timeoutSeconds===t.timeoutSeconds})(this.experimentalLongPollingOptions,o.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===o.ignoreUndefinedProperties&&this.useFetchStreams===o.useFetchStreams}},B0=class{constructor(o,r,e,t){this._authCredentials=o,this._appCheckCredentials=r,this._databaseId=e,this._app=t,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new sL({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new Mt(ht.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!=="notTerminated"}_setSettings(o){if(this._settingsFrozen)throw new Mt(ht.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new sL(o),this._emulatorOptions=o.emulatorOptions||{},o.credentials!==void 0&&(this._authCredentials=(function(e){if(!e)return new mZ;switch(e.type){case"firstParty":return new hZ(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new Mt(ht.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(o.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}_restart(){return X(this,null,function*(){this._terminateTask==="notTerminated"?yield this._terminate():this._terminateTask="notTerminated"})}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(r){let e=Tfe.get(r);e&&(Rt("ComponentProvider","Removing Datastore"),Tfe.delete(r),e.terminate())})(this),Promise.resolve()}};function SCe(n,o,r,e={}){var t;n=Jc(n,B0);let i=zl(o),a=n._getSettings(),l=Object.assign(Object.assign({},a),{emulatorOptions:n._getEmulatorOptions()}),c=`${o}:${r}`;i&&(Gv(`https://${c}`),ug("Firestore",!0)),a.host!==_Ce&&a.host!==c&&Og("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let d=Object.assign(Object.assign({},a),{host:c,ssl:i,emulatorOptions:e});if(!Yd(d,l)&&(n._setSettings(d),e.mockUserToken)){let m,u;if(typeof e.mockUserToken=="string")m=e.mockUserToken,u=Sa.MOCK_USER;else{m=s_(e.mockUserToken,(t=n._app)===null||t===void 0?void 0:t.options.projectId);let _=e.mockUserToken.sub||e.mockUserToken.user_id;if(!_)throw new Mt(ht.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");u=new Sa(_)}n._authCredentials=new gZ(new bF(m,u))}}var vv=class n{constructor(o,r,e){this.converter=r,this._query=e,this.type="query",this.firestore=o}withConverter(o){return new n(this.firestore,o,this._query)}},La=class n{constructor(o,r,e){this.converter=r,this._key=e,this.type="document",this.firestore=o}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new sp(this.firestore,this.converter,this._key.path.popLast())}withConverter(o){return new n(this.firestore,o,this._key)}toJSON(){return{type:n._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(o,r,e){if(bO(r,n._jsonSchema))return new n(o,e||null,new Zt(ro.fromString(r.referencePath)))}};La._jsonSchemaVersion="firestore/documentReference/1.0",La._jsonSchema={type:ya("string",La._jsonSchemaVersion),referencePath:ya("string")};var sp=class n extends vv{constructor(o,r,e){super(o,r,kO(e)),this._path=e,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let o=this._path.popLast();return o.isEmpty()?null:new La(this.firestore,null,new Zt(o))}withConverter(o){return new n(this.firestore,o,this._path)}};function yCe(n,o,...r){if(n=gr(n),SX("collection","path",o),n instanceof B0){let e=ro.fromString(o,...r);return xhe(e),new sp(n,null,e)}{if(!(n instanceof La||n instanceof sp))throw new Mt(ht.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let e=n._path.child(ro.fromString(o,...r));return xhe(e),new sp(n.firestore,null,e)}}function kCe(n,o){if(n=Jc(n,B0),SX("collectionGroup","collection id",o),o.indexOf("/")>=0)throw new Mt(ht.INVALID_ARGUMENT,`Invalid collection ID '${o}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new vv(n,null,(function(e){return new pm(ro.emptyPath(),e)})(o))}function xCe(n,o,...r){if(n=gr(n),arguments.length===1&&(o=z3.newId()),SX("doc","path",o),n instanceof B0){let e=ro.fromString(o,...r);return khe(e),new La(n,null,new Zt(e))}{if(!(n instanceof La||n instanceof sp))throw new Mt(ht.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let e=n._path.child(ro.fromString(o,...r));return khe(e),new La(n.firestore,n instanceof sp?n.converter:null,new Zt(e))}}var Ofe="AsyncQueue",dL=class{constructor(o=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new gO(this,"async_queue_retry"),this.oc=()=>{let e=CF();e&&Rt(Ofe,"Visibility state changed to "+e.visibilityState),this.F_.y_()},this._c=o;let r=CF();r&&typeof r.addEventListener=="function"&&r.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(o){this.enqueue(o)}enqueueAndForgetEvenWhileRestricted(o){this.ac(),this.uc(o)}enterRestrictedMode(o){if(!this.Xu){this.Xu=!0,this.rc=o||!1;let r=CF();r&&typeof r.removeEventListener=="function"&&r.removeEventListener("visibilitychange",this.oc)}}enqueue(o){if(this.ac(),this.Xu)return new Promise(()=>{});let r=new Zc;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(o().then(r.resolve,r.reject),r.promise)).then(()=>r.promise)}enqueueRetryable(o){this.enqueueAndForget(()=>(this.Zu.push(o),this.cc()))}cc(){return X(this,null,function*(){if(this.Zu.length!==0){try{yield this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(o){if(!yp(o))throw o;Rt(Ofe,"Operation failed with retryable error: "+o)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}})}uc(o){let r=this._c.then(()=>(this.nc=!0,o().catch(e=>{throw this.tc=e,this.nc=!1,ia("INTERNAL UNHANDLED ERROR: ",Afe(e)),e}).then(e=>(this.nc=!1,e))));return this._c=r,r}enqueueAfterDelay(o,r,e){this.ac(),this.sc.indexOf(o)>-1&&(r=0);let t=GJ.createAndSchedule(this,o,r,e,i=>this.lc(i));return this.ec.push(t),t}ac(){this.tc&&an(47125,{hc:Afe(this.tc)})}verifyOperationInProgress(){}Pc(){return X(this,null,function*(){let o;do o=this._c,yield o;while(o!==this._c)})}Tc(o){for(let r of this.ec)if(r.timerId===o)return!0;return!1}Ic(o){return this.Pc().then(()=>{this.ec.sort((r,e)=>r.targetTimeMs-e.targetTimeMs);for(let r of this.ec)if(r.skipDelay(),o!=="all"&&r.timerId===o)break;return this.Pc()})}dc(o){this.sc.push(o)}lc(o){let r=this.ec.indexOf(o);this.ec.splice(r,1)}};function Afe(n){let o=n.message||"";return n.stack&&(o=n.stack.includes(n.message)?n.stack:n.message+`
221
221
  `+n.stack),o}function Mfe(n){return(function(r,e){if(typeof r!="object"||r===null)return!1;let t=r;for(let i of e)if(i in t&&typeof t[i]=="function")return!0;return!1})(n,["next","error","complete"])}var mv=class extends B0{constructor(o,r,e,t){super(o,r,e,t),this.type="firestore",this._queue=new dL,this._persistenceKey=t?.name||"[DEFAULT]"}_terminate(){return X(this,null,function*(){if(this._firestoreClient){let o=this._firestoreClient.terminate();this._queue=new dL(o),this._firestoreClient=void 0,yield o}})}};function wL(n,o,r){r||(r=Q3);let e=Xs(n,"firestore");if(e.isInitialized(r)){let t=e.getImmediate({identifier:r}),i=e.getOptions(r);if(Yd(i,o))return t;throw new Mt(ht.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(o.cacheSizeBytes!==void 0&&o.localCache!==void 0)throw new Mt(ht.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(o.cacheSizeBytes!==void 0&&o.cacheSizeBytes!==-1&&o.cacheSizeBytes<K0e)throw new Mt(ht.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return o.host&&zl(o.host)&&Gv(o.host),e.initialize({options:o,instanceIdentifier:r})}function lS(n,o){let r=typeof n=="object"?n:ql(),e=typeof n=="string"?n:o||Q3,t=Xs(r,"firestore").getImmediate({identifier:e});if(!t._initialized){let i=Eu("firestore");i&&SCe(t,...i)}return t}function cS(n){if(n._terminated)throw new Mt(ht.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||Oze(n),n._firestoreClient}function Oze(n){var o,r,e;let t=n._freezeSettings(),i=(function(l,c,d,m){return new wZ(l,c,d,m.host,m.ssl,m.experimentalForceLongPolling,m.experimentalAutoDetectLongPolling,bCe(m.experimentalLongPollingOptions),m.useFetchStreams,m.isUsingEmulator)})(n._databaseId,((o=n._app)===null||o===void 0?void 0:o.options.appId)||"",n._persistenceKey,t);n._componentsProvider||!((r=t.localCache)===null||r===void 0)&&r._offlineComponentProvider&&(!((e=t.localCache)===null||e===void 0)&&e._onlineComponentProvider)&&(n._componentsProvider={_offline:t.localCache._offlineComponentProvider,_online:t.localCache._onlineComponentProvider}),n._firestoreClient=new nX(n._authCredentials,n._appCheckCredentials,n._queue,i,n._componentsProvider&&(function(l){let c=l?._online.build();return{_offline:l?._offline.build(c),_online:c}})(n._componentsProvider))}var rX=class{constructor(o="count",r){this._internalFieldPath=r,this.type="AggregateField",this.aggregateType=o}},oX=class{constructor(o,r,e){this._userDataWriter=r,this._data=e,this.type="AggregateQuerySnapshot",this.query=o}data(){return this._userDataWriter.convertObjectMap(this._data)}};var Dg=class n{constructor(o){this._byteString=o}static fromBase64String(o){try{return new n(ka.fromBase64String(o))}catch(r){throw new Mt(ht.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+r)}}static fromUint8Array(o){return new n(ka.fromUint8Array(o))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(o){return this._byteString.isEqual(o._byteString)}toJSON(){return{type:n._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(o){if(bO(o,n._jsonSchema))return n.fromBase64String(o.bytes)}};Dg._jsonSchemaVersion="firestore/bytes/1.0",Dg._jsonSchema={type:ya("string",Dg._jsonSchemaVersion),bytes:ya("string")};var eS=class{constructor(...o){for(let r=0;r<o.length;++r)if(o[r].length===0)throw new Mt(ht.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Na(o)}isEqual(o){return this._internalPath.isEqual(o._internalPath)}};var hO=class{constructor(o){this._methodName=o}};var dp=class n{constructor(o,r){if(!isFinite(o)||o<-90||o>90)throw new Mt(ht.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+o);if(!isFinite(r)||r<-180||r>180)throw new Mt(ht.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+r);this._lat=o,this._long=r}get latitude(){return this._lat}get longitude(){return this._long}isEqual(o){return this._lat===o._lat&&this._long===o._long}_compareTo(o){return qn(this._lat,o._lat)||qn(this._long,o._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:n._jsonSchemaVersion}}static fromJSON(o){if(bO(o,n._jsonSchema))return new n(o.latitude,o.longitude)}};dp._jsonSchemaVersion="firestore/geoPoint/1.0",dp._jsonSchema={type:ya("string",dp._jsonSchemaVersion),latitude:ya("number"),longitude:ya("number")};var vp=class n{constructor(o){this._values=(o||[]).map(r=>r)}toArray(){return this._values.map(o=>o)}isEqual(o){return(function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0})(this._values,o._values)}toJSON(){return{type:n._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(o){if(bO(o,n._jsonSchema)){if(Array.isArray(o.vectorValues)&&o.vectorValues.every(r=>typeof r=="number"))return new n(o.vectorValues);throw new Mt(ht.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};vp._jsonSchemaVersion="firestore/vectorValue/1.0",vp._jsonSchema={type:ya("string",vp._jsonSchemaVersion),vectorValues:ya("object")};var Aze=/^__.*__$/,iX=class{constructor(o,r,e){this.data=o,this.fieldMask=r,this.fieldTransforms=e}toMutation(o,r){return this.fieldMask!==null?new dv(o,this.data,this.fieldMask,r,this.fieldTransforms):new Cp(o,this.data,r,this.fieldTransforms)}},vL=class{constructor(o,r,e){this.data=o,this.fieldMask=r,this.fieldTransforms=e}toMutation(o,r){return new dv(o,this.data,this.fieldMask,r,this.fieldTransforms)}};function ICe(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw an(40011,{Ec:n})}}var aX=class n{constructor(o,r,e,t,i,a){this.settings=o,this.databaseId=r,this.serializer=e,this.ignoreUndefinedProperties=t,i===void 0&&this.Ac(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(o){return new n(Object.assign(Object.assign({},this.settings),o),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(o){var r;let e=(r=this.path)===null||r===void 0?void 0:r.child(o),t=this.Rc({path:e,mc:!1});return t.fc(o),t}gc(o){var r;let e=(r=this.path)===null||r===void 0?void 0:r.child(o),t=this.Rc({path:e,mc:!1});return t.Ac(),t}yc(o){return this.Rc({path:void 0,mc:!0})}wc(o){return gL(o,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(o){return this.fieldMask.find(r=>o.isPrefixOf(r))!==void 0||this.fieldTransforms.find(r=>o.isPrefixOf(r.field))!==void 0}Ac(){if(this.path)for(let o=0;o<this.path.length;o++)this.fc(this.path.get(o))}fc(o){if(o.length===0)throw this.wc("Document fields must not be empty");if(ICe(this.Ec)&&Aze.test(o))throw this.wc('Document fields cannot begin and end with "__"')}},lX=class{constructor(o,r,e){this.databaseId=o,this.ignoreUndefinedProperties=r,this.serializer=e||kL(o)}Dc(o,r,e,t=!1){return new aX({Ec:o,methodName:r,bc:e,path:Na.emptyPath(),mc:!1,Sc:t},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function TL(n){let o=n._freezeSettings(),r=kL(n._databaseId);return new lX(n._databaseId,!!o.ignoreUndefinedProperties,r)}function ECe(n,o,r,e,t,i={}){let a=n.Dc(i.merge||i.mergeFields?2:0,o,r,t);QX("Data must be an object, but it was:",a,e);let l=TCe(e,a),c,d;if(i.merge)c=new Ds(a.fieldMask),d=a.fieldTransforms;else if(i.mergeFields){let m=[];for(let u of i.mergeFields){let _=cX(o,u,r);if(!a.contains(_))throw new Mt(ht.INVALID_ARGUMENT,`Field '${_}' is specified in your field mask but missing from your input data.`);OCe(m,_)||m.push(_)}c=new Ds(m),d=a.fieldTransforms.filter(u=>c.covers(u.field))}else c=null,d=a.fieldTransforms;return new iX(new tc(l),c,d)}var mL=class n extends hO{_toFieldTransform(o){if(o.Ec!==2)throw o.Ec===1?o.wc(`${this._methodName}() can only appear at the top level of your update data`):o.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return o.fieldMask.push(o.path),null}isEqual(o){return o instanceof n}};function Mze(n,o,r,e){let t=n.Dc(1,o,r);QX("Data must be an object, but it was:",t,e);let i=[],a=tc.empty();kp(e,(c,d)=>{let m=eQ(o,c,r);d=gr(d);let u=t.gc(m);if(d instanceof mL)i.push(m);else{let _=EO(d,u);_!=null&&(i.push(m),a.set(m,_))}});let l=new Ds(i);return new vL(a,l,t.fieldTransforms)}function Pze(n,o,r,e,t,i){let a=n.Dc(1,o,r),l=[cX(o,e,r)],c=[t];if(i.length%2!=0)throw new Mt(ht.INVALID_ARGUMENT,`Function ${o}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let _=0;_<i.length;_+=2)l.push(cX(o,i[_])),c.push(i[_+1]);let d=[],m=tc.empty();for(let _=l.length-1;_>=0;--_)if(!OCe(d,l[_])){let I=l[_],A=c[_];A=gr(A);let M=a.gc(I);if(A instanceof mL)d.push(I);else{let B=EO(A,M);B!=null&&(d.push(I),m.set(I,B))}}let u=new Ds(d);return new vL(m,u,a.fieldTransforms)}function wCe(n,o,r,e=!1){return EO(r,n.Dc(e?4:3,o))}function EO(n,o){if(DCe(n=gr(n)))return QX("Unsupported field value:",o,n),TCe(n,o);if(n instanceof hO)return(function(e,t){if(!ICe(t.Ec))throw t.wc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.wc(`${e._methodName}() is not currently supported inside arrays`);let i=e._toFieldTransform(t);i&&t.fieldTransforms.push(i)})(n,o),null;if(n===void 0&&o.ignoreUndefinedProperties)return null;if(o.path&&o.fieldMask.push(o.path),n instanceof Array){if(o.settings.mc&&o.Ec!==4)throw o.wc("Nested arrays are not supported");return(function(e,t){let i=[],a=0;for(let l of e){let c=EO(l,t.yc(a));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),a++}return{arrayValue:{values:i}}})(n,o)}return(function(e,t){if((e=gr(e))===null)return{nullValue:"NULL_VALUE"};if(typeof e=="number")return CHe(t.serializer,e);if(typeof e=="boolean")return{booleanValue:e};if(typeof e=="string")return{stringValue:e};if(e instanceof Date){let i=_i.fromDate(e);return{timestampValue:q1(t.serializer,i)}}if(e instanceof _i){let i=new _i(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:q1(t.serializer,i)}}if(e instanceof dp)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Dg)return{bytesValue:A0e(t.serializer,e._byteString)};if(e instanceof La){let i=t.databaseId,a=e.firestore._databaseId;if(!a.isEqual(i))throw t.wc(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:RX(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof vp)return(function(a,l){return{mapValue:{fields:{[TX]:{stringValue:DX},[$1]:{arrayValue:{values:a.toArray().map(d=>{if(typeof d!="number")throw l.wc("VectorValues must only contain numeric values.");return PX(l.serializer,d)})}}}}}})(e,t);throw t.wc(`Unsupported field value: ${pL(e)}`)})(n,o)}function TCe(n,o){let r={};return e0e(n)?o.path&&o.path.length>0&&o.fieldMask.push(o.path):kp(n,(e,t)=>{let i=EO(t,o.Vc(e));i!=null&&(r[e]=i)}),{mapValue:{fields:r}}}function DCe(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof _i||n instanceof dp||n instanceof Dg||n instanceof La||n instanceof hO||n instanceof vp)}function QX(n,o,r){if(!DCe(r)||!Ufe(r)){let e=pL(r);throw e==="an object"?o.wc(n+" a custom object"):o.wc(n+" "+e)}}function cX(n,o,r){if((o=gr(o))instanceof eS)return o._internalPath;if(typeof o=="string")return eQ(n,o);throw gL("Field path arguments must be of type string or ",n,!1,void 0,r)}var Rze=new RegExp("[~\\*/\\[\\]]");function eQ(n,o,r){if(o.search(Rze)>=0)throw gL(`Invalid field path (${o}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,r);try{return new eS(...o.split("."))._internalPath}catch{throw gL(`Invalid field path (${o}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,r)}}function gL(n,o,r,e,t){let i=e&&!e.isEmpty(),a=t!==void 0,l=`Function ${o}() called with invalid data`;r&&(l+=" (via `toFirestore()`)"),l+=". ";let c="";return(i||a)&&(c+=" (found",i&&(c+=` in field ${e}`),a&&(c+=` in document ${t}`),c+=")"),new Mt(ht.INVALID_ARGUMENT,l+n+c)}function OCe(n,o){return n.some(r=>r.isEqual(o))}var j0=class{constructor(o,r,e,t,i){this._firestore=o,this._userDataWriter=r,this._key=e,this._document=t,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new La(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let o=new sX(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(o)}return this._userDataWriter.convertValue(this._document.data.value)}}get(o){if(this._document){let r=this._document.data.field(DL("DocumentSnapshot.get",o));if(r!==null)return this._userDataWriter.convertValue(r)}}},sX=class extends j0{data(){return super.data()}};function DL(n,o){return typeof o=="string"?eQ(n,o):o instanceof eS?o._internalPath:o._delegate._internalPath}function ACe(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new Mt(ht.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var fO=class{},tS=class extends fO{};function MCe(n,o,...r){let e=[];o instanceof fO&&e.push(o),e=e.concat(r),(function(i){let a=i.filter(c=>c instanceof nS).length,l=i.filter(c=>c instanceof CO).length;if(a>1||a>0&&l>0)throw new Mt(ht.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")})(e);for(let t of e)n=t._apply(n);return n}var CO=class n extends tS{constructor(o,r,e){super(),this._field=o,this._op=r,this._value=e,this.type="where"}static _create(o,r,e){return new n(o,r,e)}_apply(o){let r=this._parse(o);return VCe(o._query,r),new vv(o.firestore,o.converter,BZ(o._query,r))}_parse(o){let r=TL(o.firestore);return(function(i,a,l,c,d,m,u){let _;if(d.isKeyField()){if(m==="array-contains"||m==="array-contains-any")throw new Mt(ht.INVALID_ARGUMENT,`Invalid Query. You can't perform '${m}' queries on documentId().`);if(m==="in"||m==="not-in"){Rfe(u,m);let A=[];for(let M of u)A.push(Pfe(c,i,M));_={arrayValue:{values:A}}}else _=Pfe(c,i,u)}else m!=="in"&&m!=="not-in"&&m!=="array-contains-any"||Rfe(u,m),_=wCe(l,a,u,m==="in"||m==="not-in");return Vr.create(d,m,_)})(o._query,"where",r,o.firestore._databaseId,this._field,this._op,this._value)}};function PCe(n,o,r){let e=o,t=DL("where",n);return CO._create(t,e,r)}var nS=class n extends fO{constructor(o,r){super(),this.type=o,this._queryConstraints=r}static _create(o,r){return new n(o,r)}_parse(o){let r=this._queryConstraints.map(e=>e._parse(o)).filter(e=>e.getFilters().length>0);return r.length===1?r[0]:Po.create(r,this._getOperator())}_apply(o){let r=this._parse(o);return r.getFilters().length===0?o:((function(t,i){let a=t,l=i.getFlattenedFilters();for(let c of l)VCe(a,c),a=BZ(a,c)})(o._query,r),new vv(o.firestore,o.converter,BZ(o._query,r)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function RCe(...n){return n.forEach(o=>BCe("or",o)),nS._create("or",n)}function NCe(...n){return n.forEach(o=>BCe("and",o)),nS._create("and",n)}var dX=class n extends tS{constructor(o,r){super(),this._field=o,this._direction=r,this.type="orderBy"}static _create(o,r){return new n(o,r)}_apply(o){let r=(function(t,i,a){if(t.startAt!==null)throw new Mt(ht.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(t.endAt!==null)throw new Mt(ht.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new M0(i,a)})(o._query,this._field,this._direction);return new vv(o.firestore,o.converter,(function(t,i){let a=t.explicitOrderBy.concat([i]);return new pm(t.path,t.collectionGroup,a,t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)})(o._query,r))}};function FCe(n,o="asc"){let r=o,e=DL("orderBy",n);return dX._create(e,r)}var vX=class n extends tS{constructor(o,r,e){super(),this.type=o,this._limit=r,this._limitType=e}static _create(o,r,e){return new n(o,r,e)}_apply(o){return new vv(o.firestore,o.converter,PF(o._query,this._limit,this._limitType))}};function LCe(n){return RGe("limit",n),vX._create("limit",n,"F")}var mX=class n extends tS{constructor(o,r,e){super(),this.type=o,this._docOrFields=r,this._inclusive=e}static _create(o,r,e){return new n(o,r,e)}_apply(o){let r=Nze(o,this.type,this._docOrFields,this._inclusive);return new vv(o.firestore,o.converter,(function(t,i){return new pm(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,i,t.endAt)})(o._query,r))}};function UCe(...n){return mX._create("startAfter",n,!1)}function Nze(n,o,r,e){if(r[0]=gr(r[0]),r[0]instanceof j0)return(function(i,a,l,c,d){if(!c)throw new Mt(ht.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${l}().`);let m=[];for(let u of O1(i))if(u.field.isKeyField())m.push(A0(a,c.key));else{let _=c.data.field(u.field);if(bL(_))throw new Mt(ht.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+u.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(_===null){let I=u.field.canonicalString();throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${I}' (used as the orderBy) does not exist.`)}m.push(_)}return new um(m,d)})(n._query,n.firestore._databaseId,o,r[0]._document,e);{let t=TL(n.firestore);return(function(a,l,c,d,m,u){let _=a.explicitOrderBy;if(m.length>_.length)throw new Mt(ht.INVALID_ARGUMENT,`Too many arguments provided to ${d}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let I=[];for(let A=0;A<m.length;A++){let M=m[A];if(_[A].field.isKeyField()){if(typeof M!="string")throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${d}(), but got a ${typeof M}`);if(!AX(a)&&M.indexOf("/")!==-1)throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${d}() must be a plain document ID, but '${M}' contains a slash.`);let B=a.path.child(ro.fromString(M));if(!Zt.isDocumentKey(B))throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${d}() must result in a valid document path, but '${B}' is not because it contains an odd number of segments.`);let q=new Zt(B);I.push(A0(l,q))}else{let B=wCe(c,d,M);I.push(B)}}return new um(I,u)})(n._query,n.firestore._databaseId,t,o,r,e)}}function Pfe(n,o,r){if(typeof(r=gr(r))=="string"){if(r==="")throw new Mt(ht.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!AX(o)&&r.indexOf("/")!==-1)throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);let e=o.path.child(ro.fromString(r));if(!Zt.isDocumentKey(e))throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${e}' is not because it has an odd number of segments (${e.length}).`);return A0(n,new Zt(e))}if(r instanceof La)return A0(n,r._key);throw new Mt(ht.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${pL(r)}.`)}function Rfe(n,o){if(!Array.isArray(n)||n.length===0)throw new Mt(ht.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${o.toString()}' filters.`)}function VCe(n,o){let r=(function(t,i){for(let a of t)for(let l of a.getFlattenedFilters())if(i.indexOf(l.op)>=0)return l.op;return null})(n.filters,(function(t){switch(t){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}})(o.op));if(r!==null)throw r===o.op?new Mt(ht.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${o.op.toString()}' filter.`):new Mt(ht.INVALID_ARGUMENT,`Invalid query. You cannot use '${o.op.toString()}' filters with '${r.toString()}' filters.`)}function BCe(n,o){if(!(o instanceof CO||o instanceof nS))throw new Mt(ht.INVALID_ARGUMENT,`Function ${n}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var uL=class{convertValue(o,r="none"){switch(up(o)){case 0:return null;case 1:return o.booleanValue;case 2:return bi(o.integerValue||o.doubleValue);case 3:return this.convertTimestamp(o.timestampValue);case 4:return this.convertServerTimestamp(o,r);case 5:return o.stringValue;case 6:return this.convertBytes(Mg(o.bytesValue));case 7:return this.convertReference(o.referenceValue);case 8:return this.convertGeoPoint(o.geoPointValue);case 9:return this.convertArray(o.arrayValue,r);case 11:return this.convertObject(o.mapValue,r);case 10:return this.convertVectorValue(o.mapValue);default:throw an(62114,{value:o})}}convertObject(o,r){return this.convertObjectMap(o.fields,r)}convertObjectMap(o,r="none"){let e={};return kp(o,(t,i)=>{e[t]=this.convertValue(i,r)}),e}convertVectorValue(o){var r,e,t;let i=(t=(e=(r=o.fields)===null||r===void 0?void 0:r[$1].arrayValue)===null||e===void 0?void 0:e.values)===null||t===void 0?void 0:t.map(a=>bi(a.doubleValue));return new vp(i)}convertGeoPoint(o){return new dp(bi(o.latitude),bi(o.longitude))}convertArray(o,r){return(o.values||[]).map(e=>this.convertValue(e,r))}convertServerTimestamp(o,r){switch(r){case"previous":let e=_L(o);return e==null?null:this.convertValue(e,r);case"estimate":return this.convertTimestamp(X3(o));default:return null}}convertTimestamp(o){let r=Ag(o);return new _i(r.seconds,r.nanos)}convertDocumentKey(o,r){let e=ro.fromString(o);dn(B0e(e),9688,{name:o});let t=new j1(e.get(1),e.get(3)),i=new Zt(e.popFirst(5));return t.isEqual(r)||ia(`Document ${i} contains a document reference within a different database (${t.projectId}/${t.database}) which is not supported. It will be treated as a reference in the current database (${r.projectId}/${r.database}) instead.`),i}};function jCe(n,o,r){let e;return e=n?r&&(r.merge||r.mergeFields)?n.toFirestore(o,r):n.toFirestore(o):o,e}var gX=class extends uL{constructor(o){super(),this.firestore=o}convertBytes(o){return new Dg(o)}convertReference(o){let r=this.convertDocumentKey(o,this.firestore._databaseId);return new La(this.firestore,null,r)}};function Fze(){return new rX("count")}var cp=class{constructor(o,r){this.hasPendingWrites=o,this.fromCache=r}isEqual(o){return this.hasPendingWrites===o.hasPendingWrites&&this.fromCache===o.fromCache}},mp=class n extends j0{constructor(o,r,e,t,i,a){super(o,r,e,t,a),this._firestore=o,this._firestoreImpl=o,this.metadata=i}exists(){return super.exists()}data(o={}){if(this._document){if(this._converter){let r=new M1(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(r,o)}return this._userDataWriter.convertValue(this._document.data.value,o.serverTimestamps)}}get(o,r={}){if(this._document){let e=this._document.data.field(DL("DocumentSnapshot.get",o));if(e!==null)return this._userDataWriter.convertValue(e,r.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new Mt(ht.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let o=this._document,r={};return r.type=n._jsonSchemaVersion,r.bundle="",r.bundleSource="DocumentSnapshot",r.bundleName=this._key.toString(),!o||!o.isValidDocument()||!o.isFoundDocument()?r:(this._userDataWriter.convertObjectMap(o.data.value.mapValue.fields,"previous"),r.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),r)}};mp._jsonSchemaVersion="firestore/documentSnapshot/1.0",mp._jsonSchema={type:ya("string",mp._jsonSchemaVersion),bundleSource:ya("string","DocumentSnapshot"),bundleName:ya("string"),bundle:ya("string")};var M1=class extends mp{data(o={}){return super.data(o)}},O0=class n{constructor(o,r,e,t){this._firestore=o,this._userDataWriter=r,this._snapshot=t,this.metadata=new cp(t.hasPendingWrites,t.fromCache),this.query=e}get docs(){let o=[];return this.forEach(r=>o.push(r)),o}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(o,r){this._snapshot.docs.forEach(e=>{o.call(r,new M1(this._firestore,this._userDataWriter,e.key,e,new cp(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(o={}){let r=!!o.includeMetadataChanges;if(r&&this._snapshot.excludesMetadataChanges)throw new Mt(ht.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===r||(this._cachedChanges=(function(t,i){if(t._snapshot.oldDocs.isEmpty()){let a=0;return t._snapshot.docChanges.map(l=>{let c=new M1(t._firestore,t._userDataWriter,l.doc.key,l.doc,new cp(t._snapshot.mutatedKeys.has(l.doc.key),t._snapshot.fromCache),t.query.converter);return l.doc,{type:"added",doc:c,oldIndex:-1,newIndex:a++}})}{let a=t._snapshot.oldDocs;return t._snapshot.docChanges.filter(l=>i||l.type!==3).map(l=>{let c=new M1(t._firestore,t._userDataWriter,l.doc.key,l.doc,new cp(t._snapshot.mutatedKeys.has(l.doc.key),t._snapshot.fromCache),t.query.converter),d=-1,m=-1;return l.type!==0&&(d=a.indexOf(l.doc.key),a=a.delete(l.doc.key)),l.type!==1&&(a=a.add(l.doc),m=a.indexOf(l.doc.key)),{type:Lze(l.type),doc:c,oldIndex:d,newIndex:m}})}})(this,r),this._cachedChangesIncludeMetadataChanges=r),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new Mt(ht.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let o={};o.type=n._jsonSchemaVersion,o.bundleSource="QuerySnapshot",o.bundleName=z3.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let r=[],e=[],t=[];return this.docs.forEach(i=>{i._document!==null&&(r.push(i._document),e.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),t.push(i.ref.path))}),o.bundle=(this._firestore,this.query._query,o.bundleName,"NOT SUPPORTED"),o}};function Lze(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return an(61501,{type:n})}}function $Ce(n){n=Jc(n,La);let o=Jc(n.firestore,mv);return wze(cS(o),n._key).then(r=>YCe(o,n,r))}O0._jsonSchemaVersion="firestore/querySnapshot/1.0",O0._jsonSchema={type:ya("string",O0._jsonSchemaVersion),bundleSource:ya("string","QuerySnapshot"),bundleName:ya("string"),bundle:ya("string")};var $0=class extends uL{constructor(o){super(),this.firestore=o}convertBytes(o){return new Dg(o)}convertReference(o){let r=this.convertDocumentKey(o,this.firestore._databaseId);return new La(this.firestore,null,r)}};function GCe(n){n=Jc(n,vv);let o=Jc(n.firestore,mv),r=cS(o),e=new $0(o);return ACe(n._query),Tze(r,n._query).then(t=>new O0(o,e,n,t))}function HCe(n,o,r){n=Jc(n,La);let e=Jc(n.firestore,mv),t=jCe(n.converter,o,r);return qCe(e,[ECe(TL(e),"setDoc",n._key,t,n.converter!==null,r).toMutation(n._key,wl.none())])}function zCe(n){return qCe(Jc(n.firestore,mv),[new F0(n._key,wl.none())])}function WCe(n,...o){var r,e,t;n=gr(n);let i={includeMetadataChanges:!1,source:"default"},a=0;typeof o[a]!="object"||Mfe(o[a])||(i=o[a++]);let l={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(Mfe(o[a])){let u=o[a];o[a]=(r=u.next)===null||r===void 0?void 0:r.bind(u),o[a+1]=(e=u.error)===null||e===void 0?void 0:e.bind(u),o[a+2]=(t=u.complete)===null||t===void 0?void 0:t.bind(u)}let c,d,m;if(n instanceof La)d=Jc(n.firestore,mv),m=kO(n._key.path),c={next:u=>{o[a]&&o[a](YCe(d,n,u))},error:o[a+1],complete:o[a+2]};else{let u=Jc(n,vv);d=Jc(u.firestore,mv),m=u._query;let _=new $0(d);c={next:I=>{o[a]&&o[a](new O0(d,_,u,I))},error:o[a+1],complete:o[a+2]},ACe(n._query)}return(function(_,I,A,M){let B=new pO(M),q=new uO(I,B,A);return _.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){return $X(yield cL(_),q)})),()=>{B.Ou(),_.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){return GX(yield cL(_),q)}))}})(cS(d),m,l,c)}function qCe(n,o){return(function(e,t){let i=new Zc;return e.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){return vze(yield Eze(e),t,i)})),i.promise})(cS(n),o)}function YCe(n,o,r){let e=r.docs.get(o._key),t=new $0(n);return new mp(n,t,o._key,e,new cp(r.hasPendingWrites,r.fromCache),o.converter)}function KCe(n){return ZCe(n,{count:Fze()})}function ZCe(n,o){let r=Jc(n.firestore,mv),e=cS(r),t=lHe(o,(i,a)=>new HZ(a,i.aggregateType,i._internalFieldPath));return Dze(e,n._query,t).then(i=>(function(l,c,d){let m=new $0(l);return new oX(c,m,d)})(r,n,i))}var uX=class{constructor(o){let r;this.kind="persistent",o?.tabManager?(o.tabManager._initialize(o),r=o.tabManager):(r=Uze(void 0),r._initialize(o)),this._onlineComponentProvider=r._onlineComponentProvider,this._offlineComponentProvider=r._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function tQ(n){return new uX(n)}var pX=class{constructor(o){this.forceOwnership=o,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(o){this._onlineComponentProvider=JX.provider,this._offlineComponentProvider={build:r=>new lL(r,o?.cacheSizeBytes,this.forceOwnership)}}},hX=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(o){this._onlineComponentProvider=JX.provider,this._offlineComponentProvider={build:r=>new QJ(r,o?.cacheSizeBytes)}}};function Uze(n){return new pX(n?.forceOwnership)}function nQ(){return new hX}var Vze={maxAttempts:5};function F3(n,o){if((n=gr(n)).firestore!==o)throw new Mt(ht.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}var fX=class{constructor(o,r){this._firestore=o,this._transaction=r,this._dataReader=TL(o)}get(o){let r=F3(o,this._firestore),e=new gX(this._firestore);return this._transaction.lookup([r._key]).then(t=>{if(!t||t.length!==1)return an(24041);let i=t[0];if(i.isFoundDocument())return new j0(this._firestore,e,i.key,i,r.converter);if(i.isNoDocument())return new j0(this._firestore,e,r._key,null,r.converter);throw an(18433,{doc:i})})}set(o,r,e){let t=F3(o,this._firestore),i=jCe(t.converter,r,e),a=ECe(this._dataReader,"Transaction.set",t._key,i,t.converter!==null,e);return this._transaction.set(t._key,a),this}update(o,r,e,...t){let i=F3(o,this._firestore),a;return a=typeof(r=gr(r))=="string"||r instanceof eS?Pze(this._dataReader,"Transaction.update",i._key,r,e,t):Mze(this._dataReader,"Transaction.update",i._key,r),this._transaction.update(i._key,a),this}delete(o){let r=F3(o,this._firestore);return this._transaction.delete(r._key),this}};var CX=class extends fX{constructor(o,r){super(o,r),this._firestore=o}get(o){let r=F3(o,this._firestore),e=new $0(this._firestore);return super.get(o).then(t=>new mp(this._firestore,e,r._key,t._document,new cp(!1,!1),r.converter))}};function JCe(n,o,r){n=Jc(n,mv);let e=Object.assign(Object.assign({},Vze),r);return(function(i){if(i.maxAttempts<1)throw new Mt(ht.INVALID_ARGUMENT,"Max attempts must be at least 1")})(e),(function(i,a,l){let c=new Zc;return i.asyncQueue.enqueueAndForget(()=>X(null,null,function*(){let d=yield CCe(i);new tX(i.asyncQueue,d,l,a,c).zu()})),c.promise})(cS(n),t=>o(new CX(n,t)),e)}(function(o,r=!0){(function(t){rS=t})(Wv),Cl(new ta("firestore",(e,{instanceIdentifier:t,options:i})=>{let a=e.getProvider("app").getImmediate(),l=new mv(new uZ(e.getProvider("auth-internal")),new fZ(a,e.getProvider("app-check-internal")),(function(d,m){if(!Object.prototype.hasOwnProperty.apply(d.options,["projectId"]))throw new Mt(ht.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new j1(d.options.projectId,m)})(a,t),a);return i=Object.assign({useFetchStreams:r},i),l._setSettings(i),l},"PUBLIC").setMultipleInstances(!0)),Lr(bhe,_he,o),Lr(bhe,_he,"esm2017")})();var _r=fn(NCe,!0,2);var wO=fn(yCe,!0,2),rQ=fn(kCe,!0,2);var OL=fn(zCe,!0,2);var sS=fn(xCe,!0,2);var XCe=fn(KCe,!0),QCe=fn($Ce,!0);var ebe=fn(GCe,!0);var hm=fn(LCe,!0,2);var oQ=fn(WCe,!0);var H0=fn(RCe,!0,2),vo=fn(FCe,!0,2),iQ=fn(MCe,!0,2);var aQ=fn(JCe,!0),lQ=fn(HCe,!0,2);var tbe=fn(UCe,!0,2);var ft=fn(PCe,!0,2);var Ft=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.analyticsService=t,this.config$=new Se(null),this.disableLogsConfig$=new Se({warnings:!0,suppressAll:!1}),this.apiKey$=new Se(""),this.baseFeatureAllowList=[],this.sf$=new Se(!1),this.sdkType$=new Se("core"),this.logsEnabled$=new Se(!0),this.safeEval$=new Se(!1),this.firestorePersistentCacheEnabled$=new Se(!1),this.encryptionProvider$=new Se(null);try{this.analyticsService.setConfigService(this),this.sdkType$.subscribe(i=>{this.analyticsService.updateDefaultProperties({sdkType:i})},i=>{this.loggingService.catch("Error in ConfigService sdkType$: ",i)}),this.logsEnabled$.subscribe(i=>{i?this.loggingService.enableLogs():this.loggingService.disableLogs(),at.logsEnabled=i},i=>{this.loggingService.catch("Error in ConfigService logsEnabled$: ",i)})}catch(i){this.loggingService.catch("Error in ConfigService constructor: ",i)}}initConfig(e){try{e.featureAllowList?.length||(e.featureAllowList=Object.values($e)),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(_t(Kt))}catch(e){return this.loggingService.catch("Error in ConfigService getSF$: ",e),ce(!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),ce("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),ce(!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),ce(!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),ce(null)}}};o.\u0275fac=function(t){return new(t||o)(K(k),K(ct))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var nbe=(()=>{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)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var fm=(()=>{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)(K(nbe),K(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 it),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CoreActionsService triggerAction: ",i)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new it);let t=this.actionSubjects.get(e);return t?t.asObservable():ce(null)}catch(t){return this.loggingService.catch("Error in CoreActionsService onAction: ",t),ce(null)}}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var{entries:vbe,setPrototypeOf:rbe,isFrozen:jze,getPrototypeOf:$ze,getOwnPropertyDescriptor:Gze}=Object,{freeze:xc,seal:dd,create:uQ}=Object,{apply:pQ,construct:hQ}=typeof Reflect<"u"&&Reflect;xc||(xc=function(o){return o});dd||(dd=function(o){return o});pQ||(pQ=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)});hQ||(hQ=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=Ic(Array.prototype.forEach),Hze=Ic(Array.prototype.lastIndexOf),obe=Ic(Array.prototype.pop),DO=Ic(Array.prototype.push),zze=Ic(Array.prototype.splice),PL=Ic(String.prototype.toLowerCase),cQ=Ic(String.prototype.toString),sQ=Ic(String.prototype.match),OO=Ic(String.prototype.replace),Wze=Ic(String.prototype.indexOf),qze=Ic(String.prototype.trim),gv=Ic(Object.prototype.hasOwnProperty),kc=Ic(RegExp.prototype.test),AO=Yze(TypeError);function Ic(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 pQ(n,o,e)}}function Yze(n){return function(){for(var o=arguments.length,r=new Array(o),e=0;e<o;e++)r[e]=arguments[e];return hQ(n,r)}}function Nr(n,o){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:PL;rbe&&rbe(n,null);let e=o.length;for(;e--;){let t=o[e];if(typeof t=="string"){let i=r(t);i!==t&&(jze(o)||(o[e]=i),t=i)}n[t]=!0}return n}function Kze(n){for(let o=0;o<n.length;o++)gv(n,o)||(n[o]=null);return n}function Pg(n){let o=uQ(null);for(let[r,e]of vbe(n))gv(n,r)&&(Array.isArray(e)?o[r]=Kze(e):e&&typeof e=="object"&&e.constructor===Object?o[r]=Pg(e):o[r]=e);return o}function MO(n,o){for(;n!==null;){let e=Gze(n,o);if(e){if(e.get)return Ic(e.get);if(typeof e.value=="function")return Ic(e.value)}n=$ze(n)}function r(){return null}return r}var ibe=xc(["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"]),dQ=xc(["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"]),vQ=xc(["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"]),Zze=xc(["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"]),mQ=xc(["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"]),Jze=xc(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),abe=xc(["#text"]),lbe=xc(["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"]),gQ=xc(["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"]),cbe=xc(["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=xc(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Xze=dd(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Qze=dd(/<%[\w\W]*|[\w\W]*%>/gm),eWe=dd(/\$\{[\w\W]*/gm),tWe=dd(/^data-[\-\w.\u00B7-\uFFFF]+$/),nWe=dd(/^aria-[\-\w]+$/),mbe=dd(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),rWe=dd(/^(?:\w+script|data):/i),oWe=dd(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gbe=dd(/^html$/i),iWe=dd(/^[a-z][.\w]*(-[.\w]+)+$/i),sbe=Object.freeze({__proto__:null,ARIA_ATTR:nWe,ATTR_WHITESPACE:oWe,CUSTOM_ELEMENT:iWe,DATA_ATTR:tWe,DOCTYPE_NAME:gbe,ERB_EXPR:Qze,IS_ALLOWED_URI:mbe,IS_SCRIPT_OR_DATA:rWe,MUSTACHE_EXPR:Xze,TMPLIT_EXPR:eWe}),PO={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},aWe=function(){return typeof window>"u"?null:window},lWe=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}},dbe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ube(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:aWe(),o=kn=>ube(kn);if(o.version="3.3.0",o.removed=[],!n||!n.document||n.document.nodeType!==PO.document||!n.Element)return o.isSupported=!1,o;let{document:r}=n,e=r,t=e.currentScript,{DocumentFragment:i,HTMLTemplateElement:a,Node:l,Element:c,NodeFilter:d,NamedNodeMap:m=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:u,DOMParser:_,trustedTypes:I}=n,A=c.prototype,M=MO(A,"cloneNode"),B=MO(A,"remove"),q=MO(A,"nextSibling"),ae=MO(A,"childNodes"),be=MO(A,"parentNode");if(typeof a=="function"){let kn=r.createElement("template");kn.content&&kn.content.ownerDocument&&(r=kn.content.ownerDocument)}let re,_e="",{implementation:Ie,createNodeIterator:Ce,createDocumentFragment:Te,getElementsByTagName:Oe}=r,{importNode:Me}=e,je=dbe();o.isSupported=typeof vbe=="function"&&typeof be=="function"&&Ie&&Ie.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:We,ERB_EXPR:ze,TMPLIT_EXPR:jr,DATA_ATTR:nt,ARIA_ATTR:Et,IS_SCRIPT_OR_DATA:Je,ATTR_WHITESPACE:$t,CUSTOM_ELEMENT:Qt}=sbe,{IS_ALLOWED_URI:ar}=sbe,$r=null,bo=Nr({},[...ibe,...dQ,...vQ,...mQ,...abe]),Zn=null,_o=Nr({},[...lbe,...gQ,...cbe,...ML]),Jr=Object.seal(uQ(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,bn=null,hi=Object.seal(uQ(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Ro=!0,la=!0,Cd=!1,HC=!0,Sv=!1,Wg=!0,bd=!1,zC=!1,WC=!1,qg=!1,xh=!1,Ih=!1,qC=!0,rw=!1,aB="user-content-",Eh=!0,Nm=!1,yv={},ki=null,Va=Nr({},["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"]),wh=null,ow=Nr({},["audio","video","img","source","image","track"]),YC=null,B5=Nr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),kv="http://www.w3.org/1998/Math/MathML",Th="http://www.w3.org/2000/svg",Us="http://www.w3.org/1999/xhtml",xv=Us,iw=!1,aw=null,lw=Nr({},[kv,Th,Us],cQ),Dh=Nr({},["mi","mo","mn","ms","mtext"]),Oh=Nr({},["annotation-xml"]),Ah=Nr({},["title","style","font","a","script"]),Fm=null,cw=["application/xhtml+xml","text/html"],Lm="text/html",qi=null,_d=null,j5=r.createElement("form"),Yg=function(Ke){return Ke instanceof RegExp||Ke instanceof Function},KC=function(){let Ke=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(_d&&_d===Ke)){if((!Ke||typeof Ke!="object")&&(Ke={}),Ke=Pg(Ke),Fm=cw.indexOf(Ke.PARSER_MEDIA_TYPE)===-1?Lm:Ke.PARSER_MEDIA_TYPE,qi=Fm==="application/xhtml+xml"?cQ:PL,$r=gv(Ke,"ALLOWED_TAGS")?Nr({},Ke.ALLOWED_TAGS,qi):bo,Zn=gv(Ke,"ALLOWED_ATTR")?Nr({},Ke.ALLOWED_ATTR,qi):_o,aw=gv(Ke,"ALLOWED_NAMESPACES")?Nr({},Ke.ALLOWED_NAMESPACES,cQ):lw,YC=gv(Ke,"ADD_URI_SAFE_ATTR")?Nr(Pg(B5),Ke.ADD_URI_SAFE_ATTR,qi):B5,wh=gv(Ke,"ADD_DATA_URI_TAGS")?Nr(Pg(ow),Ke.ADD_DATA_URI_TAGS,qi):ow,ki=gv(Ke,"FORBID_CONTENTS")?Nr({},Ke.FORBID_CONTENTS,qi):Va,Mn=gv(Ke,"FORBID_TAGS")?Nr({},Ke.FORBID_TAGS,qi):Pg({}),bn=gv(Ke,"FORBID_ATTR")?Nr({},Ke.FORBID_ATTR,qi):Pg({}),yv=gv(Ke,"USE_PROFILES")?Ke.USE_PROFILES:!1,Ro=Ke.ALLOW_ARIA_ATTR!==!1,la=Ke.ALLOW_DATA_ATTR!==!1,Cd=Ke.ALLOW_UNKNOWN_PROTOCOLS||!1,HC=Ke.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Sv=Ke.SAFE_FOR_TEMPLATES||!1,Wg=Ke.SAFE_FOR_XML!==!1,bd=Ke.WHOLE_DOCUMENT||!1,qg=Ke.RETURN_DOM||!1,xh=Ke.RETURN_DOM_FRAGMENT||!1,Ih=Ke.RETURN_TRUSTED_TYPE||!1,WC=Ke.FORCE_BODY||!1,qC=Ke.SANITIZE_DOM!==!1,rw=Ke.SANITIZE_NAMED_PROPS||!1,Eh=Ke.KEEP_CONTENT!==!1,Nm=Ke.IN_PLACE||!1,ar=Ke.ALLOWED_URI_REGEXP||mbe,xv=Ke.NAMESPACE||Us,Dh=Ke.MATHML_TEXT_INTEGRATION_POINTS||Dh,Oh=Ke.HTML_INTEGRATION_POINTS||Oh,Jr=Ke.CUSTOM_ELEMENT_HANDLING||{},Ke.CUSTOM_ELEMENT_HANDLING&&Yg(Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Jr.tagNameCheck=Ke.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ke.CUSTOM_ELEMENT_HANDLING&&Yg(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),Sv&&(la=!1),xh&&(qg=!0),yv&&($r=Nr({},abe),Zn=[],yv.html===!0&&(Nr($r,ibe),Nr(Zn,lbe)),yv.svg===!0&&(Nr($r,dQ),Nr(Zn,gQ),Nr(Zn,ML)),yv.svgFilters===!0&&(Nr($r,vQ),Nr(Zn,gQ),Nr(Zn,ML)),yv.mathMl===!0&&(Nr($r,mQ),Nr(Zn,cbe),Nr(Zn,ML))),Ke.ADD_TAGS&&(typeof Ke.ADD_TAGS=="function"?hi.tagCheck=Ke.ADD_TAGS:($r===bo&&($r=Pg($r)),Nr($r,Ke.ADD_TAGS,qi))),Ke.ADD_ATTR&&(typeof Ke.ADD_ATTR=="function"?hi.attributeCheck=Ke.ADD_ATTR:(Zn===_o&&(Zn=Pg(Zn)),Nr(Zn,Ke.ADD_ATTR,qi))),Ke.ADD_URI_SAFE_ATTR&&Nr(YC,Ke.ADD_URI_SAFE_ATTR,qi),Ke.FORBID_CONTENTS&&(ki===Va&&(ki=Pg(ki)),Nr(ki,Ke.FORBID_CONTENTS,qi)),Eh&&($r["#text"]=!0),bd&&Nr($r,["html","head","body"]),$r.table&&(Nr($r,["tbody"]),delete Mn.tbody),Ke.TRUSTED_TYPES_POLICY){if(typeof Ke.TRUSTED_TYPES_POLICY.createHTML!="function")throw AO('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ke.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw AO('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');re=Ke.TRUSTED_TYPES_POLICY,_e=re.createHTML("")}else re===void 0&&(re=lWe(I,t)),re!==null&&typeof _e=="string"&&(_e=re.createHTML(""));xc&&xc(Ke),_d=Ke}},Ba=Nr({},[...dQ,...vQ,...Zze]),sw=Nr({},[...mQ,...Jze]),Mh=function(Ke){let Ut=be(Ke);(!Ut||!Ut.tagName)&&(Ut={namespaceURI:xv,tagName:"template"});let sn=PL(Ke.tagName),Go=PL(Ut.tagName);return aw[Ke.namespaceURI]?Ke.namespaceURI===Th?Ut.namespaceURI===Us?sn==="svg":Ut.namespaceURI===kv?sn==="svg"&&(Go==="annotation-xml"||Dh[Go]):!!Ba[sn]:Ke.namespaceURI===kv?Ut.namespaceURI===Us?sn==="math":Ut.namespaceURI===Th?sn==="math"&&Oh[Go]:!!sw[sn]:Ke.namespaceURI===Us?Ut.namespaceURI===Th&&!Oh[Go]||Ut.namespaceURI===kv&&!Dh[Go]?!1:!sw[sn]&&(Ah[sn]||!Ba[sn]):!!(Fm==="application/xhtml+xml"&&aw[Ke.namespaceURI]):!1},Ml=function(Ke){DO(o.removed,{element:Ke});try{be(Ke).removeChild(Ke)}catch{B(Ke)}},Um=function(Ke,Ut){try{DO(o.removed,{attribute:Ut.getAttributeNode(Ke),from:Ut})}catch{DO(o.removed,{attribute:null,from:Ut})}if(Ut.removeAttribute(Ke),Ke==="is")if(qg||xh)try{Ml(Ut)}catch{}else try{Ut.setAttribute(Ke,"")}catch{}},$5=function(Ke){let Ut=null,sn=null;if(WC)Ke="<remove></remove>"+Ke;else{let ii=sQ(Ke,/^[\r\n\t ]+/);sn=ii&&ii[0]}Fm==="application/xhtml+xml"&&xv===Us&&(Ke='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Ke+"</body></html>");let Go=re?re.createHTML(Ke):Ke;if(xv===Us)try{Ut=new _().parseFromString(Go,Fm)}catch{}if(!Ut||!Ut.documentElement){Ut=Ie.createDocument(xv,"template",null);try{Ut.documentElement.innerHTML=iw?_e:Go}catch{}}let ja=Ut.body||Ut.documentElement;return Ke&&sn&&ja.insertBefore(r.createTextNode(sn),ja.childNodes[0]||null),xv===Us?Oe.call(Ut,bd?"html":"body")[0]:bd?Ut.documentElement:ja},Vm=function(Ke){return Ce.call(Ke.ownerDocument||Ke,Ke,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},dw=function(Ke){return Ke instanceof u&&(typeof Ke.nodeName!="string"||typeof Ke.textContent!="string"||typeof Ke.removeChild!="function"||!(Ke.attributes instanceof m)||typeof Ke.removeAttribute!="function"||typeof Ke.setAttribute!="function"||typeof Ke.namespaceURI!="string"||typeof Ke.insertBefore!="function"||typeof Ke.hasChildNodes!="function")},G5=function(Ke){return typeof l=="function"&&Ke instanceof l};function Mc(kn,Ke,Ut){AL(kn,sn=>{sn.call(o,Ke,Ut,_d)})}let vw=function(Ke){let Ut=null;if(Mc(je.beforeSanitizeElements,Ke,null),dw(Ke))return Ml(Ke),!0;let sn=qi(Ke.nodeName);if(Mc(je.uponSanitizeElement,Ke,{tagName:sn,allowedTags:$r}),Wg&&Ke.hasChildNodes()&&!G5(Ke.firstElementChild)&&kc(/<[/\w!]/g,Ke.innerHTML)&&kc(/<[/\w!]/g,Ke.textContent)||Ke.nodeType===PO.progressingInstruction||Wg&&Ke.nodeType===PO.comment&&kc(/<[/\w]/g,Ke.data))return Ml(Ke),!0;if(!(hi.tagCheck instanceof Function&&hi.tagCheck(sn))&&(!$r[sn]||Mn[sn])){if(!Mn[sn]&&Ph(sn)&&(Jr.tagNameCheck instanceof RegExp&&kc(Jr.tagNameCheck,sn)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(sn)))return!1;if(Eh&&!ki[sn]){let Go=be(Ke)||Ke.parentNode,ja=ae(Ke)||Ke.childNodes;if(ja&&Go){let ii=ja.length;for(let pl=ii-1;pl>=0;--pl){let os=M(ja[pl],!0);os.__removalCount=(Ke.__removalCount||0)+1,Go.insertBefore(os,q(Ke))}}}return Ml(Ke),!0}return Ke instanceof c&&!Mh(Ke)||(sn==="noscript"||sn==="noembed"||sn==="noframes")&&kc(/<\/no(script|embed|frames)/i,Ke.innerHTML)?(Ml(Ke),!0):(Sv&&Ke.nodeType===PO.text&&(Ut=Ke.textContent,AL([We,ze,jr],Go=>{Ut=OO(Ut,Go," ")}),Ke.textContent!==Ut&&(DO(o.removed,{element:Ke.cloneNode()}),Ke.textContent=Ut)),Mc(je.afterSanitizeElements,Ke,null),!1)},ZC=function(Ke,Ut,sn){if(qC&&(Ut==="id"||Ut==="name")&&(sn in r||sn in j5))return!1;if(!(la&&!bn[Ut]&&kc(nt,Ut))){if(!(Ro&&kc(Et,Ut))){if(!(hi.attributeCheck instanceof Function&&hi.attributeCheck(Ut,Ke))){if(!Zn[Ut]||bn[Ut]){if(!(Ph(Ke)&&(Jr.tagNameCheck instanceof RegExp&&kc(Jr.tagNameCheck,Ke)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(Ke))&&(Jr.attributeNameCheck instanceof RegExp&&kc(Jr.attributeNameCheck,Ut)||Jr.attributeNameCheck instanceof Function&&Jr.attributeNameCheck(Ut,Ke))||Ut==="is"&&Jr.allowCustomizedBuiltInElements&&(Jr.tagNameCheck instanceof RegExp&&kc(Jr.tagNameCheck,sn)||Jr.tagNameCheck instanceof Function&&Jr.tagNameCheck(sn))))return!1}else if(!YC[Ut]){if(!kc(ar,OO(sn,$t,""))){if(!((Ut==="src"||Ut==="xlink:href"||Ut==="href")&&Ke!=="script"&&Wze(sn,"data:")===0&&wh[Ke])){if(!(Cd&&!kc(Je,OO(sn,$t,"")))){if(sn)return!1}}}}}}}return!0},Ph=function(Ke){return Ke!=="annotation-xml"&&sQ(Ke,Qt)},Sd=function(Ke){Mc(je.beforeSanitizeAttributes,Ke,null);let{attributes:Ut}=Ke;if(!Ut||dw(Ke))return;let sn={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Zn,forceKeepAttr:void 0},Go=Ut.length;for(;Go--;){let ja=Ut[Go],{name:ii,namespaceURI:pl,value:os}=ja,Vs=qi(ii),yd=os,Yi=ii==="value"?yd:qze(yd);if(sn.attrName=Vs,sn.attrValue=Yi,sn.keepAttr=!0,sn.forceKeepAttr=void 0,Mc(je.uponSanitizeAttribute,Ke,sn),Yi=sn.attrValue,rw&&(Vs==="id"||Vs==="name")&&(Um(ii,Ke),Yi=aB+Yi),Wg&&kc(/((--!?|])>)|<\/(style|title|textarea)/i,Yi)){Um(ii,Ke);continue}if(Vs==="attributename"&&sQ(Yi,"href")){Um(ii,Ke);continue}if(sn.forceKeepAttr)continue;if(!sn.keepAttr){Um(ii,Ke);continue}if(!HC&&kc(/\/>/i,Yi)){Um(ii,Ke);continue}Sv&&AL([We,ze,jr],mw=>{Yi=OO(Yi,mw," ")});let z5=qi(Ke.nodeName);if(!ZC(z5,Vs,Yi)){Um(ii,Ke);continue}if(re&&typeof I=="object"&&typeof I.getAttributeType=="function"&&!pl)switch(I.getAttributeType(z5,Vs)){case"TrustedHTML":{Yi=re.createHTML(Yi);break}case"TrustedScriptURL":{Yi=re.createScriptURL(Yi);break}}if(Yi!==yd)try{pl?Ke.setAttributeNS(pl,ii,Yi):Ke.setAttribute(ii,Yi),dw(Ke)?Ml(Ke):obe(o.removed)}catch{Um(ii,Ke)}}Mc(je.afterSanitizeAttributes,Ke,null)},H5=function kn(Ke){let Ut=null,sn=Vm(Ke);for(Mc(je.beforeSanitizeShadowDOM,Ke,null);Ut=sn.nextNode();)Mc(je.uponSanitizeShadowNode,Ut,null),vw(Ut),Sd(Ut),Ut.content instanceof i&&kn(Ut.content);Mc(je.afterSanitizeShadowDOM,Ke,null)};return o.sanitize=function(kn){let Ke=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ut=null,sn=null,Go=null,ja=null;if(iw=!kn,iw&&(kn="<!-->"),typeof kn!="string"&&!G5(kn))if(typeof kn.toString=="function"){if(kn=kn.toString(),typeof kn!="string")throw AO("dirty is not a string, aborting")}else throw AO("toString is not a function");if(!o.isSupported)return kn;if(zC||KC(Ke),o.removed=[],typeof kn=="string"&&(Nm=!1),Nm){if(kn.nodeName){let os=qi(kn.nodeName);if(!$r[os]||Mn[os])throw AO("root node is forbidden and cannot be sanitized in-place")}}else if(kn instanceof l)Ut=$5("<!---->"),sn=Ut.ownerDocument.importNode(kn,!0),sn.nodeType===PO.element&&sn.nodeName==="BODY"||sn.nodeName==="HTML"?Ut=sn:Ut.appendChild(sn);else{if(!qg&&!Sv&&!bd&&kn.indexOf("<")===-1)return re&&Ih?re.createHTML(kn):kn;if(Ut=$5(kn),!Ut)return qg?null:Ih?_e:""}Ut&&WC&&Ml(Ut.firstChild);let ii=Vm(Nm?kn:Ut);for(;Go=ii.nextNode();)vw(Go),Sd(Go),Go.content instanceof i&&H5(Go.content);if(Nm)return kn;if(qg){if(xh)for(ja=Te.call(Ut.ownerDocument);Ut.firstChild;)ja.appendChild(Ut.firstChild);else ja=Ut;return(Zn.shadowroot||Zn.shadowrootmode)&&(ja=Me.call(e,ja,!0)),ja}let pl=bd?Ut.outerHTML:Ut.innerHTML;return bd&&$r["!doctype"]&&Ut.ownerDocument&&Ut.ownerDocument.doctype&&Ut.ownerDocument.doctype.name&&kc(gbe,Ut.ownerDocument.doctype.name)&&(pl="<!DOCTYPE "+Ut.ownerDocument.doctype.name+`>
222
- `+pl),Sv&&AL([We,ze,jr],os=>{pl=OO(pl,os," ")}),re&&Ih?re.createHTML(pl):pl},o.setConfig=function(){let kn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};KC(kn),zC=!0},o.clearConfig=function(){_d=null,zC=!1},o.isValidAttribute=function(kn,Ke,Ut){_d||KC({});let sn=qi(kn),Go=qi(Ke);return ZC(sn,Go,Ut)},o.addHook=function(kn,Ke){typeof Ke=="function"&&DO(je[kn],Ke)},o.removeHook=function(kn,Ke){if(Ke!==void 0){let Ut=Hze(je[kn],Ke);return Ut===-1?void 0:zze(je[kn],Ut,1)[0]}return obe(je[kn])},o.removeHooks=function(kn){je[kn]=[]},o.removeAllHooks=function(){je=dbe()},o}var dS=ube();var pbe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Ve=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new it,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new it,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new ur),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let c=[];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 m=!1;d.childNodes.forEach(u=>{Co(u)&&(m=!0)}),m||c.push(d)}else c.push(d)}else c.push(d)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Pr(),ln(([c,d])=>{try{let m=d.filter(_=>!c.includes(_)),u=c.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]()}),m.length&&m.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(m){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",m)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?ehe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):the("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}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 c=e.getAttribute(l);c&&c.length<=256&&(t[l]=c)}),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,m)=>{let u=l.findIndex(I=>d.startsWith(I)),_=l.findIndex(I=>m.startsWith(I));return(u===-1?99:u)-(_===-1?99:_)}).slice(0,4).forEach(d=>{let m=CSS.escape(t[d]);a.push(`[${d}="${m}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,c=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),c++,c>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return $pe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],c=e,d=0;for(;c&&c!==document.documentElement&&d<i;){let I=this.buildRobustXPathSegment(c);if(I&&(l.unshift(I),this.isStrongAnchorSegment(I)))break;c=c.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 c=e.getAttribute("role");if(c)return`${t}[@role=${this.escapeXPathValue(c)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let m=e.getAttribute("name");if(m)return`${t}[@name=${this.escapeXPathValue(m)}]`;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(c=>`'${c}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}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&&Yr(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,c=this.getStableAttributes(i),d=this.buildStableElementSelector(i,c),m=this.getVisibleText(i),u=this.hashText(m||""),_=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 c=t[0].score,d=t.filter(u=>u.score===c);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 m=t[0];return{element:m.el,matchedBy:m.by,score:m.score,scoreBreakdown:m.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(c=>{let d=c;if(typeof d.getAttribute=="function"){let m=d.getAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(m!==null&&m!==""){let u=this.xpathCacheId.get(m);u!==void 0&&(this.xpathCacheId.delete(m),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(c=>{a.target?.closest(c)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Yr(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"),m=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(m||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,c=e.className||"";return typeof c=="string"&&(c.includes("slider")&&(c.includes("bullet")||c.includes("pagination"))&&(l=!0),c.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{No(kr(window,"offline").pipe(ge(()=>!1)),kr(window,"online").pipe(ge(()=>!0)),new Vt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let t=this.calculateScreenSize();this.deviceInfo$.next(new ur),this.currentScreenSize$.next(t)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}onPointerDown(){this.loggingService.log("%c[WB] Calling FUNCTION: onPointerDown","color: green;");try{this.unsubscribeFromPointerDown(),this.unlistenPointerDown=this.renderer.listen("window","pointerdown",e=>{this.mousedown=!0,this.windowMouseDown$.next(e),this.setPointerPosition(e)})}catch(e){this.loggingService.catch("Error in DomService onPointerDown: ",e)}}unsubscribeFromPointerDown(){try{this.unlistenPointerDown&&typeof this.unlistenPointerDown=="function"&&(this.unlistenPointerDown(),this.unlistenPointerDown=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromPointerDown: ",e)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowClick(),this.unlistenWindowClick=this.renderer.listen("window","click",e=>{this.windowClick$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowClick: ",e)}}unsubscribeFromWindowClick(){try{this.unlistenWindowClick&&typeof this.unlistenWindowClick=="function"&&(this.unlistenWindowClick(),this.unlistenWindowClick=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowClick: ",e)}}onWindowKeyupBackspace(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupBackspace","color: green;");try{this.unsubscribeFromWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=this.renderer.listen("window","keyup.backspace",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupBackspace$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupBackspace: ",e)}}unsubscribeFromWindowKeyupBackspace(){try{this.unlistenWindowKeyupBackspace&&typeof this.unlistenWindowKeyupBackspace=="function"&&(this.unlistenWindowKeyupBackspace(),this.unlistenWindowKeyupBackspace=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupBackspace: ",e)}}onWindowKeyupDelete(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupDelete","color: green;");try{this.unsubscribeFromWindowKeyupDelete(),this.unlistenWindowKeyupDelete=this.renderer.listen("window","keyup.delete",e=>{this.isVideoEditorHandlingDelete||this.windowKeyupDelete$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupDelete: ",e)}}unsubscribeFromWindowKeyupDelete(){try{this.unlistenWindowKeyupDelete&&typeof this.unlistenWindowKeyupDelete=="function"&&(this.unlistenWindowKeyupDelete(),this.unlistenWindowKeyupDelete=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupDelete: ",e)}}onWindowKeyupEsc(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowKeyupEsc","color: green;");try{this.unsubscribeFromWindowKeyupEsc(),this.unlistenWindowKeyupEsc=this.renderer.listen("window","keyup.esc",e=>{this.windowKeyupEsc$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowKeyupEsc: ",e)}}unsubscribeFromWindowKeyupEsc(){try{this.unlistenWindowKeyupEsc&&typeof this.unlistenWindowKeyupEsc=="function"&&(this.unlistenWindowKeyupEsc(),this.unlistenWindowKeyupEsc=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowKeyupEsc: ",e)}}onWindowPopState(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopState","color: green;");try{this.unsubscribeFromWindowPopState(),this.unlistenWindowPopState=this.renderer.listen("window","popstate",e=>{this.windowPopState$.next(e)})}catch(e){this.loggingService.catch("Error in DomService onWindowPopState: ",e)}}unsubscribeFromWindowPopState(){try{this.unlistenWindowPopState&&typeof this.unlistenWindowPopState=="function"&&(this.unlistenWindowPopState(),this.unlistenWindowPopState=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowPopState: ",e)}}onDocumentClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onDocumentClick","color: green;");try{this.unsubscribeFromDocumentClick(),this.documentClickListener=e=>{e?.target?.tagName?.toLowerCase()!==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 kr(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Bs}}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,c=e.clientY-a.y,d=l*100/(a.width||1),m=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:m,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,c=!0,d){try{let m=e,u=m?.touches?.length?m.touches[0]?.clientX:m?.clientX,_=m?.touches?.length?m.touches[0]?.clientY:m?.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,be=q*100/(B.width||1),re=ae*100/(B.height||1),_e={xpath:A,fXpath:M,leftPercentage:be,topPercentage:re};if(a){let Ie=this.getXPath(I,!0,!0);_e.cfXpath=Ie}if(c){let Ie=this.generateAnchorRecord(I);Ie&&(_e.anchor=Ie)}return _e}else return null}catch(m){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",m),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),c=[];l.forEach(m=>{Co(m)?c=[]:Yr(m)&&c.push(m)}),a&&(c=c.filter(m=>this.isElementVisibleOnScreen(m)));let d=0;return i||c?.forEach((m,u)=>{m.tagName.toLowerCase()==="svg"&&(d=u)}),c[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)&&Yr(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"),c=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(N.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),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 c=l.split("/"),d=!1;c.forEach((m,u)=>{m.includes("svg")&&(d=!0),d&&(c[u]="svg:"+m)}),l=c.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 c=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(c){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),m=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]===c:!1);if(m.length>1){let u=m.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.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=lt();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 S3;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 S3}}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),m;for(;m=d.nextNode();)m?.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),c=Object.keys(this.getRecordingInProgress()||{});l=[...l,...c];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 m={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(m[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(m[u]=d[u]);break;default:d[u]?.type!==t&&(m[u]=d[u]);break}}),Object.keys(m).forEach(u=>{let _=m[u]?.multiThreadAnnotationId;_&&!m[_]&&(m[_]={annotationId:_,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(m)&&this.selectedAnnotationsMap$.next(m),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 c=l.shadowRoot.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);c&&e.push(c)}else{let c=l.querySelector(`${N.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(c?.shadowRoot){let d=c.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 c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(c[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(d).forEach(m=>{c[m]||delete d[m]}),this.selectedAnnotationsLocationMap$.next(d)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}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),ce([])}}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),ce([])}}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 c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let m=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-m.left,i.offsetTop+=u.top-m.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 Vt(e=>{let t=kr(document,"mousedown").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=kr(document,"mousemove").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=kr(document,"mouseup").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),c=t.pipe(ye(d=>i.pipe(Pr(),ge(([m,u])=>({startPoint:d,prevPoint:m,curPoint:u})),zo(a)))).subscribe(e);return()=>c.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),c=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=`${c}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 c=this.getTextXPath(i);this.isXpathWithId(c)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);if(c){t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let d=this.generateAnchorRecord(c);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=p0(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 c=document.getElementById(e[l]);c&&a.push(c)}if(t?.length)for(let l=0;l<t.length;l++){let c=document.getElementsByClassName(t[l]);for(let d=0;d<c.length;d++){let m=c[d];m&&m instanceof HTMLElement&&a.push(m)}}if(i?.length)for(let l=0;l<i.length;l++){let c=document.querySelectorAll(i[l]);for(let d=0;d<c.length;d++){let m=c[d];m&&m instanceof HTMLElement&&a.push(m)}}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),ce(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)}}subscribeInjectCustomCss(e){try{return this.customCss$.subscribe(()=>{this.injectCustomCss(e?.nativeElement)})}catch(t){return this.loggingService.catch("Error in DomService subscribeInjectCustomCss: ",t),new Ln}}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;"),dS.sanitize(e,pbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeHtmlForPaste(e){try{let t=this.convertStylesToTags(e);return dS.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.convertBlockElementsToBr(t),this.processNodeStyles(t),t.innerHTML}catch(t){return this.loggingService.catch("Error in DomService convertStylesToTags: ",t),e}}convertBlockElementsToBr(e){try{let t=["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","SECTION","ARTICLE","HEADER","FOOTER"],i;for(;(i=e.querySelector(t.join(",")))!==null;){let a=i.parentNode;if(!a)break;for(;i.firstChild;)a.insertBefore(i.firstChild,i);i.nextSibling&&a.insertBefore(document.createElement("br"),i),a.removeChild(i)}}catch(t){this.loggingService.catch("Error in DomService convertBlockElementsToBr: ",t)}}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,c=i,d=l?.fontWeight;if(d==="bold"||d==="700"||d==="800"||d==="900"){let m=a.tagName?.toLowerCase();if(m!=="b"&&m!=="strong"){let u=document.createElement("b");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}if(l?.fontStyle==="italic"){let m=a.tagName?.toLowerCase();if(m!=="i"&&m!=="em"){let u=document.createElement("i");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}if((l?.textDecorationLine?.includes("underline")||l?.textDecoration?.includes("underline"))&&a.tagName?.toLowerCase()!=="u"){let u=document.createElement("u");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}}catch(t){this.loggingService.catch("Error in DomService processNodeStyles: ",t)}}sanitizeSvg(e){try{return dS.sanitize(e,pbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ur;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),ce(new ur)}}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=lt(),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 ur}}isMobileDevice(){try{return new ur().getDeviceType()===ji.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ur().getDeviceType()===ji.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ur().getDeviceType()===ji.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(c=>{l.setAttribute(c.name,c.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new ur().getDeviceType()===ji.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)(K(ct),K(xi),K(k),K($d))},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,c,d,m){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=c,this.analyticsService=d,this.loggingService=m,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(So(this.afAuth.currentUser),Pr(),ye(([u,_])=>this.domService.onNetworkStatusChange$().pipe(Ge(I=>I),ut(1),ge(()=>({previousUser:u,currentUser:_}))))).subscribe(I=>X(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(_t(Kt)).subscribe(u=>{let _=Vo(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 wN),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=>X(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Zv(a,!0).catch(c=>null);if(l){let{user:c}=l?.claims;this.autoLoginRequired&&(c=yield this.updateUserWithColorAndTextColor(c),this.initializeClient(c,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 X(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 XK(()=>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(Ge(a=>a.code==="token_expired"),ut(10)).subscribe(a=>X(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],m=this.docService?.getLocation();m&&d.push(m.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(I=>{d.push(I.location)}),(yield XK(()=>X(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:c,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!m}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return X(this,null,function*(){try{if(e){let t=yield Es(e,e?.userId??"");localStorage.setItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return X(this,null,function*(){try{let t=localStorage.getItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield g1(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 X(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 X(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 X(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=cd(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let c=yield Cr(this.afAuth).pipe(ut(1)).toPromise().catch(m=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let m=yield Zv(c,!0).catch(A=>null);if(!m)return;let{user:u,firebaseConfig:_,advancedQueries:I}=m.claims;c?.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(c,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 m=qr(this.functions,Kr({url:On.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=el(),_=(yield m({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 Zv(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(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),t?.throwError?Promise.reject(c):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=el();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=el();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({},On.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 gn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ge(()=>this.getAdvancedQueriesEnabled()),Jn(()=>ce(!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(ye(e=>e?this.user$.asObservable():ce(null)),_t(Kt))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=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 mde(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 X(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=lt(),l=ys.IDENTIFY;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:vi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let c=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});c&&c[e.userId]&&(i=JSON.parse(JSON.stringify(c[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 X(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=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=El({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let m=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:to.IDENTIFY,organizationId:e.clientOrganizationId}}],u=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:m}}),l=this.userPermissionService?.onResourceAccessRequired({requests:m,uniqueId:u,userId:e.userId,methodName:to.IDENTIFY,fromCache:!1})??Promise.resolve()}let[c,d]=yield Promise.allSettled([a,l]);c.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!c.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(c.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",c.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 X(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield qr(this.functions,Kr({url:On.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:el(),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(Ge(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(ye(e=>e?this.userOrganization$.asObservable().pipe(ge(t=>t?.metadata?.organizationId===e.organizationId?t:null)):ce(null)))}signOutUser(e="internal"){return X(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 ep(1e3),gde(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 Mo(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 Vo(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)(K(Qr),K(Ft),K(fm),K(tr),K(Ve),K(Oo),K(ct),K(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(),c=a.firebaseOptions.databaseURL;l?.v1DbHost&&c&&(c=zN(c,l.v1DbHost),l?.forceLongPolling&&Vq());let d=T_(void 0,c);l?.v1DbHost&&c&&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)(K(qe),K(Ft),K(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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.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 m(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],B=y(h({},e),{commentAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.commentAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.commentAnnotationById$.next(h(h({},this.commentAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(c?.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:ti.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:c,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:ti.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||lt();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return X(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?oi(t):void 0),m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.commentAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:m,event:xo.COMMENT_ANNOTATION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:m,event:xo.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:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:I,commentAnnotationId:e.toString(),metadata:m}}),{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:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Xc=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.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 m(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],B=y(h({},e),{reactionAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.reactionAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.reactionAnnotationById$.next(h(h({},this.reactionAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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 c={reactionAnnotation:e,event:xo.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Oi(()=>i?.config?.saveConfig?.url?$i(i.config.saveConfig.url,i.config.saveConfig.headers,c,!1):i?.save?.(c)||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:ni.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:c.event}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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||lt();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return X(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())),c=t??l?.[e]?.metadata,d=c?oi(c):void 0,m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.reactionAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:m,event:xo.REACTION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:m,event:xo.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:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:I,reactionAnnotationId:e.toString(),metadata:m}}),{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:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Qc=(()=>{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 X(this,null,function*(){try{let l=new FormData;l.append("file",i);let c={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(c));let d={};t&&Object.entries(t).forEach(([_,I])=>{_.toLowerCase()!=="content-type"&&(d[_]=I)});let m=yield fetch(e,{method:"POST",headers:d,body:l});return m.ok?{data:(yield m.json())?.data??{},success:!0,statusCode:200}:(at.catch(`Error in makeAttachmentConfigBasedRequest: ${m.status} ${m.statusText}`),{data:{},success:!1,statusCode:m.status})}catch(l){return at.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return X(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),c=t||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Oi(()=>X(this,null,function*(){if(a?.config?.saveConfig?.url){let m=e.attachment,{file:u}=m,_=Fh(m,["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:c,methodName:ks.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:c,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,c,d){return X(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let m=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||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:I,methodName:ks.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Oi(()=>{if(m?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:xo.ATTACHMENT_DELETE};return $i(m.config.deleteConfig.url,m.config.deleteConfig.headers,M,!1)}return m?.delete?.({attachmentId:e,metadata:u,event:xo.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:ks.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:ks.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:_.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!0})}catch(m){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",m);let u=this.getRetryDeleteConfig(a),_=i||lt(),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:ks.DELETE_ATTACHMENT,source:"internal",payload:{error:m,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:c,configKey:d})=>{let m=i?.[d]?.url,u=c in e&&typeof e[c]=="function";!m&&!u&&l.push(c)}),l.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(c);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)(K(tr),K(k),K(ct))},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(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.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 m(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],B=y(h({},e),{recorderAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.recorderAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.recorderAnnotationById$.next(h(h({},this.recorderAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(c?.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:ri.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,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:ri.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||lt();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return X(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?oi(t):void 0),m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.recorderAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:m,event:xo.RECORDER_ANNOTATION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:m,event:xo.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:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:I,recorderAnnotationId:e.toString(),metadata:m}}),{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:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct),K(Qc))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var st=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=c,this.commentResolverService=d,this.reactionResolverService=m,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 it,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(jB(()=>as(this.currentDebounceTime))).subscribe({next:A=>X(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(Ge(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=XN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>X(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(Ge(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=XN(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=XN(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 X(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:kl.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(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}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))&&sr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(m=>m.clientDocumentId),c=JN(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(m=>l.includes(m.id))||!sr(c,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,c=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:c,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return X(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:kl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(i){return X(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:kl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(c=>c.clientDocumentId);if(!l.includes(e.id)){let c=[...l.map(m=>({id:m})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:c,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(_t(Kt))}getProcessedDocContext(){return uhe(this.getDocContext())}filterRelevantDocuments(a){return X(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 X(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield El({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(c=>{t.find(d=>d.clientDocumentId===c.id)||t.push({documentId:mi(c.id),clientDocumentId:c.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:to.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:to.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:to.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&rF({input:e?.context}).forEach(c=>{let d=JSON.stringify(c.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:to.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:c}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let 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(c=>i.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),l=phe({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 X(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=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:to.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(c,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return X(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 c=this.currentValidationToken,d=[...t];return c&&this.validatePermissionsInBackground(e,t,i,c),d})}validateAndFilterPermissions(e,t,i){return X(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(m=>m.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===fo.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===fo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([m,u])=>{u?.errorCode===fo.PERMISSION_DENIED&&c.add(m)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].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:[...c],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(m=>!c.has(m.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(c=>c.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(c=>{if(this.currentValidationToken===a&&c){this.userPermissionService?.setCurrentUserPermissions(c);let d=[];Object.entries(c?.[i.userId]?.documents??{}).forEach(([m,u])=>{u?.errorCode===fo.PERMISSION_DENIED&&d.push(m)}),l&&c?.[i.userId]?.organization?.[l]?.errorCode===fo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&c?.[i.userId]?.folders?.[e?.folderId]?.errorCode===fo.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(c=>{this.loggingService.catch("Error in background permission validation:",c)})}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||[],c=l.filter(d=>!e.includes(d.clientDocumentId));c.length!==l.length&&(c.length>0?this.setDocuments({documents:c.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 X(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let c=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield El({data:h({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:c,userId:a??t?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(l){return X(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,JN(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=lt();this.currentValidationToken=c;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 m=this.authService.getUser();if(!m){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(_=>_.id),this.pendingOptions=JN(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??m?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:m}),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(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(a){return X(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:kl.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 X(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 c=Date.now(),d=c-this.lastSetDocumentIdCallTime,m=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&m>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=c;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 X(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 c=`${Qn(e)}`,d=i?.folderId,m=i?.folderId?Rr(i?.folderId):void 0,u=i?.locationId,_=i?.allDocuments,I=a?.organizationId?t?It(t):a?.organizationId:void 0,A=lt(),M=o1.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ti.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let B=lt(),q=i1.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:ni.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=lt(),be=a1.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:be,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:B,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:be})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==I){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let re=new ON,_e=new RL;re.clientDocumentId=e,_e.clientDocumentId=e,re.folderId=d,_e.folderId=d,re.locationId=u,_e.locationId=u,re.allDocuments=_,_e.allDocuments=_,re.veltFolderId=m,_e.veltFolderId=m,re.documentId=c,_e.documentId=c,I&&(re.organizationId=I,re.clientOrganizationId=t??a?.clientOrganizationId,_e.organizationId=I,_e.clientOrganizationId=t??a?.clientOrganizationId);let Ie=`${this.apiKey}`,Ce=`apiKey/${this.apiKey}`;I&&(Ie=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${re.organizationId}`,Ce=`${Ce}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${re.organizationId}`),_e.organization=`apiKey/${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,_e.document=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,re.presence=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,re.cursor=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,re.comment=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,_e.comment=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,re.multiThread=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,_e.multiThread=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,re.tag=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,re.area=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,_e.area=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AREA}`,re.arrow=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,re.selection=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,re.audioHuddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,re.huddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,re.recorder=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,_e.recorder=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,re.flock=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,re.syncVideoPlayer=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,re.liveState=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,re.liveStateSingleEditorMode=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,re.reaction=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,_e.reaction=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,re.crdt=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,_e.crdt=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,re.customerMetadata=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,re.views=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,_e.notificationViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,_e.documentViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,_e.locationViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,re.notifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,re.metadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,re.users=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,re.documentIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.workspaceIam=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.groupContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,re.globalContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,re.logins=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,re.userFeedback=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,re.userReportBugs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,re.userContactUs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,I&&(re.organizationMetadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,re.organizationIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.organizationGroups=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,re.organizationNotifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(re.organizationNotificationsWithDocumentId=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,re.heartbeatByDocument=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),re.organizationNotificationsLastNotificationTimestamp=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,re.organizationNotificationsUsers=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,re.heartbeat=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),_e.organizationUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,_e.users=`${Ce}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,_e.documentUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,_e.notificationDocs=`${Ce}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,_e.notificationUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(re),this.firestorePaths$.next(_e),re?.clientOrganizationId&&re?.organizationId&&!(re?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&re?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:re?.organizationId,clientOrganizationId:re?.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:c,clientDocumentId:e}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(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:kl.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:kl.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 X(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 X(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 X(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=[],c={organizationId:t?.clientOrganizationId,folderId:a},d=[],m=20;for(let _=0;_<e.length;_+=m)d.push(e.slice(_,_+m));d.forEach(_=>{let I=JSON.parse(JSON.stringify(c));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 X(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=[],c={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],m=20;for(let _=0;_<t.length;_+=m)d.push(t.slice(_,_+m));d.forEach(_=>{let I=JSON.parse(JSON.stringify(c));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(Jn(t=>ce(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 X(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:kl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return X(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:kl.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 X(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:kl.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=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...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=Di(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=Di(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}let m=[];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:_}),m.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:kl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),m}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:kl.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:kl.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:kl.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:kl.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:kl.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),ce([])}}updateOrganizationMetadata(e){return X(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 VN;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 X(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=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield El({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 X(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=>X(this,null,function*(){let l=new DN;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 c=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let m=!0,u=this.documentMetadata$.value?.[a.documentId];if(c&&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!==c||_?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),m=!1):_?.folderId===c?(c&&(l.folderId=c),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),m=!1):(c&&(l.folderId=c),d&&(l.veltFolderId=d))}if(u){let _={};Object.entries(l).forEach(([I,A])=>{_[I]=A}),sr(_,u)&&(m=!1)}m&&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 X(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 c=[];for(let d of e){let m=new RN;m.locationId=d?.locationId,m.veltLocationId=BK(d?.location?.id??""),m.location=d?.location,m.pageInfo=no(),m?.pageInfo?.deviceInfo&&delete m?.pageInfo?.deviceInfo;let u=y(h({},l),{[N.FIREBASE_PARTIAL_PATH_LOCATIONS]:y(h({},l[N.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:m})});this.commonDbService?.shouldUseFirestore()||c.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(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Di(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(c=>c.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 c=JSON.parse(l),d=this.genarateLocationId(c);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),ce({})}}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 c={id:a},d=this.genarateLocationId(c);e[a]={element:i,location:{locationId:d,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${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),_t(Kt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(e=>e||{}),_t(Kt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},t={},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(c=>{let d=e?.[c.documentId];d&&(t[c.documentId]=d)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),_t(Kt))}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||{}),_t(Kt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(_t(Kt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(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,c=this.getDocumentMetadata(l);if(!c)return;let d=c?.folderId,m=c?.veltFolderId;return h(h({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),m?{veltFolderId:m}:{})}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),c=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||c||{};return d.sdkVersion=el(),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 X(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=Rr(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 X(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=Rr(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 X(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 c=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],m=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=c,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=Rr(l||this.documentPaths$.value?.folderId||""));let I=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=m?.[_];M?m[_]=h(h({},M),u):m[_]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:_,organizationId:c,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:c,documentId:_}}))}yield Promise.all(d),this.setAllDocumentMetadata(m)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return X(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 c=l.map(u=>mi(u)),d=[],m=this.locationMetadata$.value;m||(m={}),c.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=BK(_.id),M=m?.[u],B=M?.[_.id];m&&(M||(m[u]={}),B||(m[u][_.id]={}),m[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(m||{}).length>0&&this.locationMetadata$.next(m)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return X(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 c=Rr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,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","==",c)],folderId:c,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(ye(e=>e?this.documentPaths$.pipe(ye(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),_t((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):ce(null))):ce(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?Gr.RESTRICTED:Gr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:Gr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),Gr.PUBLIC}}changeDocumentAccessType(e){return X(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 Gr.PUBLIC:i.features.all.restricted=!1;break;case Gr.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)(K(ct),K(qe),K($n),K(Ve),K(Ft),K(k),K(rl),K(Xc),K(ol),K(tr),K(Oo))},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 Ln,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=c=>{try{return this.userById$.value?.[c]}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(Ge(c=>!!c),ye(()=>this.getUnresolvedUsers$().pipe(Ge(c=>c.length>0),Xr(300),ut(20),ye(c=>{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",c.slice(0,20)))]}}).pipe(ge(m=>m?.data),ln(m=>{if(m&&typeof m=="object"){delete m.undefined,delete m.null;let u=Object.values(m??{});this.setUserByIds(u.map(I=>I.user));let _=c.filter(I=>!u.some(A=>A.user.userId===I));_.length!==c.length&&this.setUnresolvedUsers(_)}})):ce([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}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(m){return X(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:c,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=c||lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:vi.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((be,re)=>{q=setTimeout(()=>{re(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:vi.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:vi.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 _=c||lt();return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:vi.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 X(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 $i(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 m=yield l.get(e);if(m&&typeof m=="object"&&"success"in m&&"statusCode"in m&&typeof m.success=="boolean"&&typeof m.statusCode=="number"){let u=m;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return m}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(c.flat());let d={};return c.forEach(m=>{m.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 X(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let m=0;m<e.length;m+=30)l.push(e.slice(m,m+30));let c=l.map((m,u)=>X(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",m)],skipUserCheck:i}}))||[]}catch(_){return this.loggingService.catch(`Error in batch ${u+1}:`,_),[]}}));return yield Promise.all(c)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return X(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 c=[];for(let M=0;M<i.length;M+=30)c.push(i.slice(M,M+30));let d=[],m=0,u=(M,B)=>X(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 ${m+1}:`,q),[]}});for(let M of l)for(let B of c)d.push(u(M,B)),m++;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(_t(Kt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),ce({})}}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 X(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(re=>!!re))];if(l.length===0)return{};let c={},d=[];if(l.forEach(re=>{let _e=this.userIdByEmailCache[re];_e?c[re]=_e:d.push(re)}),d.length===0)return c;let m=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",_=this.docService.getDocumentPaths()?.folderId||"",I={organizationId:m,documentId:u,folderId:_,emails:d},A=t||lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:m,documentId:u,folderId:_}});let M=a.config?.resolveTimeout||this.resolveTimeout,B,q=new Promise((re,_e)=>{B=setTimeout(()=>{_e(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},be=X(this,null,function*(){try{let re=yield Oi(()=>a.resolveUserIdsByEmail(I),"resolveUserIdsByEmail",ae);return re?.statusCode===200&&re?.data?re.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${re?.statusCode}. Message: ${re?.message||"Unknown error"}`),{})}finally{clearTimeout(B)}});try{let re=yield Promise.race([be,q]);return Object.entries(re).forEach(([_e,Ie])=>{Ie&&(this.userIdByEmailCache[_e]=Ie,c[_e]=Ie,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:Ie,name:_e,email:_e},currentUserId:this.authService.getUser()?.userId??""}).catch(Ce=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",Ce)}))}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:re,emails:d}}),c}catch(re){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",re),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:re,emails:d}}),c}}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)(K(ct),K(qe),K(tr),K(st),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return at.error("Error in isTestingDb:",r),!1}}};var Cm=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=c,this.attachmentResolverService=d,this.coreActionsService=m,this.notificationActionTypeMap={[At.NEWLY_ADDED]:xo.COMMENT_ANNOTATION_ADD,[At.ADDED]:xo.COMMENT_ADD,[At.UPDATED]:xo.COMMENT_UPDATE,[At.DELETED]:xo.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?.suggestion?.resolvedBy?.userId&&t.add(i?.suggestion?.resolvedBy?.userId),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?.suggestion?.resolvedBy?.userId){let t=this.usersService.getUserById(e?.suggestion?.resolvedBy?.userId);t&&(e.suggestion.resolvedBy=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,c)=>c.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(ld(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(ld(`@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};e?.suggestion?.resolvedBy?.userId&&(e.suggestion.resolvedBy={userId:e.suggestion.resolvedBy.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 c=t?.comments?.[l?.commentId];if(c){l.commentHtml=c?.commentHtml,l.commentText=c?.commentText;let d=c?.attachments;i&&d&&l.attachments?.forEach(m=>{let u=m?.attachmentId;d?.[u]&&(m.name=d?.[u]?.name,m.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?!sr(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 Jl;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));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 X(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=lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:vi.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(c=>{if(c?.contact?.email&&!c?.userId){let d=a[c.contact.email];if(d){let m=c.text;if(m){let u=ld(m),_=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(_,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(_,`{{${d}}}`))}c.userId=d,c.contact.userId=d,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),l.to=l.to?.map(c=>{if(c?.email&&!c?.userId){let d=a[c.email];if(d)return delete c?.email,delete c?.visibility,y(h({},c),{userId:d})}return c})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return X(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(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),m;t&&(m=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:oi(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,c?.length>0&&c.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(be=>{ae[be.attachmentId]={attachmentId:be.attachmentId,name:be.name,url:be.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 Mr;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&&(m=_?.comments?.length&&_?.comments?.length>0?xo.COMMENT_ADD:xo.COMMENT_ANNOTATION_ADD),{strippedData:I&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:_,eventType:m}}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(c=>c.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(ld(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 X(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,c=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:to.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0}}),c){let I=JSON.stringify(c);d.push({userId:_,resource:{id:I,type:oa.CONTEXT,source:to.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let m=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.SET_NOTIFICATIONS,uniqueId:m,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:m,methodName:to.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(c){return X(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=WN(this.authService.getFirebaseConfig()?.firebaseOptions),m=qr(this.functions,Kr({url:On.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=wp.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:On.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:el(),deniedForYouUsers:_,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield Es(I,this.authService.getUser()?.userId??"");yield m({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(K(k),K(An),K(qe),K(Oo),K(Ft),K(rl),K(Qc),K(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,c){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=c}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 X(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=WN(this.authService.getFirebaseConfig()?.firebaseOptions),c=qr(this.functions,Kr({url:On.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=wp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),m=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:el()},_=yield Es(u,m);yield c({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?!sr(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:oi(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)(K(k),K(An),K(qe),K(Oo),K(Ft),K(Xc))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tp=(()=>{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 X(this,null,function*(){try{return yield Es(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:oi(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[m,u]of Object.entries(e.recordingEditVersions)){let _=Number(m),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(m=>({attachmentId:m?.attachmentId,name:m?.name,bucketPath:m?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let c;return t===Zl.ADDED?c=xo.RECORDER_ANNOTATION_ADD:t===Zl.UPDATED?c=xo.RECORDER_ANNOTATION_UPDATE:t===Zl.DELETED&&(c=xo.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:c}}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)(K(qe),K(k),K(An),K(ol))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dp=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.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 m(),u({});let A={},M=[...new Set(e.activityIds||[])],B=y(h({},e),{activityIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in ActivityResolverService resolveActivities:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.activityById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.activityById$.next(h(h({},this.activityById$.getValue()),re)),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:yc.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(c?.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:yc.SAVE_ACTIVITY,source:"internal",payload:{error:c,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:yc.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||lt();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:yc.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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},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,a,l,c,d,m,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=c,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=m,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((c,d)=>{if(c!=null&&typeof c=="object")return c[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 X(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 X(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=oi(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?oi(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?oi(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let c=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(c?.strippedData){let d=Object.keys(c.strippedData)[0];d&&(a.entityData=c.strippedData[d])}}if(i){let c=this.reactionUtilsService.stripReactionAnnotationData(l);if(c?.strippedData){let d=Object.keys(c.strippedData)[0];d&&(a.entityData=c.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 Hr.ANNOTATION_ADD:return`${t} added a comment`;case Hr.COMMENT_ADD:return`${t} replied to a comment`;case Hr.COMMENT_UPDATE:return`${t} edited a comment`;case Hr.COMMENT_DELETE:return`${t} deleted a comment`;case Hr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case Hr.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 Hr.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),c=i?.from,d=c&&typeof c=="object"?c?.name:c?String(c):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case Hr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case Hr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case Hr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case Hr.APPROVE:return`${t} approved the comment`;case Hr.ACCEPT:return`${t} accepted a suggestion`;case Hr.REJECT:return`${t} rejected a suggestion`;case Hr.REACTION_ADD:return`${t} reacted to a comment`;case Hr.REACTION_DELETE:return`${t} removed a reaction`;case Hr.SUBSCRIBE:return`${t} subscribed to the thread`;case Hr.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 h3.RECORDING_ADD:return`${t} added a recording`;case h3.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 f3.REACTION_ADD:return`${t} added a reaction`;case f3.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 X(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 c=t.comments?.[String(l)];c&&(c.commentText&&(a.commentText=c.commentText),c.commentHtml&&(a.commentHtml=c.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,c=t,d=i,m=a===At.DELETED&&l?.isAnnotationDelete?Hr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!m)return null;let u=c?.annotationId;if(!u)return null;let _=d?.commentId,I=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:m,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 Hr.ANNOTATION_ADD;case At.ADDED:return Hr.COMMENT_ADD;case At.UPDATED:return Hr.COMMENT_UPDATE;case At.DELETED:return Hr.COMMENT_DELETE;case At.STATUS_CHANGED:return Hr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return Hr.PRIORITY_CHANGE;case At.ASSIGNED:return Hr.ASSIGN;case At.ACCESS_MODE_CHANGED:return Hr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return Hr.CUSTOM_LIST_CHANGE;case At.APPROVED:return Hr.APPROVE;case At.ACCEPTED:return Hr.ACCEPT;case At.REJECTED:return Hr.REJECT;case At.REACTION_ADDED:return Hr.REACTION_ADD;case At.REACTION_DELETED:return Hr.REACTION_DELETE;case At.SUBSCRIBED:return Hr.SUBSCRIBE;case At.UNSUBSCRIBED:return Hr.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 Zl.ADDED:return h3.RECORDING_ADD;case Zl.DELETED:return h3.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 f3.REACTION_ADD;case"delete":return f3.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)(K(k),K(An),K(Cm),K(NL),K(Tp),K(rl),K(Xc),K(ol),K(Dp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bm=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=Rr(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=Rr(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 fbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cbe=(()=>{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)(K(k),K(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}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)(K(k),K(An))},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}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)(K(k),K(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 X(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=lt(),a=ys.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:vi.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 c of e)c?.from?.userId&&l[c.from.userId]&&(c.from=l[c.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)(K(tr),K(k),K(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 X(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=lt(),a=ys.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:vi.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)(K(tr),K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _m=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let Ie=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.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 m(),u({});let A={},M=this.notificationById$.getValue()||{},B=[...new Set(e.notificationIds||[])],q=[],ae=[],be=[];for(let Ie of B)M[Ie]||(this.inFlightRequests.has(Ie)?(q.push(this.inFlightRequests.get(Ie)),ae.push(Ie)):be.push(Ie));let re=y(h({},e),{notificationIds:be});X(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),be.length>0){let Ie=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:re}});let Ce,Te=new Promise(Me=>{Ce=Me});for(let Me of be)this.inFlightRequests.set(Me,Te.then(je=>je?.[Me]));let Oe=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,re,!0):I?.get?.(re)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Me=>c?{}:(m(),Me&&Me.statusCode!==200?(this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Me,request:re}}),this.loggingService.catch(Me?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Me?.data)).catch(Me=>{throw m(),Me});try{A=(yield Oe)||{},Ce(A);for(let je of be)this.inFlightRequests.delete(je);this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:be});let Me={};Object.entries(A).forEach(([je,We])=>{let ze=this.notificationById$.value?.[je];ze?ze&&JSON.stringify(ze)!==JSON.stringify(We)&&(Me[je]=We):Me[je]=We}),Object.keys(Me).length>0&&this.notificationById$.next(h(h({},this.notificationById$.getValue()),Me)),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Me,request:re}}),u(Me)}catch(Me){Ce({});for(let We of be)this.inFlightRequests.delete(We);let je=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:je,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Me,request:re}}),c||_(Me),u(A)}}else m(),u({})}catch(Ie){m();let Ce=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ie,request:re}}),_(Ie)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return X(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||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:yl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let c=this.notificationById$.getValue(),d=h({},c);delete d?.[e],this.notificationById$._value=d;let m={notificationId:e,organizationId:t},u=yield Oi(()=>a?.config?.deleteConfig?.url?$i(a.config.deleteConfig.url,a.config.deleteConfig.headers,m,!1):a?.delete?.(m)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),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:yl.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:yl.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||lt();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:yl.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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},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,c,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=c,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 c of l)t.add(c)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),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 X(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 Es(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)(K(Cm),K(Tp),K(k),K(An),K(qe),K(rl),K(_m))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ibe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ebe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vd=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,B,q,ae,be,re,_e,Ie,Ce,Te,Oe,Me){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=c,this.cursorUtilsService=d,this.huddleUtilsService=m,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=be,this.usersService=re,this.docService=_e,this.commentAnnotationsResolverService=Ie,this.reactionAnnotationsResolverService=Ce,this.recorderAnnotationsResolverService=Te,this.notificationResolverService=Oe,this.activityResolverService=Me}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:c,folderId:d}=t;c||(c=i?.organizationId);let m=new LL({apiKey:a,documentId:l?`${l}`:"",organizationId:c?`${c}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&m?.userConfig?`${m?.userConfig}/${t?.userId}${t?.documentId?`/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return m?.permissionsUsers?`${m?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&m?.comment?`${m?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&m?.comment?`${m?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&m?.multiThread?`${m?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&m?.multiThread?`${m?.multiThread}`:void 0;case"crdt":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return m?.lastNotificationTimestamp?`${m?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&m?.lastNotificationTimestamp?`${m?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&m?.activities?`${m?.activities}/${t?.id}`:void 0;case"allActivities":return m?.activities?`${m?.activities}`:void 0;case"allLastActivityTimestamp":return m?.lastActivityTimestamp?`${m?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&m?.lastActivityTimestamp?`${m?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&m?.area?`${m?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&m?.area?`${m?.area}`:void 0;case"allDocuments":return m?.document?`${m?.document}`:void 0;case"allLocations":return m?.location?`${m?.location}`:void 0;case"allFolders":return m?.folder?`${m?.folder}`:void 0;case"folder":return m?.folder&&t.folderId?`${m?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&m?.documentUsers?`${m?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&m?.reaction?`${m?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&m?.reaction?`${m?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&m?.recorder?`${m?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&m?.document?`${m?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return m?.organization?`${m?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&m?.document?`${m?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&m?.folder?`${m?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&m?.location&&t?.id?`${m?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&m?.documentUsers?`${m?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return m?.users?`${m?.users}`:void 0;case"allFolderUsers":return m?.users?`${m?.users}`:void 0;case"allOrganizationGroups":return m?.organizationGroups?`${m?.organizationGroups}`:void 0;case"allOrganizationUsers":return m?.users?`${m?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&m?.notificationViews?`${m?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&m?.documentViews?`${m?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&m?.documentViews?`${m?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&m?.locationViews?`${m?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&m?.locationViews?`${m?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&m?.docNotification?`${m?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&m?.docNotification?`${m?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&m?.notificationUsers?`${m?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&m?.notificationUsers?`${m?.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:c,organizationId:d}=t;d||(d=i?.organizationId);let m=new bm({apiKey:a,documentId:c?`${c}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&m?.userConfig?`${m?.userConfig}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&m?.comment?`${m?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&m?.globalContacts?`${m?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&m?.globalContacts?`${m?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&m?.groupContacts?`${m?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&m?.groupContacts?`${m?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&m?.logins?`${m?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&m?.logins?`${m?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&m?.logins?`${m?.logins}${t?.userId}`:void 0;case"customerMetadata":return m?.customerMetadata?`${m?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&m?.arrow?`${m?.arrow}`:void 0;case"arrow":return t?.documentId&&m?.arrow&&t.id?`${m?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&m?.cursor?`${m?.cursor}`:void 0;case"cursor":return t?.documentId&&m?.cursor&&t.id?`${m?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&m?.flock&&t.id?`${m?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&m?.flock&&t.id?`${m?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&m?.huddle?`${m?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&m?.huddle?`${m?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&m?.huddle?`${m?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&m?.huddle?`${m?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&m?.liveState?`${m?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&m?.liveState?`${m?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&m?.liveState&&t?.id?`${m?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&m?.liveStateSingleEditorMode?`${m?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&m?.liveState?`${m?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&m?.liveState?`${m?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&m?.liveState&&t?.id?`${m?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&m?.presence&&t?.userId?`${m?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&m?.presence?`${m?.presence}`:void 0;case"workspaceIam":return m?.workspaceIam?`${m?.workspaceIam}`:void 0;case"selection":return t?.documentId&&m?.selection&&t?.userId?`${m?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&m?.selection?`${m?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&m?.syncVideoPlayer?`${m?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&m?.tag?`${m?.tag}`:void 0;case"tag":return t?.documentId&&m?.tag&&t?.id?`${m?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&m?.userContactUs?`${m?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&m?.userFeedback?`${m?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&m?.userReportBugs?`${m?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&m?.comment?`${m?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&m?.multiThread?`${m?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&m?.crdt?`${m?.crdt}`:void 0;case"crdtData":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&m?.crdt&&t?.id&&t?.versionId?`${m?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&m?.crdt&&t?.id&&t?.messageId?`${m?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&m?.multiThread?`${m?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&m?.organizationNotificationsLastNotificationTimestamp?`${m?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&m?.organizationNotificationsLastNotificationTimestamp?`${m?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&m?.documentIam?`${m?.documentIam}`:void 0;case"allDocuments":return!l&&m?.docs&&t?.documentId?`${m?.docs}/${t?.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&m?.area?`${m?.area}`:void 0;case"area":return!l&&t?.id&&m?.area?`${m?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&m?.folder?`${m?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&m?.documentIam?`${m?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&m?.documentIam?`${m?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&m?.documentIam?`${m?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&m?.organizationGroups?`${m?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&m?.organizationIam?`${m?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&m?.reaction?`${m?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&m?.reaction?`${m?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&m?.recorder?`${m?.recorder}`:void 0;case"organizationMetadata":return!l&&m?.organizationMetadata?`${m?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&m?.heartbeat?`${m?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return m?.heartbeat?`${m?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&m?.heartbeatByDocument?`${m?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return m?.heartbeatByDocument?`${m?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&m?.documentIam?`${m?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&m?.metadata?`${m?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&m?.views?`${m?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&m?.views?`${m?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&m?.views?`${m?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&m?.views?`${m?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&m?.views?`${m?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&m?.views?`${m?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&m?.views?`${m?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&m?.views?`${m?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&m?.views?`${m?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&m?.organizationNotificationsWithDocumentId?`${m?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&m?.organizationNotificationsWithDocumentId?`${m?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&m?.organizationNotificationsUsers?`${m?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&m?.organizationNotificationsUsers?`${m?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(i){return X(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=lt(),l=o1.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.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=lt(),l=i1.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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=lt(),l=a1.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.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 X(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:c=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:m=!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=lt(),M=ys.GET_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.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=lt(),M=LK.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:yl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:c}}),c?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=lt(),M=o1.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ti.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=lt(),q=UK.GET_ACTIVITIES;this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:yc.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=lt(),q=i1.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:m}}),m?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=lt(),q=a1.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),ce(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,c])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,c])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(c,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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),ce(e)}}handleDataStripping(l){return X(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(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{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 c=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,c);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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(l){return X(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});i.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}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 X(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 X(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:c=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:c})):i[A]?.subject?.next({data:y(h({},M?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",m),null}})}handleCommentEncryption(c){return X(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 X(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)(K(gS),K(fbe),K(Cbe),K(Cm),K(bbe),K(tr),K(_be),K(UL),K(VL),K(k),K(kbe),K(jL),K(Ibe),K(NL),K(Tp),K(Ebe),K(wbe),K(An),K(st),K(rl),K(Xc),K(ol),K(_m),K(Dp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tbe=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{gn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Ge(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,c])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||On?.firebaseLogLevel||"silent";bX(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=wp.getFirestoreProdDbName(l,a.firebaseOptions),m=this.configService.getProxyConfig();if(m?.v2DbHost){let u={host:m.v2DbHost,ssl:!0};m.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,c&&(u.localCache=tQ({tabManager:nQ()}));try{this.firestore$.next(wL(ql(),u,d))}catch(_){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",_),this.firestore$.next(lS(d))}}else if(c)try{let u=ql(),_=wL(u,{localCache:tQ({tabManager:nQ()})},d);this.firestore$.next(_)}catch{this.firestore$.next(lS(d))}else this.firestore$.next(lS(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||lS("DocumentIdDb");if(e){let t=wO(e,"generateDocumentId");return sS(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(K(Ft),K(qe),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var yn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,B){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=c,this.databaseService=d,this.configService=m,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=Cg(ae,be=>{let re=be.val();this.offset=re})}})),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 X(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return bc(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){gn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ge(([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,c){return X(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>X(this,[u],function*({db:d,firestore:m}){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")&&m&&_&&(M=sS(m,`${_}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:_}),c&&c({firestoreAvailable:!!m})}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 X(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,c),this.performDatabaseOperation(e,i,m=>X(this,null,function*(){if(m.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:m.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Qf(m.dbRef,()=>JSON.parse(JSON.stringify(u))):yield e0(m.dbRef,JSON.parse(JSON.stringify(u)))}try{if(m.firestoreRef&&m.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:m.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:c?.actionType,commentId:c?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ti.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:c?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:c?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:m.firestorePath??"",extraData:c,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.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:m.firestorePath??""}))}else if(e==="recorder"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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 aQ(this.firestore,q=>X(this,null,function*(){q.set(m.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield lQ(m.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(m){this.loggingService.catch(`Error in setData for ${e}`,m)}})}updateData(d){return X(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,c),this.performDatabaseOperation(e,i,m=>X(this,null,function*(){if(m.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:m.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Qf(m.dbRef,_=>{let I;return i?.rtdbTransactionCallback?I=i.rtdbTransactionCallback(_,u):I=this.commonDbUtilsService.rtdbDefaultTransactionCallback(_,u),JSON.parse(JSON.stringify(I))}):yield x8(m.dbRef,JSON.parse(JSON.stringify(u)))}try{if(m.firestoreRef&&m.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:m.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:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ti.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:c?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:c?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:m.firestorePath??"",extraData:c,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.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:m.firestorePath??""}))}else if(e==="recorder"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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 aQ(this.firestore,q=>X(this,null,function*(){q.set(m.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield lQ(m.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(m){this.loggingService.catch(`Error in updateData for ${e}`,m)}})}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(c){return X(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=>X(this,null,function*(){d.dbRef&&(yield k8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ti.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield OL(d.firestoreRef))}else if(e==="userNotification"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:yl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),m=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(m?.isSuccess||m===null)&&(yield OL(d.firestoreRef))}else yield OL(d.firestoreRef)}catch(m){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,m)}}),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=lt()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),lt()||"noDocumentId"}}queryData(i){return X(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 X(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=wO(this.firestore,i);t?.useCollectionGroup&&(a=rQ(this.firestore,i));let l=t?.firestoreQuery??[],c=iQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield XCe(c).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,m),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 ebe(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let m=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:m})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),m}}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 X(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??[],c=Yq(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield zq(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let m=d.val();return m?t?.skipObjectValues?m:Object.values(m??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return X(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 c=yield QCe(sS(this.firestore,l)).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,m),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:m})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=c.data();return t?.field?d?.[t.field]??{}:d??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}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 c=yield zq(Ur(this.db,l)).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,m),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:m})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=c.val();return t?.field?d?.[t.field]??{}:d??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return gn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Ge(l=>!!l))]).pipe(Ge(([l,c])=>l?i&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ye(([l,c])=>{try{if(i&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,c).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.firestoreSubscriptions[a]=u}return new Vt(m=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>m.next(_),_=>m.error(_),()=>m.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 Vt(m=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>m.next(_),_=>m.error(_),()=>m.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 ce({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),ce({})}}),qh(()=>{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 Vt(c=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,c,t):this.setupDocumentListener(i,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(ye(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ye(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):ce(c)),ye(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):ce(c)),ye(c=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:e}):ce(c)),_t(Kt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),ce({}))}setupCollectionListener(e,t,i,a,l){let c=`${i}-${JSON.stringify(l)}`,d=wO(e,t);if(l?.useCollectionGroup&&(d=rQ(e,t)),l?.useQuery&&l?.firestoreQuery){let _=l?.firestoreQuery??[];d=iQ(d,..._)}let m=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),oQ(d,_=>{try{let I=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),A=null,M=!1;_?.docChanges()?.length?_.docChanges().forEach(B=>{["allComments","allReactions","allRecorders"].includes(i)&&!m&&B.type!=="removed"&&u.push(B.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:B,cache:this.observablesCache[c]?.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})),m=!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 c=sS(e,t);return oQ(c,d=>{try{let m=d.data()||{};l?.field&&(m=m?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:m,subscriber:a,operation:null})}catch(m){this.handleListenerError(m,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}`),ce({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];l=Yq(l,...c)}return this.objectValFromChildEvents(l,e).pipe(Jn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),ce({}))),ge(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((m,[u,_])=>(m[u]=this.commonDbUtilsService.addMetadata(_,t),m),{}):this.commonDbUtilsService.addMetadata(c,t))),ye(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ye(c=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}pushData(a){return X(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=>X(this,null,function*(){if(l.dbRef){let c=y8(l.dbRef);yield e0(c,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 Vt(a=>{let l=null,c=!1,d=({db:m})=>{if(!m||c||!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(m,u),A=!1,M=ae=>{try{let be=ae.val();if(A){if(i!=null&&be?.timestamp!=null&&be.timestamp<=i)return;a.next(be)}}catch(be){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,be)}},B=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(be){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,be)}};qq(I,M,B);let q=Cg(I,()=>{A=!0},B,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),OD(I,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{c=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),ce(null)}}objectValFromChildEvents(e,t){return new Vt(i=>{let a={},l=!1,c=null,d=B=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,B),i.error(B)}catch{}},m=B=>{try{if(!sr(B,c)){let q=JSON.parse(JSON.stringify(B));c=q,i.next(q)}}catch{}},u=B=>{try{B.key&&(a[B.key]=B.val(),l&&m(h({},a)))}catch{}},_=B=>{try{B.key&&(a[B.key]=B.val(),l&&m(h({},a)))}catch{}},I=B=>{try{B.key&&(delete a[B.key],l&&m(h({},a)))}catch{}},A=B=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=q,i.next(q),l=!0}}catch{}};qq(e,u,d),_me(e,_,d),Sme(e,I,d);let M=Cg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),OD(e,"child_added",u),OD(e,"child_changed",_),OD(e,"child_removed",I)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(K(gS),K(qe),K(vd),K(tr),K(k),K(Tbe),K($n),K(Ft),K(st),K(An),K(rl),K(Xc),K(ol),K(_m))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Sm=(()=>{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 c=e;for(let d of a){let m=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;c=c.replace(new RegExp(`\\bid="${m}"`,"g"),`id="${u}"`),c=c.replace(new RegExp(`url\\(#${m}\\)`,"g"),`url(#${u})`),c=c.replace(new RegExp(`href="#${m}"`,"g"),`href="#${u}"`)}return c}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
+ `+pl),Sv&&AL([We,ze,jr],os=>{pl=OO(pl,os," ")}),re&&Ih?re.createHTML(pl):pl},o.setConfig=function(){let kn=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};KC(kn),zC=!0},o.clearConfig=function(){_d=null,zC=!1},o.isValidAttribute=function(kn,Ke,Ut){_d||KC({});let sn=qi(kn),Go=qi(Ke);return ZC(sn,Go,Ut)},o.addHook=function(kn,Ke){typeof Ke=="function"&&DO(je[kn],Ke)},o.removeHook=function(kn,Ke){if(Ke!==void 0){let Ut=Hze(je[kn],Ke);return Ut===-1?void 0:zze(je[kn],Ut,1)[0]}return obe(je[kn])},o.removeHooks=function(kn){je[kn]=[]},o.removeAllHooks=function(){je=dbe()},o}var dS=ube();var pbe={ADD_TAGS:["velt-skeleton-loader"],ADD_ATTR:["border-radius","target"]},Ve=(()=>{let o=class o{constructor(e,t,i,a){this.analyticsService=e,this.rendererFactory2=t,this.loggingService=i,this.sanitizer=a,this.smoothScrollShieldHandler=null,this.smoothScrollShieldLoadListener=null,this.isVideoEditorHandlingDelete=!1,this.pageScrollHeight=0,this.enableRectSelectionSubject$=new Se(!1),this.enableRectSelection$=this.enableRectSelectionSubject$.asObservable(),this.scrollableElementsIds$=new Se([]),this.mousedown=!1,this.windowMouseDown$=new it,this.windowPointerMove$=new Se(null),this.windowPointerUp$=new Se(null),this.documentSelectionChange$=new Se(null),this.windowClick$=new Se(null),this.windowScroll$=new Se(null),this.windowResize$=new Se(null),this.windowKeyupBackspace$=new Se(null),this.windowKeyupDelete$=new Se(null),this.windowKeyupEsc$=new Se(null),this.windowPopState$=new Se(null),this.documentClick$=new Se(null),this.documentClickSubject$=new it,this.documentFocus$=new Se(null),this.windowKeydownShift$=new Se(null),this.windowKeyupShift$=new Se(null),this.mutation$=new Se(null),this.childListMutation$=new Se(null),this.networkStatus$=new Se(!1),this.xpathCache=new Map,this.xpathCacheId=new Map,this.selectedAnnotationsMap$=new Se({}),this.selectedAnnotationsLocationMap$=new Se({}),this.recordingInProgress$=new Se({}),this.deleteAnnotations$=new Se([]),this.pinHighlighterClass$=new Se(null),this.dialogOpenedInSidebar$=new Se(!1),this.textHighlighterClass$=new Se(null),this.commentPinHighlighter$=new Se(!1),this.deviceInfo$=new Se(new ur),this.customCss$=new Se(null),this.mutationObserver=null,this.animationFilterEnabled=!1,this.animationLibraryDetected=null,this.staticAnimationCache=new WeakMap,this.ANIMATION_LIBRARY_SELECTOR=["[data-gsap]",".gsap-marker-start",".gsap-marker-end","[data-gsap-id]",".swiper-slide",".swiper-wrapper",".swiper-pagination",".swiper-pagination-bullet","[data-aos]"].join(", "),this.previousMousePosition={pageX:0,pageY:0,clientX:0,clientY:0},this.currentMousePosition={pageX:0,pageY:0,clientX:0,clientY:0,element:{xpath:"",topPercentage:0,leftPercentage:0}},this.nodeMap={},this.unlistenElementScroll={},this.tabId=null,this.dynamicIdPatterns=[/^yui_[a-z0-9_]+$/i],this.excludeClassList=["show-pin-cursor"],this.filterSnippylyNodes=l=>{try{let c=[];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 m=!1;d.childNodes.forEach(u=>{Co(u)&&(m=!0)}),m||c.push(d)}else c.push(d)}else c.push(d)}),c}catch(c){return this.loggingService.catch("Error in DomService filterSnippylyNodes: ",c),[]}},this.loggingService.log("%c[WB] Creating CLASS: DomService","color: blue;");try{this.analyticsService.setDomService(this),this.renderer=this.rendererFactory2.createRenderer(null,null);let l=this.calculateScreenSize();this.currentScreenSize$=new Se(l),this.currentMousePosition$=new Se(this.currentMousePosition),this.detectNetworkStatusChange(),this.getScrollableElementsIds$().pipe(Pr(),ln(([c,d])=>{try{let m=d.filter(_=>!c.includes(_)),u=c.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]()}),m.length&&m.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(m){this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",m)}})).subscribe(()=>{},c=>{this.loggingService.catch("Error in DomService getScrollableElementsIds subscription: ",c)}),this.getSelectedAnnotationsMap$().subscribe(c=>{Object.keys(c||{})?.length?ehe("snippylyUserScalableNo","viewport","width=device-width, user-scalable=no"):the("snippylyUserScalableNo")},c=>{this.loggingService.catch("Error in DomService getSelectedAnnotationsMap$ subscription: ",c)})}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 c=e.getAttribute(l);c&&c.length<=256&&(t[l]=c)}),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,m)=>{let u=l.findIndex(I=>d.startsWith(I)),_=l.findIndex(I=>m.startsWith(I));return(u===-1?99:u)-(_===-1?99:_)}).slice(0,4).forEach(d=>{let m=CSS.escape(t[d]);a.push(`[${d}="${m}"]`)}),a.join("")}catch{return}}getVisibleText(e,t=400){try{let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a="",l,c=0;for(;(l=i.nextNode())&&a.length<t;){let d=(l.textContent||"").replace(/\s+/g," ").trim();if(d&&(a+=(a?" ":"")+d),c++,c>100)break}return a.slice(0,t)}catch{return""}}hashText(e){try{return $pe(e)}catch{return}}generateRobustXPath(e,t){try{let i=t?.maxDepth||10,a=t?.useAbsolutePath||!1,l=[],c=e,d=0;for(;c&&c!==document.documentElement&&d<i;){let I=this.buildRobustXPathSegment(c);if(I&&(l.unshift(I),this.isStrongAnchorSegment(I)))break;c=c.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 c=e.getAttribute("role");if(c)return`${t}[@role=${this.escapeXPathValue(c)}]`;let d=e.getAttribute("aria-label");if(d&&d.length<50)return`${t}[@aria-label=${this.escapeXPathValue(d)}]`;let m=e.getAttribute("name");if(m)return`${t}[@name=${this.escapeXPathValue(m)}]`;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(c=>`'${c}'`).join(`,"'",`)})`}catch{return t?`'${e}'`:e}}}getElementFromRobustXPath(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}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&&Yr(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,c=this.getStableAttributes(i),d=this.buildStableElementSelector(i,c),m=this.getVisibleText(i),u=this.hashText(m||""),_=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 c=t[0].score,d=t.filter(u=>u.score===c);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 m=t[0];return{element:m.el,matchedBy:m.by,score:m.score,scoreBreakdown:m.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.setupSmoothScrollShield()):(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(),this.teardownSmoothScrollShield())})).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(c=>{let d=c;if(typeof d.getAttribute=="function"){let m=d.getAttribute(N.ATTRIBUTES.VELT_ELEMENT_CACHE_ID);if(m!==null&&m!==""){let u=this.xpathCacheId.get(m);u!==void 0&&(this.xpathCacheId.delete(m),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(c=>{a.target?.closest(c)&&(l=!1)}),l}),i=i.filter(a=>a.target&&Yr(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"),m=i.includes("will-change")&&i.includes("transform"),u=i.includes("transform-style")&&i.includes("preserve-3d");if(d&&(m||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,c=e.className||"";return typeof c=="string"&&(c.includes("slider")&&(c.includes("bullet")||c.includes("pagination"))&&(l=!0),c.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{No(kr(window,"offline").pipe(ge(()=>!1)),kr(window,"online").pipe(ge(()=>!0)),new Vt(e=>{e.next(navigator.onLine),e.complete()})).subscribe(e=>{this.networkStatus$.next(e)})}catch(e){this.loggingService.catch("Error in DomService detectNetworkStatusChange: ",e)}}onWindowResize(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowResize","color: green;");try{this.unsubscribeFromWindowResize(),this.unlistenWindowResize=this.renderer.listen("window","resize",e=>{this.windowResize$.next(e);let t=this.calculateScreenSize();this.deviceInfo$.next(new ur),this.currentScreenSize$.next(t)})}catch(e){this.loggingService.catch("Error in DomService onWindowResize: ",e)}}unsubscribeFromWindowResize(){try{this.unlistenWindowResize&&typeof this.unlistenWindowResize=="function"&&(this.unlistenWindowResize(),this.unlistenWindowResize=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowResize: ",e)}}onWindowScroll(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowScroll","color: green;");try{this.unsubscribeFromWindowScroll(),this.unlistenWindowScroll=this.renderer.listen("window","scroll",e=>{this.windowScroll$.next(e);let t=this.calculateScreenSize();this.currentScreenSize$.next(t)})}catch(e){this.loggingService.catch("Error in DomService onWindowScroll: ",e)}}unsubscribeFromWindowScroll(){try{this.unlistenWindowScroll&&typeof this.unlistenWindowScroll=="function"&&(this.unlistenWindowScroll(),this.unlistenWindowScroll=null)}catch(e){this.loggingService.catch("Error in DomService unsubscribeFromWindowScroll: ",e)}}setupSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: setupSmoothScrollShield","color: green;");try{if(typeof window>"u"||typeof document>"u"||this.smoothScrollShieldHandler)return;if(this.isSmoothScrollLibPresent()){this.attachSmoothScrollShield();return}if(document.readyState!=="complete"&&!this.smoothScrollShieldLoadListener){let e=()=>{this.smoothScrollShieldLoadListener=null;try{if(this.smoothScrollShieldHandler)return;this.isSmoothScrollLibPresent()&&this.attachSmoothScrollShield()}catch(t){this.loggingService.catch("Error in DomService smooth-scroll shield load re-check: ",t)}};window.addEventListener("load",e,{once:!0}),this.smoothScrollShieldLoadListener=()=>window.removeEventListener("load",e)}}catch(e){this.loggingService.catch("Error in DomService setupSmoothScrollShield: ",e)}}isSmoothScrollLibPresent(){try{if(typeof window>"u"||typeof document>"u")return!1;if(window.ET_SmoothScroll)return!0;let t=document.body;return!!(t&&t.classList&&t.classList.contains("et_smooth_scroll"))}catch(e){return this.loggingService.catch("Error in DomService isSmoothScrollLibPresent: ",e),!1}}attachSmoothScrollShield(){if(this.smoothScrollShieldHandler)return;let e=/^(VELT-|SUPERFLOW-|SNIPPYLY-)/,t=a=>{try{let l=typeof a.composedPath=="function"?a.composedPath():[];for(let c=0;c<l.length;c++){let d=l[c];if(!(!d||d.nodeType!==1)&&d.tagName&&e.test(d.tagName)){a.stopImmediatePropagation();return}}}catch(l){this.loggingService.catch("Error in DomService smoothScrollShield handler: ",l)}};this.smoothScrollShieldHandler=t;let i={capture:!0,passive:!0};window.addEventListener("wheel",t,i),window.addEventListener("mousewheel",t,i),window.addEventListener("touchmove",t,i),this.unlistenWindowWheelShield=()=>window.removeEventListener("wheel",t,i),this.unlistenWindowMouseWheelShield=()=>window.removeEventListener("mousewheel",t,i),this.unlistenWindowTouchMoveShield=()=>window.removeEventListener("touchmove",t,i)}teardownSmoothScrollShield(){this.loggingService.log("%c[WB] Calling FUNCTION: teardownSmoothScrollShield","color: green;");try{try{this.smoothScrollShieldLoadListener&&typeof this.smoothScrollShieldLoadListener=="function"&&(this.smoothScrollShieldLoadListener(),this.smoothScrollShieldLoadListener=null)}catch(e){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (load): ",e)}try{this.unlistenWindowWheelShield&&typeof this.unlistenWindowWheelShield=="function"&&(this.unlistenWindowWheelShield(),this.unlistenWindowWheelShield=null)}catch(e){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (wheel): ",e)}try{this.unlistenWindowMouseWheelShield&&typeof this.unlistenWindowMouseWheelShield=="function"&&(this.unlistenWindowMouseWheelShield(),this.unlistenWindowMouseWheelShield=null)}catch(e){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (mousewheel): ",e)}try{this.unlistenWindowTouchMoveShield&&typeof this.unlistenWindowTouchMoveShield=="function"&&(this.unlistenWindowTouchMoveShield(),this.unlistenWindowTouchMoveShield=null)}catch(e){this.loggingService.catch("Error in DomService teardownSmoothScrollShield (touchmove): ",e)}this.smoothScrollShieldHandler=null}catch(e){this.loggingService.catch("Error in DomService teardownSmoothScrollShield: ",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 kr(window,"keydown")}catch(e){return this.loggingService.catch("Error in DomService onWindowKeydown$: ",e),Bs}}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,c=e.clientY-a.y,d=l*100/(a.width||1),m=c*100/(a.height||1);this.currentMousePosition.element={xpath:t,topPercentage:m,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,c=!0,d){try{let m=e,u=m?.touches?.length?m.touches[0]?.clientX:m?.clientX,_=m?.touches?.length?m.touches[0]?.clientY:m?.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,be=q*100/(B.width||1),re=ae*100/(B.height||1),_e={xpath:A,fXpath:M,leftPercentage:be,topPercentage:re};if(a){let Ie=this.getXPath(I,!0,!0);_e.cfXpath=Ie}if(c){let Ie=this.generateAnchorRecord(I);Ie&&(_e.anchor=Ie)}return _e}else return null}catch(m){return this.loggingService.catch("Error in DomService getTargetElementForCommentPinAnnotation: ",m),null}}getBackgroundElement(e,t,i=!0,a=!1){try{let l=document.elementsFromPoint(e,t),c=[];l.forEach(m=>{Co(m)?c=[]:Yr(m)&&c.push(m)}),a&&(c=c.filter(m=>this.isElementVisibleOnScreen(m)));let d=0;return i||c?.forEach((m,u)=>{m.tagName.toLowerCase()==="svg"&&(d=u)}),c[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)&&Yr(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"),c=a?{defaultCursorValue:a,defaultCursorPriority:l}:"";e.setAttribute(N.ATTRIBUTES.DEFAULT_CURSOR,c?JSON.stringify(c):""),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 c=l.split("/"),d=!1;c.forEach((m,u)=>{m.includes("svg")&&(d=!0),d&&(c[u]="svg:"+m)}),l=c.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 c=e.className?.split(" ")?.filter(d=>!d?.includes("snippyly")&&!d?.includes("velt")&&!["show-pin-cursor"].includes(d))[0];if(c){let d=this.calculateXPath(e.parentNode,t,i,a)+"/"+e.tagName.toLowerCase(),m=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]===c:!1);if(m.length>1){let u=m.indexOf(e)+1;d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')][${u}]`}else d+=`[contains(concat(' ', normalize-space(@class), ' '), ' ${c} ')]`;return d}}let l=[].filter.call(e.parentNode?.children?e.parentNode?.children:[],function(c){return c.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=lt();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 S3;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 S3}}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),m;for(;m=d.nextNode();)m?.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),c=Object.keys(this.getRecordingInProgress()||{});l=[...l,...c];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 m={};Object.keys(d).forEach(u=>{if(l.includes(u)&&(m[u]=d[u]),t)switch(t){case"comment":["comment","videoPin"].includes(d[u]?.type)||(m[u]=d[u]);break;default:d[u]?.type!==t&&(m[u]=d[u]);break}}),Object.keys(m).forEach(u=>{let _=m[u]?.multiThreadAnnotationId;_&&!m[_]&&(m[_]={annotationId:_,type:"multiThread"})}),JSON.stringify(this.selectedAnnotationsMap$.value)!==JSON.stringify(m)&&this.selectedAnnotationsMap$.next(m),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 c=l.shadowRoot.querySelector(`[${N.ATTRIBUTES.VELT_ANNOTATION_DRAFT}]`);c&&e.push(c)}else{let c=l.querySelector(`${N.TAGS.VELT_SHADOW_DOM_INTERNAL}`);if(c?.shadowRoot){let d=c.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 c=JSON.parse(JSON.stringify(this.selectedAnnotationsMap$.value||{})),d=JSON.parse(JSON.stringify(this.selectedAnnotationsLocationMap$.value||{}));c[e.annotationId]&&!a?delete c[e.annotationId]:((!this.windowKeydownShift$.value||a)&&(c={}),c[e.annotationId]=e,d[e.annotationId]=t,l=e?.multiThreadAnnotationId||l,l&&(c[l]={annotationId:l,type:"multiThread"},d[l]=t)),this.selectedAnnotationsMap$.next(c),Object.keys(d).forEach(m=>{c[m]||delete d[m]}),this.selectedAnnotationsLocationMap$.next(d)}catch(c){this.loggingService.catch("Error in DomService toggleAnnotationSelection: ",c)}}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),ce([])}}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),ce([])}}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 c=window.getComputedStyle(a);if(a.tagName.toLowerCase()==="svg"||a instanceof SVGElement){let d=a.parentElement;if(d){let m=d.getBoundingClientRect(),u=a.getBoundingClientRect();i.offsetLeft+=u.left-m.left,i.offsetTop+=u.top-m.top}}else c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 c=window.getComputedStyle(a);c.position==="static"?c.transformStyle!="preserve-3d"&&c.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 Vt(e=>{let t=kr(document,"mousedown").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),i=kr(document,"mousemove").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),a=kr(document,"mouseup").pipe(ge(d=>({type:d.type,x:d.clientX+window.scrollX,y:d.clientY+window.scrollY,event:d}))),c=t.pipe(ye(d=>i.pipe(Pr(),ge(([m,u])=>({startPoint:d,prevPoint:m,curPoint:u})),zo(a)))).subscribe(e);return()=>c.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),c=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=`${c}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 c=this.getTextXPath(i);this.isXpathWithId(c)&&(a=i)}let l=this.getAdditionalLocationContainer(i);if(l&&(a=l),t.commonAncestorContainer=this.getTextXPath(a),t.commonAncestorContainer){let c=this.getElementFromXPath(t.commonAncestorContainer);if(c){t.commonAncestorContainerFXpath=this.getXPath(c,!0),t.commonAncestorContainerCFXpath=this.getXPath(c,!0,!0);let d=this.generateAnchorRecord(c);d&&(t.commonAncestorContainerAnchor=d)}}return t.text=e.toString(),t.occurrence=p0(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 c=document.getElementById(e[l]);c&&a.push(c)}if(t?.length)for(let l=0;l<t.length;l++){let c=document.getElementsByClassName(t[l]);for(let d=0;d<c.length;d++){let m=c[d];m&&m instanceof HTMLElement&&a.push(m)}}if(i?.length)for(let l=0;l<i.length;l++){let c=document.querySelectorAll(i[l]);for(let d=0;d<c.length;d++){let m=c[d];m&&m instanceof HTMLElement&&a.push(m)}}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),ce(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)}}subscribeInjectCustomCss(e){try{return this.customCss$.subscribe(()=>{this.injectCustomCss(e?.nativeElement)})}catch(t){return this.loggingService.catch("Error in DomService subscribeInjectCustomCss: ",t),new Ln}}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;"),dS.sanitize(e,pbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeHtml: ",t),""}}sanitizeHtmlForPaste(e){try{let t=this.convertStylesToTags(e);return dS.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.convertBlockElementsToBr(t),this.processNodeStyles(t),t.innerHTML}catch(t){return this.loggingService.catch("Error in DomService convertStylesToTags: ",t),e}}convertBlockElementsToBr(e){try{let t=["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","SECTION","ARTICLE","HEADER","FOOTER"],i;for(;(i=e.querySelector(t.join(",")))!==null;){let a=i.parentNode;if(!a)break;for(;i.firstChild;)a.insertBefore(i.firstChild,i);i.nextSibling&&a.insertBefore(document.createElement("br"),i),a.removeChild(i)}}catch(t){this.loggingService.catch("Error in DomService convertBlockElementsToBr: ",t)}}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,c=i,d=l?.fontWeight;if(d==="bold"||d==="700"||d==="800"||d==="900"){let m=a.tagName?.toLowerCase();if(m!=="b"&&m!=="strong"){let u=document.createElement("b");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}if(l?.fontStyle==="italic"){let m=a.tagName?.toLowerCase();if(m!=="i"&&m!=="em"){let u=document.createElement("i");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}if((l?.textDecorationLine?.includes("underline")||l?.textDecoration?.includes("underline"))&&a.tagName?.toLowerCase()!=="u"){let u=document.createElement("u");c.parentNode.insertBefore(u,c),u.appendChild(c),c=u}}}catch(t){this.loggingService.catch("Error in DomService processNodeStyles: ",t)}}sanitizeSvg(e){try{return dS.sanitize(e,pbe)}catch(t){return this.loggingService.catch("Error in DomService sanitizeSvg: ",t),e}}setDeviceInfo(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDeviceInfo","color: green;");let e=new ur;this.deviceInfo$.next(e)}catch(e){this.loggingService.catch("Error in DomService setDeviceInfo: ",e)}}getDeviceInfo$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getDeviceInfo$","color: green;"),this.deviceInfo$.asObservable()}catch(e){return this.loggingService.catch("Error in DomService getDeviceInfo$: ",e),ce(new ur)}}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=lt(),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 ur}}isMobileDevice(){try{return new ur().getDeviceType()===ji.MOBILE}catch(e){return this.loggingService.catch("Error in DomService isMobileDevice: ",e),!1}}isTabletDevice(){try{return new ur().getDeviceType()===ji.TABLET}catch(e){return this.loggingService.catch("Error in DomService isTabletDevice: ",e),!1}}isDesktopDevice(){try{return new ur().getDeviceType()===ji.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(c=>{l.setAttribute(c.name,c.value)});i.firstChild;)l.appendChild(i.firstChild);i.parentNode.replaceChild(l,i)}})}isMonitorDevice(){try{return new ur().getDeviceType()===ji.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)(K(ct),K(xi),K(k),K($d))},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,c,d,m){this.afAuth=e,this.configService=t,this.avatarService=i,this.coreActionsService=a,this.domService=l,this.functions=c,this.analyticsService=d,this.loggingService=m,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(So(this.afAuth.currentUser),Pr(),ye(([u,_])=>this.domService.onNetworkStatusChange$().pipe(Ge(I=>I),ut(1),ge(()=>({previousUser:u,currentUser:_}))))).subscribe(I=>X(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(_t(Kt)).subscribe(u=>{let _=Vo(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 wN),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=>X(this,null,function*(){if(this.autoLoginCalled=!0,a){let l=yield Zv(a,!0).catch(c=>null);if(l){let{user:c}=l?.claims;this.autoLoginRequired&&(c=yield this.updateUserWithColorAndTextColor(c),this.initializeClient(c,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 X(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 XK(()=>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(Ge(a=>a.code==="token_expired"),ut(10)).subscribe(a=>X(this,null,function*(){if(a.code==="token_expired"){let l=this.docService?.getDocumentIds()?.map(I=>({id:I.clientDocumentId}))??[],c=this.docService?.getOptionsFromDocumentPaths()??void 0,d=[],m=this.docService?.getLocation();m&&d.push(m.location);let u=this.docService?.getLocations();u&&Object.values(u).forEach(I=>{d.push(I.location)}),(yield XK(()=>X(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:c,source:"internal"}),yield this.docService?.setLocations({locations:d,source:"internal",options:{appendLocation:!m}}))}}))),i}catch(t){return this.loggingService.catch("Error in setVeltAuthProvider: ",t),null}})}setUserToStorage(e){return X(this,null,function*(){try{if(e){let t=yield Es(e,e?.userId??"");localStorage.setItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER,t)}}catch(t){this.loggingService.catch("Error in setUserToStorage: ",t)}})}getUserFromStorage(e){return X(this,null,function*(){try{let t=localStorage.getItem(N.LOCAL_STORAGE.VELT_IDENTIFY_USER);return t?yield g1(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 X(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 X(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 X(this,null,function*(){try{if(this.autoLoginRequired=!1,this.userOptions$.next(t),this.initializeClientToken)this.pendingUserLogin=e,this.pendingUserLoginSource=l;else{e.userSnippylyId=cd(this.configService.getApiKey(),e.userId),this.pendingUserLogin=void 0,this.pendingUserLoginSource=void 0,this.initializeClientToken=i;let c=yield Cr(this.afAuth).pipe(ut(1)).toPromise().catch(m=>null),d=!0;if(this.providedUser=JSON.parse(JSON.stringify(e)),c){let m=yield Zv(c,!0).catch(A=>null);if(!m)return;let{user:u,firebaseConfig:_,advancedQueries:I}=m.claims;c?.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(c,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 m=qr(this.functions,Kr({url:On.cloudFunction.validateClient,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),u=el(),_=(yield m({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 Zv(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(c){return this.initializeClientToken=0,this.checkForPendingLogin(),this.loggingService.catch("Error in initializeClient: ",c),t?.throwError?Promise.reject(c):Promise.resolve(null)}})}isVersionGreaterThanOrEqualTo4(){try{let e=el();return(e?parseInt(e.split(".")?.[0]||"0"):0)>=4}catch(e){return this.loggingService.catch("Error in isVersionGreaterThanOrEqualTo4: ",e),!1}}isVersion4Point5(){try{let e=el();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({},On.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 gn([this.configService.getConfig$(),this.getAdvancedQueries$()]).pipe(ge(()=>this.getAdvancedQueriesEnabled()),Jn(()=>ce(!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(ye(e=>e?this.user$.asObservable():ce(null)),_t(Kt))}getAuthUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAuthUser","color: green;"),this.afAuth?.currentUser}getUserOptions(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions","color: green;"),this.userOptions$.value}getUserOptions$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getUserOptions$","color: green;"),this.userOptions$.asObservable()}updateUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateUser","color: green;");try{let t=this.user$.value;if(e.userId&&e.userId!==t?.userId||e?.groupId&&e?.groupId!==t?.groupId||e?.organizationId&&e?.organizationId!==t?.organizationId)this.providedUser=e,this.initializeClient(e,this.userOptions$?.value||{},new Date().getTime(),void 0,"internal-updateUser");else if(this.providedUser=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 mde(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 X(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=lt(),l=ys.IDENTIFY;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:vi.MERGE_USER_WITH_PROVIDED_USER_DATA,moduleName:l,source:"internal",payload:{userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId}});let c=yield this.usersService.resolveUsers({userIds:[e.userId],organizationId:this.providedUser?.organizationId||e.organizationId,skipUserCheck:!0,uniqueId:a,moduleName:l});c&&c[e.userId]&&(i=JSON.parse(JSON.stringify(c[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 X(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=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()})),a=El({methodName:"updateUserInternally",data:{type:"getProjectConfig"},getSdkProxy:i,userId:e?.userId??""}),l=Promise.resolve();if(this.userPermissionService?.isPermissionProviderAvailable()&&e.clientOrganizationId){let m=[{userId:e.userId,resource:{id:e.clientOrganizationId,type:oa.ORGANIZATION,source:to.IDENTIFY,organizationId:e.clientOrganizationId}}],u=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.IDENTIFY,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:m}}),l=this.userPermissionService?.onResourceAccessRequired({requests:m,uniqueId:u,userId:e.userId,methodName:to.IDENTIFY,fromCache:!1})??Promise.resolve()}let[c,d]=yield Promise.allSettled([a,l]);c.status==="fulfilled"?(this.setIsPrivateCommentsEnabled(!!c.value?.data?.isPrivateCommentsEnabled),this.activityService?.setActivityFeatureConfig(c.value?.data?.activityConfig??{immutable:!1,isEnabled:!1})):this.loggingService.warn("Failed to fetch project config:",c.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 X(this,null,function*(){try{this.getPlanDetailsCalled=!0;let t=yield qr(this.functions,Kr({url:On.cloudFunction.getPlanDetails,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3})({apiKey:this.configService.getApiKey(),sdkVersion:el(),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(Ge(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(ye(e=>e?this.userOrganization$.asObservable().pipe(ge(t=>t?.metadata?.organizationId===e.organizationId?t:null)):ce(null)))}signOutUser(e="internal"){return X(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 ep(1e3),gde(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 Mo(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 Vo(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)(K(Qr),K(Ft),K(fm),K(tr),K(Ve),K(Oo),K(ct),K(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(),c=a.firebaseOptions.databaseURL;l?.v1DbHost&&c&&(c=zN(c,l.v1DbHost),l?.forceLongPolling&&Vq());let d=T_(void 0,c);l?.v1DbHost&&c&&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)(K(qe),K(Ft),K(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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.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 m(),u({});let A={},M=[...new Set(e.commentAnnotationIds||[])],B=y(h({},e),{commentAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.commentAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.commentAnnotationById$.next(h(h({},this.commentAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ti.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveCommentAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={commentAnnotation:e.commentAnnotation,event:e.eventType,commentId:e.commentId,metadata:Object.values(e.commentAnnotation??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=l),this.loggingService.catch(c?.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:ti.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:c,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:ti.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||lt();return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteCommentAnnotation(e,t,i){return X(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?oi(t):void 0),m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.commentAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={commentAnnotationId:e.toString(),metadata:m,event:xo.COMMENT_ANNOTATION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({commentAnnotationId:e.toString(),metadata:m,event:xo.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:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:I,commentAnnotationId:e.toString(),metadata:m}}),{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:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ti.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:a,commentAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Xc=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.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 m(),u({});let A={},M=[...new Set(e.reactionAnnotationIds||[])],B=y(h({},e),{reactionAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length||e.folderId){let ae=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.reactionAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.reactionAnnotationById$.next(h(h({},this.reactionAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveReactionAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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 c={reactionAnnotation:e,event:xo.REACTION_ADD,metadata:Object.values(e??{})?.[0]?.metadata},d=yield Oi(()=>i?.config?.saveConfig?.url?$i(i.config.saveConfig.url,i.config.saveConfig.headers,c,!1):i?.save?.(c)||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:ni.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:c.event}),this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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||lt();return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(e,t,i){return X(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())),c=t??l?.[e]?.metadata,d=c?oi(c):void 0,m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.reactionAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={reactionAnnotationId:e.toString(),metadata:m,event:xo.REACTION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({reactionAnnotationId:e.toString(),metadata:m,event:xo.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:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:I,reactionAnnotationId:e.toString(),metadata:m}}),{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:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ni.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:a,reactionAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Qc=(()=>{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 X(this,null,function*(){try{let l=new FormData;l.append("file",i);let c={attachment:{attachmentId:a.attachment.attachmentId,name:a.attachment.name,mimeType:a.attachment.mimeType},metadata:a.metadata,event:a.event};l.append("request",JSON.stringify(c));let d={};t&&Object.entries(t).forEach(([_,I])=>{_.toLowerCase()!=="content-type"&&(d[_]=I)});let m=yield fetch(e,{method:"POST",headers:d,body:l});return m.ok?{data:(yield m.json())?.data??{},success:!0,statusCode:200}:(at.catch(`Error in makeAttachmentConfigBasedRequest: ${m.status} ${m.statusText}`),{data:{},success:!1,statusCode:m.status})}catch(l){return at.catch("Error in makeAttachmentConfigBasedRequest:",l),{data:{},success:!1,statusCode:500}}})}saveAttachment(e,t,i){return X(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),c=t||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{request:e}});let d=yield Oi(()=>X(this,null,function*(){if(a?.config?.saveConfig?.url){let m=e.attachment,{file:u}=m,_=Fh(m,["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:c,methodName:ks.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:c,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{result:d,request:e}}),d}catch(a){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",a);let l=t||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ks.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:e}});return}})}deleteAttachment(l,c,d){return X(this,arguments,function*({attachmentId:e,metadata:t},i,a){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let m=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||lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:I,methodName:ks.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e,metadata:u}});let A=yield Oi(()=>{if(m?.config?.deleteConfig?.url){let M={attachmentId:e,metadata:u,event:xo.ATTACHMENT_DELETE};return $i(m.config.deleteConfig.url,m.config.deleteConfig.headers,M,!1)}return m?.delete?.({attachmentId:e,metadata:u,event:xo.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:ks.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:ks.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:_.revertOnFailure,isSuccess:!0},attachmentId:e,metadata:u}}),{revertOnFailure:_.revertOnFailure,isSuccess:!0})}catch(m){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",m);let u=this.getRetryDeleteConfig(a),_=i||lt(),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:ks.DELETE_ATTACHMENT,source:"internal",payload:{error:m,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:c,configKey:d})=>{let m=i?.[d]?.url,u=c in e&&typeof e[c]=="function";!m&&!u&&l.push(c)}),l.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${l.join(", ")}.`;this.loggingService.catch(c);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)(K(tr),K(k),K(ct))},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(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.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 m(),u({});let A={},M=[...new Set(e.recorderAnnotationIds||[])],B=y(h({},e),{recorderAnnotationIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.recorderAnnotationById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.recorderAnnotationById$.next(h(h({},this.recorderAnnotationById$.getValue()),re)),this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveRecorderAnnotation(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={recorderAnnotation:e.recorderAnnotation,event:e.eventType,metadata:Object.values(e.recorderAnnotation??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=l),this.loggingService.catch(c?.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:ri.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,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:ri.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||lt();return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:e}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(e,t,i){return X(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?oi(t):void 0),m=d?h({apiKey:d.apiKey??null,documentId:d.documentId??null,organizationId:d.organizationId??null},d.folderId&&{folderId:d.folderId}):void 0,u=i||lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:e.toString(),metadata:m}});let _=h({},l);delete _?.[e],this.recorderAnnotationById$._value=_;let I=yield Oi(()=>{if(a?.config?.deleteConfig?.url){let A={recorderAnnotationId:e.toString(),metadata:m,event:xo.RECORDER_ANNOTATION_DELETE};return $i(a.config.deleteConfig.url,a.config.deleteConfig.headers,A,!1)}return a?.delete?.({recorderAnnotationId:e.toString(),metadata:m,event:xo.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:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:I,recorderAnnotationId:e.toString(),metadata:m}}),{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:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:e.toString(),metadata:m}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(a){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",a);let l=i||lt(),c=t?oi(t):void 0;return this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:ri.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:a,recorderAnnotationId:e.toString(),metadata:c}}),{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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct),K(Qc))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var st=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I){this.analyticsService=e,this.authService=t,this.databaseService=i,this.domService=a,this.configService=l,this.loggingService=c,this.commentResolverService=d,this.reactionResolverService=m,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 it,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0};try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.setDocumentIdSubject.pipe(jB(()=>as(this.currentDebounceTime))).subscribe({next:A=>X(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(Ge(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=XN(window.location.href);this.currentUrl=M}this.analyticsService.updateDefaultProperties({apiKey:A})}}),this.authService.getUser$().subscribe(A=>X(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(Ge(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=XN(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=XN(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 X(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:kl.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(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}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))&&sr(t,this.pendingOptions))return!1;let i=this.documentPaths$.value?.clientDocumentId,a=t?.rootDocumentId??e[0]?.id,l=this.documentIds$.value.map(m=>m.clientDocumentId),c=JN(this.getOptionsFromDocumentPaths()??{})??{};return!e.every(m=>l.includes(m.id))||!sr(c,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,c=`${Qn(l)}`;t&&a?.metadata&&typeof a.metadata=="object"&&(this.clientDocumentMetadataMap[l]=a.metadata),i.push({documentId:c,clientDocumentId:l})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(l){return X(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:kl.SET_DOCUMENTS,source:i,payload:{documents:e,options:t}}),yield this.setDocumentsImpl({documents:e,options:t??{},source:i,skipPermissionValidation:a})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(i){return X(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:kl.SET_ROOT_DOCUMENT,source:t,payload:{document:e}});let a=this.getOptionsFromDocumentPaths()??{},l=this.documentIds$.value.map(c=>c.clientDocumentId);if(!l.includes(e.id)){let c=[...l.map(m=>({id:m})),{id:e.id}],d=this.getDocumentIdsFromDocuments({documents:c,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(_t(Kt))}getProcessedDocContext(){return uhe(this.getDocContext())}filterRelevantDocuments(a){return X(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 X(this,null,function*(){if(!e?.folderId||!e?.allDocuments)return t;try{let a=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield El({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:e?.organizationId??i?.clientOrganizationId,folderId:e?.folderId}},getSdkProxy:a,userId:i?.userId??""}))?.data?.forEach(c=>{t.find(d=>d.clientDocumentId===c.id)||t.push({documentId:mi(c.id),clientDocumentId:c.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:to.SET_DOCUMENTS,organizationId:e.organizationId,context:e?.context}}),e.folderId&&a.push({userId:i.userId,resource:{id:e.folderId,type:oa.FOLDER,source:to.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:to.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:e?.context}})}),e?.context&&this.userPermissionService?.getIsContextEnabled()&&rF({input:e?.context}).forEach(c=>{let d=JSON.stringify(c.access);a.push({userId:i.userId,resource:{id:d,type:oa.CONTEXT,source:to.SET_DOCUMENTS,organizationId:e?.organizationId??i?.clientOrganizationId??"",context:c}})}),a}catch(a){return this.loggingService.catch("Error in buildPermissionRequests:",a),[]}}processAccessibleContexts(e,t){try{if(!e?.success||!e?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let 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(c=>i.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),l=phe({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 X(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=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.SET_DOCUMENTS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}}),this.userPermissionService?.cancelPendingRevokes(a);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:to.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(a??"nil"))),this.processAccessibleContexts(c,a)}catch(a){this.loggingService.catch("Error in handlePermissionProvider:",a)}})}filterDocumentsByPermissions(e,t,i,a=!1){return X(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 c=this.currentValidationToken,d=[...t];return c&&this.validatePermissionsInBackground(e,t,i,c),d})}validateAndFilterPermissions(e,t,i){return X(this,null,function*(){try{let a=e?.organizationId??i?.clientOrganizationId,l=yield this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:t.map(m=>m.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]});if(!l)return t;this.userPermissionService?.setCurrentUserPermissions(l),a&&l?.[i.userId]?.organization?.[a]?.errorCode===fo.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===fo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${e?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(l?.[i.userId]?.documents??{}).forEach(([m,u])=>{u?.errorCode===fo.PERMISSION_DENIED&&c.add(m)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].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:[...c],userId:i.userId,timestamp:new Date().getTime()}));let d=t.filter(m=>!c.has(m.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(c=>c.clientDocumentId),folderIds:e?.folderId?[e?.folderId]:[]}).then(c=>{if(this.currentValidationToken===a&&c){this.userPermissionService?.setCurrentUserPermissions(c);let d=[];Object.entries(c?.[i.userId]?.documents??{}).forEach(([m,u])=>{u?.errorCode===fo.PERMISSION_DENIED&&d.push(m)}),l&&c?.[i.userId]?.organization?.[l]?.errorCode===fo.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${l}`,void 0,void 0,!0),e?.folderId&&c?.[i.userId]?.folders?.[e?.folderId]?.errorCode===fo.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(c=>{this.loggingService.catch("Error in background permission validation:",c)})}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||[],c=l.filter(d=>!e.includes(d.clientDocumentId));c.length!==l.length&&(c.length>0?this.setDocuments({documents:c.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 X(this,arguments,function*({organizationId:e,user:t,notificationsConfig:i,currentUserId:a}){try{let c=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield El({data:h({type:"addUserInfoToOrganization",metadata:{organizationId:e},user:this.usersService?.externalUserDataProviderAvailable()?{userId:t?.userId}:t},i&&{notificationsConfig:i}),getSdkProxy:c,userId:a??t?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(l){return X(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,JN(t))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=lt();this.currentValidationToken=c;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 m=this.authService.getUser();if(!m){this.draftDocuments=e,this.draftOptions=t;return}this.pendingDocumentIds=e.map(_=>_.id),this.pendingOptions=JN(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??m?.clientOrganizationId;if(u&&this.addUserInfoToOrganization({organizationId:u,user:m}),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(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(a){return X(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:kl.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 X(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 c=Date.now(),d=c-this.lastSetDocumentIdCallTime,m=c-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=c,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||d>l&&m>l){yield this.setDocumentIdImpl(e,t,i),this.lastSetDocumentIdExecutionTime=c;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 X(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 c=`${Qn(e)}`,d=i?.folderId,m=i?.folderId?Rr(i?.folderId):void 0,u=i?.locationId,_=i?.allDocuments,I=a?.organizationId?t?It(t):a?.organizationId:void 0,A=lt(),M=o1.SET_DOCUMENTS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ti.INIT_DOCUMENTS,moduleName:M,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let B=lt(),q=i1.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:ni.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}});let ae=lt(),be=a1.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:be,methodName:ri.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:A,moduleName:M}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:B,moduleName:q}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(re=>re.clientDocumentId),organizationId:t??a?.clientOrganizationId??""},uniqueId:ae,moduleName:be})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==I){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let re=new ON,_e=new RL;re.clientDocumentId=e,_e.clientDocumentId=e,re.folderId=d,_e.folderId=d,re.locationId=u,_e.locationId=u,re.allDocuments=_,_e.allDocuments=_,re.veltFolderId=m,_e.veltFolderId=m,re.documentId=c,_e.documentId=c,I&&(re.organizationId=I,re.clientOrganizationId=t??a?.clientOrganizationId,_e.organizationId=I,_e.clientOrganizationId=t??a?.clientOrganizationId);let Ie=`${this.apiKey}`,Ce=`apiKey/${this.apiKey}`;I&&(Ie=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${re.organizationId}`,Ce=`${Ce}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${re.organizationId}`),_e.organization=`apiKey/${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,_e.document=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}`,re.presence=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_PRESENCE}/`,re.cursor=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CURSOR}/`,re.comment=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/`,_e.comment=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_COMMENT}`,re.multiThread=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,_e.multiThread=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,re.tag=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_TAG}/`,re.area=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AREA}/`,_e.area=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AREA}`,re.arrow=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_ARROW}/`,re.selection=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_SELECTION}/`,re.audioHuddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,re.huddle=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_HUDDLE}/`,re.recorder=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/`,_e.recorder=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`,re.flock=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,re.syncVideoPlayer=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,re.liveState=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,re.liveStateSingleEditorMode=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,re.reaction=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_REACTION}/`,_e.reaction=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_REACTION}`,re.crdt=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CRDT}/`,_e.crdt=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_CRDT}`,re.customerMetadata=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,re.views=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_VIEWS}/`,_e.notificationViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,_e.documentViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,_e.locationViews=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,re.notifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,re.metadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_METADATA}/`,re.users=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,re.documentIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.workspaceIam=`${this.apiKey}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.groupContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GROUPS}/`,re.globalContacts=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_GLOBAL}/`,re.logins=`${Ie}/${N.FIREBASE_PARTIAL_PATH_CONTACTS}/${N.FIREBASE_PARTIAL_PATH_LOGINS}/`,re.userFeedback=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,re.userReportBugs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_BUGS}/`,re.userContactUs=`${Ie}/${N.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${N.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,I&&(re.organizationMetadata=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,re.organizationIam=`${Ie}/${N.FIREBASE_PARTIAL_PATH_IAM}/`,re.organizationGroups=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,re.organizationNotifications=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(re.organizationNotificationsWithDocumentId=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,re.heartbeatByDocument=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),re.organizationNotificationsLastNotificationTimestamp=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${N.FIREBASE_PARTIAL_PATH_DOCS}/`,re.organizationNotificationsUsers=`${Ie}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${N.FIREBASE_PARTIAL_PATH_USERS}/`,re.heartbeat=`${Ie}/${N.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),_e.organizationUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,_e.users=`${Ce}/${N.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,_e.documentUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,_e.notificationDocs=`${Ce}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,_e.notificationUsers=`${Ce}/${N.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(re),this.firestorePaths$.next(_e),re?.clientOrganizationId&&re?.organizationId&&!(re?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&re?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.organizationConfig$.next({organizationId:re?.organizationId,clientOrganizationId:re?.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:c,clientDocumentId:e}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:e},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(a){this.loggingService.catch("Error in setDocumentIdImpl: ",a)}})}unsetDocumentId({source:e,unsetDocumentPaths:t}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{e==="internal"&&this.analyticsService.trackEvent(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:kl.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:kl.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 X(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 X(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 X(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=[],c={organizationId:t?.clientOrganizationId,folderId:a},d=[],m=20;for(let _=0;_<e.length;_+=m)d.push(e.slice(_,_+m));d.forEach(_=>{let I=JSON.parse(JSON.stringify(c));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 X(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=[],c={organizationId:e?.clientOrganizationId,folderId:i,allDocuments:a},d=[],m=20;for(let _=0;_<t.length;_+=m)d.push(t.slice(_,_+m));d.forEach(_=>{let I=JSON.parse(JSON.stringify(c));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(Jn(t=>ce(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 X(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:kl.SET_LOCATION,payload:{locations:[e],options:void 0}}),this.setLocationsImpl({locations:[e]})}catch(a){this.loggingService.catch("Error in setLocation: ",a)}})}setLocations(a){return X(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:kl.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 X(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:kl.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=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...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=Di(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=Di(d),_=Qn(JSON.stringify(u));u.id&&l.push({locationId:_,location:u}),this.location$.next({locationId:_,location:u})}let m=[];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:_}),m.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:kl.SET_LOCATIONS,payload:{locations:a,options:t}}),this.analyticsService.trackEvent(Y.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:a,options:t},!0,this.getUserIdForAnalytics()),m}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:kl.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:kl.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:kl.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:kl.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:kl.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),ce([])}}updateOrganizationMetadata(e){return X(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 VN;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 X(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=qr(this.functions,Kr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));yield El({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 X(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=>X(this,null,function*(){let l=new DN;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 c=e?.folderId,d=e?.veltFolderId;l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let m=!0,u=this.documentMetadata$.value?.[a.documentId];if(c&&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!==c||_?.veltFolderId!==d)?(this.loggingService.catch(`Folder id mismatch for document ${a?.clientDocumentId??""}`),m=!1):_?.folderId===c?(c&&(l.folderId=c),d&&(l.veltFolderId=d)):(this.loggingService.catch(`Document ${a?.clientDocumentId??""} is not in the folder ${c??""}`),m=!1):(c&&(l.folderId=c),d&&(l.veltFolderId=d))}if(u){let _={};Object.entries(l).forEach(([I,A])=>{_[I]=A}),sr(_,u)&&(m=!1)}m&&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 X(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 c=[];for(let d of e){let m=new RN;m.locationId=d?.locationId,m.veltLocationId=BK(d?.location?.id??""),m.location=d?.location,m.pageInfo=no(),m?.pageInfo?.deviceInfo&&delete m?.pageInfo?.deviceInfo;let u=y(h({},l),{[N.FIREBASE_PARTIAL_PATH_LOCATIONS]:y(h({},l[N.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[d?.locationId]:m})});this.commonDbService?.shouldUseFirestore()||c.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(c)}}}}catch(t){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",t)}})}genarateLocationId(e){try{return e&&typeof e=="object"?Qn(JSON.stringify(Di(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(c=>c.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 c=JSON.parse(l),d=this.genarateLocationId(c);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),ce({})}}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 c={id:a},d=this.genarateLocationId(c);e[a]={element:i,location:{locationId:d,location:c}}}}}),e}catch(e){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",e),{}}}getAdditionLocationFromElement(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let t;if(t=e?.closest(`[${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),_t(Kt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(e=>e||{}),_t(Kt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(e){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",e),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let e=this.documentMetadata$.value||{},t={},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(c=>{let d=e?.[c.documentId];d&&(t[c.documentId]=d)});else if(this.documentPaths$.value?.documentId){let c=e?.[this.documentPaths$.value?.documentId];c&&(t[this.documentPaths$.value?.documentId]=c)}}return Object.values(t)}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",e),[]}}getDocumentMetadata$(e){return this.documentMetadata$.asObservable().pipe(ge(t=>t?.[e??this.documentPaths$.value?.documentId??""]||null),_t(Kt))}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||{}),_t(Kt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(_t(Kt))}getOrganizationConfig(){return this.organizationConfig$.value}getMetadataFromType(e,t){try{switch(e){case"area":return;case"comment":return t?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(t.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return t?.commentAnnotationId?this.commentService?.getAnnotationById(t.commentAnnotationId)?.metadata:void 0;default:return}}catch(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,c=this.getDocumentMetadata(l);if(!c)return;let d=c?.folderId,m=c?.veltFolderId;return h(h({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:a,clientOrganizationId:i.clientOrganizationId,documentId:l,organizationId:i.organizationId},d?{folderId:d}:{}),m?{veltFolderId:m}:{})}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),c=this.getDefaultMetadata({clientDocumentId:i,documentId:a}),d=l||c||{};return d.sdkVersion=el(),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 X(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=Rr(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 X(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=Rr(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 X(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 c=Pa(i);if(!a||a.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let d=[],m=this.documentMetadata$.value??{};for(let u of a)if(u?.documentId){u.organizationId=c,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=Rr(l||this.documentPaths$.value?.folderId||""));let I=()=>{if(l&&this.documentPaths$.value?.folderId&&l!==this.documentPaths$.value?.folderId)return;let M=m?.[_];M?m[_]=h(h({},M),u):m[_]=u},A=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:_,organizationId:c,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:c,documentId:_}}))}yield Promise.all(d),this.setAllDocumentMetadata(m)}catch(t){return this.loggingService.catch("Error in DocService updateDocuments:",t),[]}})}updateLocations(e){return X(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 c=l.map(u=>mi(u)),d=[],m=this.locationMetadata$.value;m||(m={}),c.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=BK(_.id),M=m?.[u],B=M?.[_.id];m&&(M||(m[u]={}),B||(m[u][_.id]={}),m[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(m||{}).length>0&&this.locationMetadata$.next(m)}catch(t){return this.loggingService.catch("Error in DocService updateLocations:",t),[]}})}fetchFolders(e){return X(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 c=Rr(e?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,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","==",c)],folderId:c,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(ye(e=>e?this.documentPaths$.pipe(ye(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),_t((i,a)=>JSON.stringify(i??{})===JSON.stringify(a??{}))):ce(null))):ce(null)))}getDocumentAccessType(e){try{return e&&e.features&&e.features.all?e.features.all.restricted?Gr.RESTRICTED:Gr.PUBLIC:e&&e.documentAccessType?e.documentAccessType:Gr.PUBLIC}catch(t){return this.loggingService.catch("Error in DocService getDocumentAccessType:",t),Gr.PUBLIC}}changeDocumentAccessType(e){return X(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 Gr.PUBLIC:i.features.all.restricted=!1;break;case Gr.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)(K(ct),K(qe),K($n),K(Ve),K(Ft),K(k),K(rl),K(Xc),K(ol),K(tr),K(Oo))},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 Ln,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=c=>{try{return this.userById$.value?.[c]}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(Ge(c=>!!c),ye(()=>this.getUnresolvedUsers$().pipe(Ge(c=>c.length>0),Xr(300),ut(20),ye(c=>{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",c.slice(0,20)))]}}).pipe(ge(m=>m?.data),ln(m=>{if(m&&typeof m=="object"){delete m.undefined,delete m.null;let u=Object.values(m??{});this.setUserByIds(u.map(I=>I.user));let _=c.filter(I=>!u.some(A=>A.user.userId===I));_.length!==c.length&&this.setUnresolvedUsers(_)}})):ce([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}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(m){return X(this,arguments,function*({userIds:e,forceResolve:t,feature:i,organizationId:a,skipUserCheck:l=!1,uniqueId:c,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=c||lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:M,moduleName:d,methodName:vi.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((be,re)=>{q=setTimeout(()=>{re(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:vi.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:vi.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 _=c||lt();return this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:vi.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 X(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 $i(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 m=yield l.get(e);if(m&&typeof m=="object"&&"success"in m&&"statusCode"in m&&typeof m.success=="boolean"&&typeof m.statusCode=="number"){let u=m;return u.statusCode===200&&u.data?u.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${u.statusCode}`),{})}return m}if(t||(t=this.docService.getOrganizationConfig()?.organizationId),!t)return{};let c=(yield this.getUsersFromDBWithBatching({userIds:e,organizationId:t,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(c.flat());let d={};return c.forEach(m=>{m.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 X(this,arguments,function*({userIds:e,organizationId:t,skipUserCheck:i=!1}){try{if(!e?.length)return[];let l=[];for(let m=0;m<e.length;m+=30)l.push(e.slice(m,m+30));let c=l.map((m,u)=>X(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("user.userId","in",m)],skipUserCheck:i}}))||[]}catch(_){return this.loggingService.catch(`Error in batch ${u+1}:`,_),[]}}));return yield Promise.all(c)}catch(l){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",l),[]}})}getTemporaryUsersFromDBWithBatching(a){return X(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 c=[];for(let M=0;M<i.length;M+=30)c.push(i.slice(M,M+30));let d=[],m=0,u=(M,B)=>X(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 ${m+1}:`,q),[]}});for(let M of l)for(let B of c)d.push(u(M,B)),m++;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(_t(Kt))}catch(e){return this.loggingService.catch("Error in UsersService getUserById$:",e),ce({})}}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 X(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(re=>!!re))];if(l.length===0)return{};let c={},d=[];if(l.forEach(re=>{let _e=this.userIdByEmailCache[re];_e?c[re]=_e:d.push(re)}),d.length===0)return c;let m=this.docService.getOrganizationConfig()?.clientOrganizationId||"",u=this.docService.getDocumentPaths()?.clientDocumentId||"",_=this.docService.getDocumentPaths()?.folderId||"",I={organizationId:m,documentId:u,folderId:_,emails:d},A=t||lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:d,organizationId:m,documentId:u,folderId:_}});let M=a.config?.resolveTimeout||this.resolveTimeout,B,q=new Promise((re,_e)=>{B=setTimeout(()=>{_e(new Error("resolveUserIdsByEmail timeout"))},M)}),ae=a.config?.getRetryConfig||{retryCount:0,retryDelay:0},be=X(this,null,function*(){try{let re=yield Oi(()=>a.resolveUserIdsByEmail(I),"resolveUserIdsByEmail",ae);return re?.statusCode===200&&re?.data?re.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${re?.statusCode}. Message: ${re?.message||"Unknown error"}`),{})}finally{clearTimeout(B)}});try{let re=yield Promise.race([be,q]);return Object.entries(re).forEach(([_e,Ie])=>{Ie&&(this.userIdByEmailCache[_e]=Ie,c[_e]=Ie,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:Ie,name:_e,email:_e},currentUserId:this.authService.getUser()?.userId??""}).catch(Ce=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",Ce)}))}),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:re,emails:d}}),c}catch(re){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",re),this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:re,emails:d}}),c}}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)(K(ct),K(qe),K(tr),K(st),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wp=class{static getFirestoreProdDbName(o,r){return r?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||r?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":r?.storeDbId??(this.isTestingDb(r?.databaseURL??"")?"sdktest":`apikey${o.toLowerCase()}`)}static isTestingDb(o){try{return o.includes("-test")}catch(r){return at.error("Error in isTestingDb:",r),!1}}};var Cm=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.commentAnnotationsResolverService=c,this.attachmentResolverService=d,this.coreActionsService=m,this.notificationActionTypeMap={[At.NEWLY_ADDED]:xo.COMMENT_ANNOTATION_ADD,[At.ADDED]:xo.COMMENT_ADD,[At.UPDATED]:xo.COMMENT_UPDATE,[At.DELETED]:xo.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?.suggestion?.resolvedBy?.userId&&t.add(i?.suggestion?.resolvedBy?.userId),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?.suggestion?.resolvedBy?.userId){let t=this.usersService.getUserById(e?.suggestion?.resolvedBy?.userId);t&&(e.suggestion.resolvedBy=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,c)=>c.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(ld(`{{${a.userId}}}`),"g");t.commentText?.includes(`@User ${a.userId}`)&&(l=new RegExp(ld(`@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};e?.suggestion?.resolvedBy?.userId&&(e.suggestion.resolvedBy={userId:e.suggestion.resolvedBy.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 c=t?.comments?.[l?.commentId];if(c){l.commentHtml=c?.commentHtml,l.commentText=c?.commentText;let d=c?.attachments;i&&d&&l.attachments?.forEach(m=>{let u=m?.attachmentId;d?.[u]&&(m.name=d?.[u]?.name,m.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?!sr(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 Jl;if(Object.assign(a,e),a.isCommentResolverUsed=t,i){let l=a.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));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 X(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=lt();this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:vi.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(c=>{if(c?.contact?.email&&!c?.userId){let d=a[c.contact.email];if(d){let m=c.text;if(m){let u=ld(m),_=new RegExp(u,"g");l.commentText&&(l.commentText=l.commentText.replace(_,`{{${d}}}`)),l.commentHtml&&(l.commentHtml=l.commentHtml.replace(_,`{{${d}}}`))}c.userId=d,c.contact.userId=d,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),l.to=l.to?.map(c=>{if(c?.email&&!c?.userId){let d=a[c.email];if(d)return delete c?.email,delete c?.visibility,y(h({},c),{userId:d})}return c})})}return e}catch(t){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",t),e}})}stripCommentAnnotationData(a){return X(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(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),d=this.commentAnnotationsResolverService.getAdditionalFields(),m;t&&(m=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:oi(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,c?.length>0&&c.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(be=>{ae[be.attachmentId]={attachmentId:be.attachmentId,name:be.name,url:be.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 Mr;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&&(m=_?.comments?.length&&_?.comments?.length>0?xo.COMMENT_ADD:xo.COMMENT_ANNOTATION_ADD),{strippedData:I&&(t&&this.notificationActionTypeMap?.[t]||A?.isDraft)?u:null,originalData:_,eventType:m}}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(c=>c.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(ld(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 X(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,c=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:to.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0}}),c){let I=JSON.stringify(c);d.push({userId:_,resource:{id:I,type:oa.CONTEXT,source:to.SET_NOTIFICATIONS,organizationId:e?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let m=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:to.SET_NOTIFICATIONS,uniqueId:m,timestamp:new Date().getTime(),source:"internal",payload:{requests:d}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:d,uniqueId:m,methodName:to.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(c){return X(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=WN(this.authService.getFirebaseConfig()?.firebaseOptions),m=qr(this.functions,Kr({url:On.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=wp.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:On.firebaseNotificationsDatabaseURL,feature:"comment",eventType:a??"PATCH",sdkVersion:el(),deniedForYouUsers:_,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),metadata:l},A=yield Es(I,this.authService.getUser()?.userId??"");yield m({veltData:A})}catch(d){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",d)}})}};o.\u0275fac=function(t){return new(t||o)(K(k),K(An),K(qe),K(Oo),K(Ft),K(rl),K(Qc),K(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,c){this.loggingService=e,this.usersService=t,this.authService=i,this.functions=a,this.configService=l,this.reactionAnnotationsResolverService=c}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 X(this,arguments,function*({data:e,firestorePath:t,eventType:i}){try{let l=WN(this.authService.getFirebaseConfig()?.firebaseOptions),c=qr(this.functions,Kr({url:On.cloudFunction?.[l]?.setEncryptedData,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d=wp.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),m=this.authService.getUser()?.userId??"",u={path:t??"",data:e??{},dbId:d??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:el()},_=yield Es(u,m);yield c({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?!sr(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:oi(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)(K(k),K(An),K(qe),K(Oo),K(Ft),K(Xc))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tp=(()=>{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 X(this,null,function*(){try{return yield Es(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:oi(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[m,u]of Object.entries(e.recordingEditVersions)){let _=Number(m),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(m=>({attachmentId:m?.attachmentId,name:m?.name,bucketPath:m?.bucketPath}))),delete d.transcription;e.isRecorderResolverUsed=!0;let c;return t===Zl.ADDED?c=xo.RECORDER_ANNOTATION_ADD:t===Zl.UPDATED?c=xo.RECORDER_ANNOTATION_UPDATE:t===Zl.DELETED&&(c=xo.RECORDER_ANNOTATION_DELETE),{strippedData:{[i]:l},originalData:e,eventType:c}}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)(K(qe),K(k),K(An),K(ol))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Dp=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let ae=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.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 m(),u({});let A={},M=[...new Set(e.activityIds||[])],B=y(h({},e),{activityIds:M});X(this,null,function*(){try{if(M.length>0||e.documentIds?.length){let ae=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:B}});let be=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,B,!0):I?.get?.(B)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(re=>c?{}:(m(),re&&re.statusCode!==200?(this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:re,request:B}}),this.loggingService.catch(re?.message??"Error in ActivityResolverService resolveActivities:"),{}):re?.data)).catch(re=>{throw m(),re});try{A=(yield be)||{},this.analyticsService.trackEvent(Y.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:M});let re={};Object.entries(A).forEach(([_e,Ie])=>{let Ce=this.activityById$.value?.[_e];Ce?Ce&&JSON.stringify(Ce)!==JSON.stringify(Ie)&&(re[_e]=Ie):re[_e]=Ie}),Object.keys(re).length>0&&this.activityById$.next(h(h({},this.activityById$.getValue()),re)),this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:ae,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:re,request:B}}),u(re)}catch(re){let _e=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_e,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:re,request:B}}),c||_(re),u(A)}}else m(),u({})}catch(ae){m();let be=t||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:be,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:ae,request:B}}),_(ae)}})})}catch(l){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:yc.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}saveActivity(e,t){return X(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||lt();this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:yc.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 c=yield Oi(()=>{if(i?.config?.saveConfig?.url){let d={activity:e.activity,event:e.event,metadata:Object.values(e.activity??{})?.[0]?.metadata};return $i(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 c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=l),this.loggingService.catch(c?.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:yc.SAVE_ACTIVITY,source:"internal",payload:{error:c,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:yc.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||lt();return this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:yc.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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},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,a,l,c,d,m,u){this.loggingService=e,this.usersService=t,this.commentUtilsService=i,this.reactionUtilsService=a,this.recorderUtilsService=l,this.commentAnnotationsResolverService=c,this.reactionAnnotationsResolverService=d,this.recorderAnnotationsResolverService=m,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((c,d)=>{if(c!=null&&typeof c=="object")return c[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 X(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 X(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=oi(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?oi(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?oi(e.metadata):void 0},l=JSON.parse(JSON.stringify(e.entityData));if(t){let c=this.recorderUtilsService.stripRecorderAnnotationData({data:l});if(c?.strippedData){let d=Object.keys(c.strippedData)[0];d&&(a.entityData=c.strippedData[d])}}if(i){let c=this.reactionUtilsService.stripReactionAnnotationData(l);if(c?.strippedData){let d=Object.keys(c.strippedData)[0];d&&(a.entityData=c.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 Hr.ANNOTATION_ADD:return`${t} added a comment`;case Hr.COMMENT_ADD:return`${t} replied to a comment`;case Hr.COMMENT_UPDATE:return`${t} edited a comment`;case Hr.COMMENT_DELETE:return`${t} deleted a comment`;case Hr.ANNOTATION_DELETE:return`${t} deleted a comment thread`;case Hr.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 Hr.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),c=i?.from,d=c&&typeof c=="object"?c?.name:c?String(c):null;return d&&l?`${t} changed priority from ${d} to ${l}`:`${t} changed priority to ${l}`}case Hr.ASSIGN:{let a=e.changes?.assignedTo?.to;return a&&typeof a=="object"&&a.name?`${t} assigned to ${a.name}`:`${t} assigned the comment`}case Hr.ACCESS_MODE_CHANGE:{let a=e.changes?.accessMode?.to;return a?`${t} changed access to ${a}`:`${t} changed the access mode`}case Hr.CUSTOM_LIST_CHANGE:return`${t} changed the custom list`;case Hr.APPROVE:return`${t} approved the comment`;case Hr.ACCEPT:return`${t} accepted a suggestion`;case Hr.REJECT:return`${t} rejected a suggestion`;case Hr.REACTION_ADD:return`${t} reacted to a comment`;case Hr.REACTION_DELETE:return`${t} removed a reaction`;case Hr.SUBSCRIBE:return`${t} subscribed to the thread`;case Hr.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 h3.RECORDING_ADD:return`${t} added a recording`;case h3.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 f3.REACTION_ADD:return`${t} added a reaction`;case f3.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 X(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 c=t.comments?.[String(l)];c&&(c.commentText&&(a.commentText=c.commentText),c.commentHtml&&(a.commentHtml=c.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,c=t,d=i,m=a===At.DELETED&&l?.isAnnotationDelete?Hr.ANNOTATION_DELETE:this.mapCommentStatusToActionType(a);if(!m)return null;let u=c?.annotationId;if(!u)return null;let _=d?.commentId,I=this.buildCommentChanges(a,d,l);return{featureType:"comment",actionType:m,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 Hr.ANNOTATION_ADD;case At.ADDED:return Hr.COMMENT_ADD;case At.UPDATED:return Hr.COMMENT_UPDATE;case At.DELETED:return Hr.COMMENT_DELETE;case At.STATUS_CHANGED:return Hr.STATUS_CHANGE;case At.PRIORITY_CHANGED:return Hr.PRIORITY_CHANGE;case At.ASSIGNED:return Hr.ASSIGN;case At.ACCESS_MODE_CHANGED:return Hr.ACCESS_MODE_CHANGE;case At.CUSTOM_LIST_CHANGED:return Hr.CUSTOM_LIST_CHANGE;case At.APPROVED:return Hr.APPROVE;case At.ACCEPTED:return Hr.ACCEPT;case At.REJECTED:return Hr.REJECT;case At.REACTION_ADDED:return Hr.REACTION_ADD;case At.REACTION_DELETED:return Hr.REACTION_DELETE;case At.SUBSCRIBED:return Hr.SUBSCRIBE;case At.UNSUBSCRIBED:return Hr.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 Zl.ADDED:return h3.RECORDING_ADD;case Zl.DELETED:return h3.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 f3.REACTION_ADD;case"delete":return f3.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)(K(k),K(An),K(Cm),K(NL),K(Tp),K(rl),K(Xc),K(ol),K(Dp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bm=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=Rr(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=Rr(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 fbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Cbe=(()=>{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)(K(k),K(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}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)(K(k),K(An))},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}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)(K(k),K(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 X(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=lt(),a=ys.GET_HUDDLE_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:vi.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 c of e)c?.from?.userId&&l[c.from.userId]&&(c.from=l[c.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)(K(tr),K(k),K(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 X(this,null,function*(){try{let t=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:e}});if(t.length){let i=lt(),a=ys.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:vi.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)(K(tr),K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var kbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _m=(()=>{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 X(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,c=!1,d=!1,m=()=>{l&&(clearTimeout(l),l=void 0,d=!0)};return new Promise((u,_)=>{l=setTimeout(()=>{if(!d){c=!0,m();let Ie=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.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 m(),u({});let A={},M=this.notificationById$.getValue()||{},B=[...new Set(e.notificationIds||[])],q=[],ae=[],be=[];for(let Ie of B)M[Ie]||(this.inFlightRequests.has(Ie)?(q.push(this.inFlightRequests.get(Ie)),ae.push(Ie)):be.push(Ie));let re=y(h({},e),{notificationIds:be});X(this,null,function*(){try{if(q.length>0&&(yield Promise.allSettled(q)),be.length>0){let Ie=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:re}});let Ce,Te=new Promise(Me=>{Ce=Me});for(let Me of be)this.inFlightRequests.set(Me,Te.then(je=>je?.[Me]));let Oe=Oi(()=>I?.config?.getConfig?.url?$i(I.config.getConfig.url,I.config.getConfig.headers,re,!0):I?.get?.(re)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(Me=>c?{}:(m(),Me&&Me.statusCode!==200?(this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Me,request:re}}),this.loggingService.catch(Me?.message??"Error in NotificationResolverService resolveNotifications:"),{}):Me?.data)).catch(Me=>{throw m(),Me});try{A=(yield Oe)||{},Ce(A);for(let je of be)this.inFlightRequests.delete(je);this.analyticsService.trackEvent(Y.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:be});let Me={};Object.entries(A).forEach(([je,We])=>{let ze=this.notificationById$.value?.[je];ze?ze&&JSON.stringify(ze)!==JSON.stringify(We)&&(Me[je]=We):Me[je]=We}),Object.keys(Me).length>0&&this.notificationById$.next(h(h({},this.notificationById$.getValue()),Me)),this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:Ie,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:Me,request:re}}),u(Me)}catch(Me){Ce({});for(let We of be)this.inFlightRequests.delete(We);let je=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:je,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Me,request:re}}),c||_(Me),u(A)}}else m(),u({})}catch(Ie){m();let Ce=t||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:Ce,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:Ie,request:re}}),_(Ie)}})})}catch(l){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",l);let c=t||lt();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:yl.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:l,request:e}}),{}}})}deleteNotification(e,t,i){return X(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||lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:yl.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:e,organizationId:t}});let c=this.notificationById$.getValue(),d=h({},c);delete d?.[e],this.notificationById$._value=d;let m={notificationId:e,organizationId:t},u=yield Oi(()=>a?.config?.deleteConfig?.url?$i(a.config.deleteConfig.url,a.config.deleteConfig.headers,m,!1):a?.delete?.(m)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return u&&u.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),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:yl.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:yl.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||lt();return this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:yl.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()):ce(void 0)}catch(e){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",e),ce(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:c})=>{let d=t?.[c]?.url,m=l in e&&typeof e[l]=="function";!d&&!m&&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)(K(tr),K(k),K(ct))},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,c,d){this.commentUtilsService=e,this.recorderUtilsService=t,this.loggingService=i,this.usersService=a,this.authService=l,this.commentAnnotationsResolverService=c,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 c of l)t.add(c)}break}}return Array.from(t)}catch(t){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",t),[]}}mergeStrippedDataWithNotification(e){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return e;let t=this.commentAnnotationsResolverService.getAnnotationById(e?.notification?.targetAnnotationId),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 X(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 Es(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)(K(Cm),K(Tp),K(k),K(An),K(qe),K(rl),K(_m))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ibe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ebe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var wbe=(()=>{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)(K(k),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vd=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,B,q,ae,be,re,_e,Ie,Ce,Te,Oe,Me){this.activityUtilsService=e,this.areaUtilsService=t,this.arrowUtilsService=i,this.commentUtilsService=a,this.contactUtilsService=l,this.coreActionsService=c,this.cursorUtilsService=d,this.huddleUtilsService=m,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=be,this.usersService=re,this.docService=_e,this.commentAnnotationsResolverService=Ie,this.reactionAnnotationsResolverService=Ce,this.recorderAnnotationsResolverService=Te,this.notificationResolverService=Oe,this.activityResolverService=Me}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:c,folderId:d}=t;c||(c=i?.organizationId);let m=new LL({apiKey:a,documentId:l?`${l}`:"",organizationId:c?`${c}`:"",veltFolderId:d?`${d}`:void 0});switch(e){case"userConfig":return t?.userId&&m?.userConfig?`${m?.userConfig}/${t?.userId}${t?.documentId?`/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:""}`:void 0;case"allPermissionsUsers":return m?.permissionsUsers?`${m?.permissionsUsers}`:void 0;case"comment":return t?.documentId&&t?.id&&m?.comment?`${m?.comment}/${t?.id}`:void 0;case"allComments":return t?.documentId&&m?.comment?`${m?.comment}`:void 0;case"multiThread":return t?.documentId&&t?.id&&m?.multiThread?`${m?.multiThread}/${t?.id}`:void 0;case"allMultiThreads":return t?.documentId&&m?.multiThread?`${m?.multiThread}`:void 0;case"crdt":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}`:void 0;case"allLastNotificationTimestamp":return m?.lastNotificationTimestamp?`${m?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return t?.id&&m?.lastNotificationTimestamp?`${m?.lastNotificationTimestamp}/${t?.id}`:void 0;case"activity":return t?.id&&m?.activities?`${m?.activities}/${t?.id}`:void 0;case"allActivities":return m?.activities?`${m?.activities}`:void 0;case"allLastActivityTimestamp":return m?.lastActivityTimestamp?`${m?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return t?.id&&m?.lastActivityTimestamp?`${m?.lastActivityTimestamp}/${t?.id}`:void 0;case"area":return t?.documentId&&t?.id&&m?.area?`${m?.area}/${t?.id}`:void 0;case"allAreas":return t?.documentId&&m?.area?`${m?.area}`:void 0;case"allDocuments":return m?.document?`${m?.document}`:void 0;case"allLocations":return m?.location?`${m?.location}`:void 0;case"allFolders":return m?.folder?`${m?.folder}`:void 0;case"folder":return m?.folder&&t.folderId?`${m?.folder}/${t.folderId}`:void 0;case"documentUserAccess":return t?.documentId&&t?.id&&m?.documentUsers?`${m?.documentUsers}/${t?.id}`:void 0;case"reaction":return t?.documentId&&t?.id&&m?.reaction?`${m?.reaction}/${t?.id}`:void 0;case"allReactions":return t?.documentId&&m?.reaction?`${m?.reaction}`:void 0;case"recorder":return t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}/${t?.id}`:void 0;case"allRecorders":return t?.documentId&&m?.recorder?`${m?.recorder}`:void 0;case"recorderTrackEvent":return t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}/${t?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return t?.documentId&&m?.document?`${m?.document}/${t?.documentId}`:void 0;case"apiKeyMetadata":return a?`apiKey/${a}`:void 0;case"organizationMetadata":return m?.organization?`${m?.organization}`:void 0;case"documentIam":case"documentMetadata":return t?.documentId&&m?.document?`${m?.document}/${t?.documentId}`:void 0;case"folderMetadata":return t?.folderId&&m?.folder?`${m?.folder}/${t?.folderId}`:void 0;case"locationMetadata":return t?.documentId&&m?.location&&t?.id?`${m?.location}/${t?.id}`:void 0;case"documentUser":return t?.documentId&&t?.id&&m?.documentUsers?`${m?.documentUsers}/${t?.id}`:void 0;case"allDocumentUsers":return m?.users?`${m?.users}`:void 0;case"allFolderUsers":return m?.users?`${m?.users}`:void 0;case"allOrganizationGroups":return m?.organizationGroups?`${m?.organizationGroups}`:void 0;case"allOrganizationUsers":return m?.users?`${m?.users}`:void 0;case"notificationViewsTimestamp":return t?.documentId&&t?.id&&m?.notificationViews?`${m?.notificationViews}/${t?.id}`:void 0;case"allDocumentViews":return t?.documentId&&m?.documentViews?`${m?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return t?.documentId&&t?.id&&m?.documentViews?`${m?.documentViews}/${t?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return t?.documentId&&t?.id&&m?.locationViews?`${m?.locationViews}/${t?.id}`:void 0;case"allLocationViews":return t?.documentId&&m?.locationViews?`${m?.locationViews}`:void 0;case"allDocNotifications":return t?.documentId&&m?.docNotification?`${m?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&m?.docNotification?`${m?.docNotification}/${t?.id}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&m?.notificationUsers?`${m?.notificationUsers}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${t?.id}`:void 0;case"allUserNotifications":return t?.userId&&m?.notificationUsers?`${m?.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:c,organizationId:d}=t;d||(d=i?.organizationId);let m=new bm({apiKey:a,documentId:c?`${c}`:"",organizationId:d?`${d}`:""});switch(e){case"userConfig":return t?.userId&&t?.documentId&&m?.userConfig?`${m?.userConfig}/${t?.userId}/${N.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${t?.documentId}`:void 0;case"allComments":return!l&&t?.documentId&&m?.comment?`${m?.comment}`:void 0;case"allGlobalContacts":return t?.documentId&&m?.globalContacts?`${m?.globalContacts}`:void 0;case"globalContacts":return t?.documentId&&t?.userId&&m?.globalContacts?`${m?.globalContacts}${t?.userId}`:void 0;case"groupContacts":return t?.documentId&&t?.groupId&&m?.groupContacts?`${m?.groupContacts}${t?.groupId}`:void 0;case"groupContactsUser":return t?.documentId&&t?.groupId&&t?.userId&&m?.groupContacts?`${m?.groupContacts}${t?.groupId}/${t?.userId}`:void 0;case"allLoginContacts":return t?.documentId&&t?.userId&&m?.logins?`${m?.logins}${t?.userId}/contacts`:void 0;case"allLogins":return t?.documentId&&m?.logins?`${m?.logins}`:void 0;case"logins":return t?.documentId&&t?.userId&&m?.logins?`${m?.logins}${t?.userId}`:void 0;case"customerMetadata":return m?.customerMetadata?`${m?.customerMetadata}`:void 0;case"allArrows":return t?.documentId&&m?.arrow?`${m?.arrow}`:void 0;case"arrow":return t?.documentId&&m?.arrow&&t.id?`${m?.arrow}${t.id}`:void 0;case"allCursors":return t?.documentId&&m?.cursor?`${m?.cursor}`:void 0;case"cursor":return t?.documentId&&m?.cursor&&t.id?`${m?.cursor}${t.id}`:void 0;case"flockUser":return t?.documentId&&m?.flock&&t.id?`${m?.flock}users/${t.id}`:void 0;case"flockSession":return t?.documentId&&m?.flock&&t.id?`${m?.flock}sessions/${t.id}`:void 0;case"allHuddleAttendees":return t?.documentId&&m?.huddle?`${m?.huddle}attendees`:void 0;case"huddleAttendee":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}attendees/${t.id}`:void 0;case"huddleAttendeeState":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}attendees/${t.id}/state`:void 0;case"allHuddleInvitees":return t?.documentId&&m?.huddle?`${m?.huddle}invitees`:void 0;case"huddleConnection":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}connections/${t.id}`:void 0;case"huddleIceCandidate":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}iceCandidates/${t.id}`:void 0;case"allHuddleIceCandidates":return t?.documentId&&m?.huddle?`${m?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return t?.documentId&&m?.huddle?`${m?.huddle}messages`:void 0;case"huddleMessage":return t?.documentId&&m?.huddle&&t.id?`${m?.huddle}messages/${t.id}`:void 0;case"allLiveStates":return t?.documentId&&m?.liveState?`${m?.liveState}`:void 0;case"allLiveStateCustoms":return t?.documentId&&m?.liveState?`${m?.liveState}custom`:void 0;case"liveStateCustom":return t?.documentId&&m?.liveState&&t?.id?`${m?.liveState}custom/${t.id}`:void 0;case"liveStateSingleEditorMode":return t?.documentId&&m?.liveStateSingleEditorMode?`${m?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return t?.documentId&&m?.liveState?`${m?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return t?.documentId&&m?.liveState?`${m?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return t?.documentId&&m?.liveState&&t?.id?`${m?.liveState}default/autoSyncState/history/${t.id}`:void 0;case"presence":return t?.documentId&&m?.presence&&t?.userId?`${m?.presence}${t?.userId}`:void 0;case"allPresence":return t?.documentId&&m?.presence?`${m?.presence}`:void 0;case"workspaceIam":return m?.workspaceIam?`${m?.workspaceIam}`:void 0;case"selection":return t?.documentId&&m?.selection&&t?.userId?`${m?.selection}${t?.userId}`:void 0;case"allSelections":return t?.documentId&&m?.selection?`${m?.selection}`:void 0;case"syncVideoPlayer":return t?.documentId&&m?.syncVideoPlayer?`${m?.syncVideoPlayer}`:void 0;case"allTags":return t?.documentId&&m?.tag?`${m?.tag}`:void 0;case"tag":return t?.documentId&&m?.tag&&t?.id?`${m?.tag}${t?.id}`:void 0;case"userContactUs":return t?.documentId&&m?.userContactUs?`${m?.userContactUs}`:void 0;case"userFeedback":return t?.documentId&&m?.userFeedback?`${m?.userFeedback}`:void 0;case"userReportBug":return t?.documentId&&m?.userReportBugs?`${m?.userReportBugs}`:void 0;case"comment":return!l&&t?.documentId&&t?.id&&m?.comment?`${m?.comment}${t?.id}`:void 0;case"allMultiThreads":return!l&&t?.documentId&&m?.multiThread?`${m?.multiThread}`:void 0;case"crdt":return!l&&t?.documentId&&m?.crdt?`${m?.crdt}`:void 0;case"crdtData":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/data`:void 0;case"crdtSyncState":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/state`:void 0;case"crdtSyncPresence":return t?.documentId&&t.userId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/presence/${t.userId}`:void 0;case"allCrdtSyncPresence":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/sync/presence`:void 0;case"crdtPresence":return t?.documentId&&t.userId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/presence/${t.userId}`:void 0;case"allCrdtPresence":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/presence`:void 0;case"crdtVersion":return t?.documentId&&m?.crdt&&t?.id&&t?.versionId?`${m?.crdt}/${t?.id}/versions/${t?.versionId}`:void 0;case"crdtVersions":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/versions`:void 0;case"crdtMessages":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/messages`:void 0;case"crdtMessage":return t?.documentId&&m?.crdt&&t?.id&&t?.messageId?`${m?.crdt}/${t?.id}/messages/${t?.messageId}`:void 0;case"crdtSnapshot":return t?.documentId&&m?.crdt&&t?.id?`${m?.crdt}/${t?.id}/snapshot`:void 0;case"multiThread":return!l&&t?.documentId&&t?.id&&m?.multiThread?`${m?.multiThread}${t?.id}`:void 0;case"allLastNotificationTimestamp":return!l&&m?.organizationNotificationsLastNotificationTimestamp?`${m?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!l&&t?.id&&m?.organizationNotificationsLastNotificationTimestamp?`${m?.organizationNotificationsLastNotificationTimestamp}${t?.id}`:void 0;case"documentIam":return!l&&t?.documentId&&m?.documentIam?`${m?.documentIam}`:void 0;case"allDocuments":return!l&&m?.docs&&t?.documentId?`${m?.docs}/${t?.documentId}/${N.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!l&&t?.documentId&&m?.area?`${m?.area}`:void 0;case"area":return!l&&t?.id&&m?.area?`${m?.area}${t?.id}`:void 0;case"folder":return!l&&t?.folderId&&m?.folder?`${m?.folder}${t?.folderId}`:void 0;case"documentUserAccess":return!l&&t?.id&&m?.documentIam?`${m?.documentIam}users/${t?.id}`:void 0;case"documentUser":return!l&&t?.documentId&&t?.id&&m?.documentIam?`${m?.documentIam}users/${t?.id}`:void 0;case"allDocumentUsers":return!l&&t?.documentId&&m?.documentIam?`${m?.documentIam}users/`:void 0;case"allOrganizationGroups":return!l&&m?.organizationGroups?`${m?.organizationGroups}`:void 0;case"allOrganizationUsers":return!l&&m?.organizationIam?`${m?.organizationIam}users/`:void 0;case"reaction":return!l&&t?.id&&m?.reaction?`${m?.reaction}${t?.id}`:void 0;case"allReactions":return!l&&t?.documentId&&m?.reaction?`${m?.reaction}`:void 0;case"recorder":return!l&&t?.documentId&&t?.id&&m?.recorder?`${m?.recorder}${t?.id}`:void 0;case"allRecorders":return!l&&t?.documentId&&m?.recorder?`${m?.recorder}`:void 0;case"organizationMetadata":return!l&&m?.organizationMetadata?`${m?.organizationMetadata}`:void 0;case"heartbeat":return t?.id&&m?.heartbeat?`${m?.heartbeat}${t?.id}`:void 0;case"allHeartbeats":return m?.heartbeat?`${m?.heartbeat}`:void 0;case"heartbeatByDocument":return t?.id&&m?.heartbeatByDocument?`${m?.heartbeatByDocument}${t?.id}`:void 0;case"allHeartbeatsByDocument":return m?.heartbeatByDocument?`${m?.heartbeatByDocument}`:void 0;case"documentAccessType":return!l&&m?.documentIam?`${m?.documentIam}`:void 0;case"documentMetadata":return!l&&t?.documentId&&m?.metadata?`${m?.metadata}`:void 0;case"allDocumentViews":return!l&&t?.documentId&&m?.views?`${m?.views}documentViews/`:void 0;case"documentViews":return!l&&t?.documentId&&t?.id&&m?.views?`${m?.views}documentViews/${t?.id}`:void 0;case"allLocationViews":return!l&&t?.documentId&&m?.views?`${m?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!l&&t?.id&&t?.user&&m?.views?`${m?.views}notification/${t?.id}/views/${t?.user}`:void 0;case"documentUsersViews":return!l&&t?.id&&t?.user&&t?.date&&m?.views?`${m?.views}documentViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"documentMetadataViews":return!l&&t?.id&&m?.views?`${m?.views}documentViews/${t?.id}/metadata`:void 0;case"documentDayViews":return!l&&t?.id&&t?.date&&t?.user&&m?.views?`${m?.views}documentViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"locationViews":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}/location`:void 0;case"location":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}`:void 0;case"locationUsersViews":return!l&&t?.id&&t?.user&&t?.date&&m?.views?`${m?.views}locationViews/${t?.id}/users/${t?.user}/${t?.date}`:void 0;case"locationMetadataViews":return!l&&t?.id&&m?.views?`${m?.views}locationViews/${t?.id}/metadata`:void 0;case"locationDayViews":return!l&&t?.id&&t?.date&&t?.user&&m?.views?`${m?.views}locationViews/${t?.id}/day/${t?.date}/${t?.user}`:void 0;case"docNotificationViews":case"docNotification":return t?.documentId&&t?.id&&m?.organizationNotificationsWithDocumentId?`${m?.organizationNotificationsWithDocumentId}${t?.id}`:void 0;case"allDocNotifications":return t?.documentId&&m?.organizationNotificationsWithDocumentId?`${m?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return t?.userId&&m?.organizationNotificationsUsers?`${m?.organizationNotificationsUsers}${t?.userId}`:void 0;case"userNotificationViews":case"userNotification":return t?.userId&&t?.id&&m?.organizationNotificationsUsers?`${m?.organizationNotificationsUsers}${t?.userId}/${t?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${e}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(i){return X(this,arguments,function*({data:e,feature:t}){try{if(e&&e?.length>0)switch(t){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let a=lt(),l=o1.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ti.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=lt(),l=i1.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ni.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=lt(),l=a1.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:ri.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 X(this,arguments,function*({feature:e,data:t,shouldAwait:i=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:l=!1,shouldNotificationResolverAwait:c=!1,shouldActivityResolverAwait:d=!1,shouldReactionResolverAwait:m=!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=lt(),M=ys.GET_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:vi.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=lt(),M=LK.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:yl.FORMAT_RESPONSE,moduleName:M,source:"internal",payload:{notificationIds:I,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??"",shouldNotificationResolverAwait:c}}),c?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=lt(),M=o1.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:ti.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=lt(),q=UK.GET_ACTIVITIES;this.coreActionsService.triggerAction(tt.ACTIVITY_RESOLVER,{event:Y.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:yc.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=lt(),q=i1.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.RESOLVE_REACTION_ANNOTATIONS,moduleName:q,source:"internal",payload:{reactionAnnotationIds:M,organizationId:A,shouldReactionResolverAwait:m}}),m?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=lt(),q=a1.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),ce(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,c])=>(a[l]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,i),a),{}):e;case"allDocNotifications":case"allUserNotifications":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((a,[l,c])=>(a[l]=this.notificationUtilsService.mergeLocationWithNotification(c,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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${e}:`,i),ce(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}}),_t(Kt))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${t}:`,i),ce(e)}}handleDataStripping(l){return X(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(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{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 c=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,c);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(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),t}}modifyAndSetData(l){return X(this,arguments,function*({feature:e,data:t,subscriber:i,operation:a=null}){try{let c=yield this.modifyData({feature:e,data:t});i.next({data:c,operation:a})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}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 X(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 X(this,arguments,function*({feature:e,data:t,observablesCache:i,eventType:a,id:l,operation:c=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:c})):i[A]?.subject?.next({data:y(h({},M?.data),{[t?.annotationId]:t}),operation:c})}),null}catch(m){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",m),null}})}handleCommentEncryption(c){return X(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 X(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)(K(gS),K(fbe),K(Cbe),K(Cm),K(bbe),K(tr),K(_be),K(UL),K(VL),K(k),K(kbe),K(jL),K(Ibe),K(NL),K(Tp),K(Ebe),K(wbe),K(An),K(st),K(rl),K(Xc),K(ol),K(_m),K(Dp))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Tbe=(()=>{let o=class o{constructor(e,t,i){this.configService=e,this.authService=t,this.loggingService=i,this.firestore$=new Se(null);try{gn([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Ge(([a,l])=>!!a&&!!l),ut(1)).subscribe(([a,l,c])=>{if(a&&l&&a?.firebaseOptions?.storeDbId){try{let u=sessionStorage?.getItem("veltFirestoreLogLevel")||On?.firebaseLogLevel||"silent";bX(u)}catch(u){this.loggingService.catch("Error in FirestoreService setLogLevel: ",u)}let d=wp.getFirestoreProdDbName(l,a.firebaseOptions),m=this.configService.getProxyConfig();if(m?.v2DbHost){let u={host:m.v2DbHost,ssl:!0};m.forceLongPolling?u.experimentalForceLongPolling=!0:u.experimentalAutoDetectLongPolling=!0,c&&(u.localCache=tQ({tabManager:nQ()}));try{this.firestore$.next(wL(ql(),u,d))}catch(_){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",_),this.firestore$.next(lS(d))}}else if(c)try{let u=ql(),_=wL(u,{localCache:tQ({tabManager:nQ()})},d);this.firestore$.next(_)}catch{this.firestore$.next(lS(d))}else this.firestore$.next(lS(d))}},a=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let e=this.getFirestoreValue()||lS("DocumentIdDb");if(e){let t=wO(e,"generateDocumentId");return sS(t).id}return}catch(e){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",e);return}}};o.\u0275fac=function(t){return new(t||o)(K(Ft),K(qe),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var yn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,B){this.activityUtilsService=e,this.authService=t,this.commonDbUtilsService=i,this.coreActionsService=a,this.loggingService=l,this.firestoreService=c,this.databaseService=d,this.configService=m,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=Cg(ae,be=>{let re=be.val();this.offset=re})}})),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 X(this,null,function*(){try{if(this.db){let i=Ur(this.db,e);return bc(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){gn([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ge(([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,c){return X(this,null,function*(){try{if(!t){this.loggingService.warn(`%c[WB] No properties found for ${e}`,"color: red;");return}return this.subscribeToServices(u=>X(this,[u],function*({db:d,firestore:m}){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")&&m&&_&&(M=sS(m,`${_}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:A,firestoreRef:M,data:a,firestorePath:_}),c&&c({firestoreAvailable:!!m})}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 X(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,c),this.performDatabaseOperation(e,i,m=>X(this,null,function*(){if(m.dbRef){let u=this.commonDbUtilsService.formatData({feature:e,data:m.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Qf(m.dbRef,()=>JSON.parse(JSON.stringify(u))):yield e0(m.dbRef,JSON.parse(JSON.stringify(u)))}try{if(m.firestoreRef&&m.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:m.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:c?.actionType,commentId:c?.targetAnnotationData?.commentId??i?.targetCommentId});if(e==="comment"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ti.SET_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:c?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:c?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:m.firestorePath??"",extraData:c,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.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:m.firestorePath??""}))}else if(e==="recorder"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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 aQ(this.firestore,q=>X(this,null,function*(){q.set(m.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield lQ(m.firestoreRef,u)}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${e}`,u)}}),t,l,a))}catch(m){this.loggingService.catch(`Error in setData for ${e}`,m)}})}updateData(d){return X(this,arguments,function*({feature:e,data:t,properties:i,callback:a,errorCallback:l,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${e}`,"color: green;"),this.shouldUseFirestore()&&t?.metadata&&!t?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:e,data:t,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(e,c),this.performDatabaseOperation(e,i,m=>X(this,null,function*(){if(m.dbRef&&!i?.skipRtdb){let u=this.commonDbUtilsService.formatData({feature:e,data:m.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield Qf(m.dbRef,_=>{let I;return i?.rtdbTransactionCallback?I=i.rtdbTransactionCallback(_,u):I=this.commonDbUtilsService.rtdbDefaultTransactionCallback(_,u),JSON.parse(JSON.stringify(I))}):yield x8(m.dbRef,JSON.parse(JSON.stringify(u)))}try{if(m.firestoreRef&&m.data&&!i?.skipFirestore){let u=this.commonDbUtilsService.formatData({feature:e,data:m.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:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(e==="comment"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ti.UPDATE_DATA,source:"internal",payload:{strippedData:_,originalData:I,eventType:A,commentId:c?.targetAnnotationData?.commentId}}),_&&(M=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:_,eventType:A,commentId:c?.targetAnnotationData?.commentId},B)),I&&(M?.isSuccess||M===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:I,firestorePath:m.firestorePath??"",extraData:c,metadata:i?.metadata}))}else if(e==="reaction"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ni.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:m.firestorePath??""}))}else if(e==="recorder"){let M=null,B=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,methodName:ri.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 aQ(this.firestore,q=>X(this,null,function*(){q.set(m.firestoreRef,JSON.parse(JSON.stringify(I)))})))}else yield lQ(m.firestoreRef,u,{merge:!0})}}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${e}`,u)}}),t,l,a))}catch(m){this.loggingService.catch(`Error in updateData for ${e}`,m)}})}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(c){return X(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=>X(this,null,function*(){d.dbRef&&(yield k8(d.dbRef));try{if(d.firestoreRef&&!t?.skipFirestore)if(e==="comment"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.COMMENT_RESOLVER,{event:Y.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ti.DELETE_DATA,source:"internal",payload:{commentAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE",metadata:t?.metadata}))}else if(e==="reaction"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.REACTION_RESOLVER,{event:Y.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ni.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:d.firestorePath??"",eventType:"DELETE"}))}else if(e==="recorder"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.RECORDER_RESOLVER,{event:Y.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:ri.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:t?.id??"",metadata:t?.metadata}}),m=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(t?.id??"",t?.metadata,u),(m?.isSuccess||m===null)&&(yield OL(d.firestoreRef))}else if(e==="userNotification"){let m=null,u=lt();this.coreActionsService.triggerAction(tt.NOTIFICATION_RESOLVER,{event:Y.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:yl.DELETE_DATA,source:"internal",payload:{notificationId:t?.id??"",organizationId:t?.organizationId??""}}),m=yield this.notificationResolverService.deleteNotification(String(t?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(m?.isSuccess||m===null)&&(yield OL(d.firestoreRef))}else yield OL(d.firestoreRef)}catch(m){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${e}`,m)}}),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=lt()),e||"noDocumentId"}catch(e){return this.loggingService.catch("Error in generateFirestoreDocumentId:",e),lt()||"noDocumentId"}}queryData(i){return X(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 X(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=wO(this.firestore,i);t?.useCollectionGroup&&(a=rQ(this.firestore,i));let l=t?.firestoreQuery??[],c=iQ(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];if(t?.getCount)try{let d=yield XCe(c).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${e}`,m),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 ebe(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${e}`,u),null));if(!d)return[];let m=d.docs.map(u=>u.data());try{return yield this.commonDbUtilsService.modifyData({feature:e,data:m})}catch(u){return this.loggingService.catch(`Error in modifyData for ${e}`,u),m}}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 X(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??[],c=Yq(a,...l);if(!this.authService.getUser()&&!t?.skipUserCheck)return[];let d=yield zq(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,u),null));if(!d)return[];let m=d.val();return m?t?.skipObjectValues?m:Object.values(m??{}):[]}catch(a){return this.loggingService.catch(`Error in RTDB query for ${e}:`,a),[]}})}getData(i){return X(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 c=yield QCe(sS(this.firestore,l)).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDoc for ${e}`,m),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:m})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No document found at ${l}`),{};let d=c.data();return t?.field?d?.[t.field]??{}:d??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${e}:`,c),{}}}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 c=yield zq(Ur(this.db,l)).catch(m=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${e}`,m),this.commonDbUtilsService.getErrorForGetRequests({feature:e,error:m})));if(c){if(c?.errorCode)return c}else return this.loggingService.warn(`[WB] No data found at ${l}`),{};let d=c.val();return t?.field?d?.[t.field]??{}:d??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${e}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(a){return this.loggingService.catch("Unexpected error in getData:",a),{}}})}dbListener({feature:e,properties:t}){let i=this.shouldUseFirestore();t?.skipFirestore&&(i=!1);let a=`${e}-${JSON.stringify(t)}`;return gn([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Ge(l=>!!l))]).pipe(Ge(([l,c])=>l?i&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${e}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${e}`),!1)),ye(([l,c])=>{try{if(i&&c){if(!!!this.observablesCache[a]){this.observablesCache[a]={subject:new Se({}),count:0};let u=this.handleFirestoreListener(e,t,c).subscribe(_=>{this.observablesCache[a]?.subject?.next(_)},_=>this.observablesCache[a]?.subject?.error(_));this.firestoreSubscriptions[a]=u}return new Vt(m=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>m.next(_),_=>m.error(_),()=>m.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 Vt(m=>{let u=this.observablesCache[a]?.subject?.subscribe(_=>m.next(_),_=>m.error(_),()=>m.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 ce({})}catch(d){return this.loggingService.catch(`Error setting up listener for ${e}:`,d),ce({})}}),qh(()=>{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 Vt(c=>{let d=t.isCollection?this.setupCollectionListener(i,a,e,c,t):this.setupDocumentListener(i,a,e,c,t);return()=>{c.complete(),c.unsubscribe(),d(),this.observablesCache[l]?.subject?.complete(),this.observablesCache[l]?.subject?.unsubscribe(),delete this.observablesCache[l]}}).pipe(ye(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:e,data:c})),ye(c=>["allComments","allUserNotifications"].includes(e)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:e}):ce(c)),ye(c=>["allReactions"].includes(e)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:e}):ce(c)),ye(c=>["allRecorders"].includes(e)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:e}):ce(c)),_t(Kt)):(this.loggingService.warn(`[WB] No firestore path found for ${e} and key ${l}`),ce({}))}setupCollectionListener(e,t,i,a,l){let c=`${i}-${JSON.stringify(l)}`,d=wO(e,t);if(l?.useCollectionGroup&&(d=rQ(e,t)),l?.useQuery&&l?.firestoreQuery){let _=l?.firestoreQuery??[];d=iQ(d,..._)}let m=!0,u=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",t,"feature:",i,"properties:",JSON.stringify(l??"nil")),oQ(d,_=>{try{let I=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),A=null,M=!1;_?.docChanges()?.length?_.docChanges().forEach(B=>{["allComments","allReactions","allRecorders"].includes(i)&&!m&&B.type!=="removed"&&u.push(B.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:B,cache:this.observablesCache[c]?.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})),m=!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 c=sS(e,t);return oQ(c,d=>{try{let m=d.data()||{};l?.field&&(m=m?.[l?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:m,subscriber:a,operation:null})}catch(m){this.handleListenerError(m,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}`),ce({});let l=Ur(i,a);if(t?.useQuery&&t?.rtdbQuery){let c=t?.rtdbQuery??[];l=Yq(l,...c)}return this.objectValFromChildEvents(l,e).pipe(Jn(c=>(this.loggingService.catch(`RTDB listener error for ${e}:`,c),ce({}))),ge(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((m,[u,_])=>(m[u]=this.commonDbUtilsService.addMetadata(_,t),m),{}):this.commonDbUtilsService.addMetadata(c,t))),ye(c=>this.commonDbUtilsService.modifyData({feature:e,data:c})),ye(c=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:e,data:c}),operation:null})))))}pushData(a){return X(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=>X(this,null,function*(){if(l.dbRef){let c=y8(l.dbRef);yield e0(c,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 Vt(a=>{let l=null,c=!1,d=({db:m})=>{if(!m||c||!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(m,u),A=!1,M=ae=>{try{let be=ae.val();if(A){if(i!=null&&be?.timestamp!=null&&be.timestamp<=i)return;a.next(be)}}catch(be){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${e}:`,be)}},B=ae=>{try{this.loggingService.catch(`streamChildAdded error for ${e}:`,ae),a.error(ae)}catch(be){this.loggingService.catch(`streamChildAdded onError handler error for ${e}:`,be)}};qq(I,M,B);let q=Cg(I,()=>{A=!0},B,{onlyOnce:!0});l=()=>{try{q&&typeof q=="function"&&q(),OD(I,"child_added",M)}catch(ae){this.loggingService.catch(`streamChildAdded cleanup error for ${e}:`,ae)}}};return this.subscribeToServices(d),()=>{c=!0,l&&l()}})}catch(a){return this.loggingService.catch(`Error in streamChildAdded for ${e}`,a),ce(null)}}objectValFromChildEvents(e,t){return new Vt(i=>{let a={},l=!1,c=null,d=B=>{try{this.loggingService.catch(`Realtime DB listener error for ${t}:`,B),i.error(B)}catch{}},m=B=>{try{if(!sr(B,c)){let q=JSON.parse(JSON.stringify(B));c=q,i.next(q)}}catch{}},u=B=>{try{B.key&&(a[B.key]=B.val(),l&&m(h({},a)))}catch{}},_=B=>{try{B.key&&(a[B.key]=B.val(),l&&m(h({},a)))}catch{}},I=B=>{try{B.key&&(delete a[B.key],l&&m(h({},a)))}catch{}},A=B=>{try{if(!l){let q=a&&typeof a=="object"?JSON.parse(JSON.stringify(a)):{};c=q,i.next(q),l=!0}}catch{}};qq(e,u,d),_me(e,_,d),Sme(e,I,d);let M=Cg(e,A,d,{onlyOnce:!0});return()=>{try{M&&typeof M=="function"&&M(),OD(e,"child_added",u),OD(e,"child_changed",_),OD(e,"child_removed",I)}catch{}}})}};o.\u0275fac=function(t){return new(t||o)(K(gS),K(qe),K(vd),K(tr),K(k),K(Tbe),K($n),K(Ft),K(st),K(An),K(rl),K(Xc),K(ol),K(_m))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Sm=(()=>{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 c=e;for(let d of a){let m=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`${d}_${t}`;c=c.replace(new RegExp(`\\bid="${m}"`,"g"),`id="${u}"`),c=c.replace(new RegExp(`url\\(#${m}\\)`,"g"),`url(#${u})`),c=c.replace(new RegExp(`href="#${m}"`,"g"),`href="#${u}"`)}return c}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"/>