@veltdev/sdk-staging 6.0.0 → 6.0.1

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 (56) hide show
  1. package/chunk-26SHKRTG.js +1 -0
  2. package/{chunk-FXK7BWOQ.js → chunk-3YCIOKO7.js} +1 -1
  3. package/{chunk-OZMOWJWG.js → chunk-4O7F5WPS.js} +1 -1
  4. package/{chunk-EIIBHBQX.js → chunk-6MGKRXSY.js} +1 -1
  5. package/{chunk-S3KLTU2O.js → chunk-7M7HPFJW.js} +1 -1
  6. package/{chunk-UVG3AHTE.js → chunk-BP5ABAKN.js} +1 -1
  7. package/{chunk-RSPIT2S4.js → chunk-CMV6XYEA.js} +1 -1
  8. package/{chunk-4MGSKBFZ.js → chunk-CN3MG4V7.js} +1 -1
  9. package/{chunk-AVNXQEE2.js → chunk-DVLF6ZJF.js} +1 -1
  10. package/{chunk-YFYJFOMT.js → chunk-EWNEUCZN.js} +1 -1
  11. package/{chunk-62665UII.js → chunk-FXVG7I7B.js} +1 -1
  12. package/{chunk-6SB63H3W.js → chunk-JD2Q4WUT.js} +1 -1
  13. package/{chunk-5YVVMUVJ.js → chunk-JMH4W4CX.js} +1 -1
  14. package/{chunk-42DJQDO6.js → chunk-KPEMFTQE.js} +1 -1
  15. package/{chunk-OPJU6Y6N.js → chunk-LSGQWTXT.js} +1 -1
  16. package/{chunk-POBWY53V.js → chunk-MJHVVJAE.js} +1 -1
  17. package/{chunk-UGCJET7Y.js → chunk-NWDWX5YO.js} +1 -1
  18. package/{chunk-CI2JGL4P.js → chunk-O7QMGDXD.js} +1 -1
  19. package/{chunk-SYUQPGKV.js → chunk-OMM2AMDX.js} +1 -1
  20. package/{chunk-3CWPPM3P.js → chunk-OO7EO3BV.js} +1 -1
  21. package/{chunk-BPPXBXFT.js → chunk-P6UVM6B7.js} +1 -1
  22. package/{chunk-PVOJRXAC.js → chunk-PNALREKY.js} +1 -1
  23. package/{chunk-IE3AYTRD.js → chunk-Q3SFRIYZ.js} +1 -1
  24. package/{chunk-EPT5TVX4.js → chunk-QEJJ3QNA.js} +1 -1
  25. package/{chunk-WOT7KXUQ.js → chunk-QYUV5PXV.js} +1 -1
  26. package/{chunk-CVMNWHT4.js → chunk-RF3TL6SQ.js} +6 -6
  27. package/chunk-THHKSZTD.js +1 -0
  28. package/{chunk-UCTOPWFQ.js → chunk-W6OGMNHQ.js} +1 -1
  29. package/{chunk-AE6AKOBL.js → chunk-WQRY6Y6C.js} +1 -1
  30. package/{chunk-QD4B4F67.js → chunk-WW7AGQRC.js} +1 -1
  31. package/{chunk-ZOLCVAWT.js → chunk-XDHXV3V6.js} +1 -1
  32. package/{chunk-QX6IGTVL.js → chunk-YBCNVNZM.js} +1 -1
  33. package/{chunk-SKH4QRW2.js → chunk-YQEMM6AB.js} +1 -1
  34. package/package.json +1 -1
  35. package/velt-activity-log.js +1 -1
  36. package/velt-area.js +1 -1
  37. package/velt-arrow.js +1 -1
  38. package/velt-comment.js +6 -6
  39. package/velt-crdt.js +1 -1
  40. package/velt-cursor.js +1 -1
  41. package/velt-huddle.js +1 -1
  42. package/velt-live-state-sync.js +1 -1
  43. package/velt-notification.js +1 -1
  44. package/velt-presence.js +1 -1
  45. package/velt-reaction.js +1 -1
  46. package/velt-recorder.js +1 -1
  47. package/velt-rewriter.js +1 -1
  48. package/velt-selection.js +1 -1
  49. package/velt-tag.js +1 -1
  50. package/velt-user-invite.js +1 -1
  51. package/velt-user-request.js +1 -1
  52. package/velt-video-player.js +1 -1
  53. package/velt-views.js +1 -1
  54. package/velt.js +2 -2
  55. package/chunk-ADSEZJIT.js +0 -1
  56. package/chunk-PRGWBNVO.js +0 -1
@@ -164,4 +164,4 @@ This typically indicates that your device does not have a healthy Internet conne
164
164
  `+e.join(`
165
165
  `)+`
166
166
  )`}copy(e,n){let t=new r;return t.comparator=this.comparator,t.keyedMap=e,t.sortedSet=n,t}};var wy=class{constructor(){this.fa=new St(se.comparator)}track(e){let n=e.doc.key,t=this.fa.get(n);t?e.type!==0&&t.type===3?this.fa=this.fa.insert(n,e):e.type===3&&t.type!==1?this.fa=this.fa.insert(n,{type:t.type,doc:e.doc}):e.type===2&&t.type===2?this.fa=this.fa.insert(n,{type:2,doc:e.doc}):e.type===2&&t.type===0?this.fa=this.fa.insert(n,{type:0,doc:e.doc}):e.type===1&&t.type===0?this.fa=this.fa.remove(n):e.type===1&&t.type===2?this.fa=this.fa.insert(n,{type:1,doc:t.doc}):e.type===0&&t.type===1?this.fa=this.fa.insert(n,{type:2,doc:e.doc}):ae(63341,{At:e,ga:t}):this.fa=this.fa.insert(n,e)}pa(){let e=[];return this.fa.inorderTraversal((n,t)=>{e.push(t)}),e}},$h=class r{constructor(e,n,t,i,o,s,a,c,l){this.query=e,this.docs=n,this.oldDocs=t,this.docChanges=i,this.mutatedKeys=o,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=c,this.hasCachedResults=l}static fromInitialDocuments(e,n,t,i,o){let s=[];return n.forEach(a=>{s.push({type:0,doc:a})}),new r(e,n,by.emptySet(n),s,t,i,!0,!1,o)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Yy(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let n=this.docChanges,t=e.docChanges;if(n.length!==t.length)return!1;for(let i=0;i<n.length;i++)if(n[i].type!==t[i].type||!n[i].doc.isEqual(t[i].doc))return!1;return!0}};var LL=class{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}},ML=class{constructor(){this.queries=PH(),this.onlineState="Unknown",this.Da=new Set}terminate(){(function(n,t){let i=he(n),o=i.queries;i.queries=PH(),o.forEach((s,a)=>{for(let c of a.wa)c.onError(t)})})(this,new Q(W.ABORTED,"Firestore shutting down"))}};function PH(){return new Yi(r=>CW(r),Yy)}function bM(r,e){return I(this,null,function*(){let n=he(r),t=3,i=e.query,o=n.queries.get(i);o?!o.Sa()&&e.ba()&&(t=2):(o=new LL,t=e.ba()?0:1);try{switch(t){case 0:o.ya=yield n.onListen(i,!0);break;case 1:o.ya=yield n.onListen(i,!1);break;case 2:yield n.onFirstRemoteStoreListen(i)}}catch(s){let a=OM(s,`Initialization of query '${mh(e.query)}' failed`);return void e.onError(a)}n.queries.set(i,o),o.wa.push(e),e.va(n.onlineState),o.ya&&e.Ca(o.ya)&&LM(n)})}function wM(r,e){return I(this,null,function*(){let n=he(r),t=e.query,i=3,o=n.queries.get(t);if(o){let s=o.wa.indexOf(e);s>=0&&(o.wa.splice(s,1),o.wa.length===0?i=e.ba()?0:1:!o.Sa()&&e.ba()&&(i=2))}switch(i){case 0:return n.queries.delete(t),n.onUnlisten(t,!0);case 1:return n.queries.delete(t),n.onUnlisten(t,!1);case 2:return n.onLastRemoteStoreUnlisten(t);default:return}})}function dse(r,e){let n=he(r),t=!1;for(let i of e){let o=i.query,s=n.queries.get(o);if(s){for(let a of s.wa)a.Ca(i)&&(t=!0);s.ya=i}}t&&LM(n)}function hse(r,e,n){let t=he(r),i=t.queries.get(e);if(i)for(let o of i.wa)o.onError(n);t.queries.delete(e)}function LM(r){r.Da.forEach(e=>{e.next()})}var PL,xH;(xH=PL||(PL={})).Fa="default",xH.Cache="cache";var yp=class{constructor(e,n,t){this.query=e,this.Ma=n,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=t||{}}Ca(e){if(!this.options.includeMetadataChanges){let t=[];for(let i of e.docChanges)i.type!==3&&t.push(i);e=new $h(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let n=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),n=!0):this.Ba(e,this.onlineState)&&(this.La(e),n=!0),this.Oa=e,n}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let n=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),n=!0),n}Ba(e,n){if(!e.fromCache||!this.ba())return!0;let t=n!=="Offline";return(!this.options.ka||!t)&&(!e.docs.isEmpty()||e.hasCachedResults||n==="Offline")}Na(e){if(e.docChanges.length>0)return!0;let n=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!n)&&this.options.includeMetadataChanges===!0}La(e){e=$h.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==PL.Cache}};var Ly=class{constructor(e){this.key=e}},My=class{constructor(e){this.key=e}},xL=class{constructor(e,n){this.query=e,this.Ha=n,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=ke(),this.mutatedKeys=ke(),this.Xa=OW(e),this.eu=new by(this.Xa)}get tu(){return this.Ha}nu(e,n){let t=n?n.ru:new wy,i=n?n.eu:this.eu,o=n?n.mutatedKeys:this.mutatedKeys,s=i,a=!1,c=this.query.limitType==="F"&&i.size===this.query.limit?i.last():null,l=this.query.limitType==="L"&&i.size===this.query.limit?i.first():null;if(e.inorderTraversal((u,d)=>{let f=i.get(u),g=Lp(this.query,d)?d:null,p=!!f&&this.mutatedKeys.has(f.key),_=!!g&&(g.hasLocalMutations||this.mutatedKeys.has(g.key)&&g.hasCommittedMutations),T=!1;f&&g?f.data.isEqual(g.data)?p!==_&&(t.track({type:3,doc:g}),T=!0):this.iu(f,g)||(t.track({type:2,doc:g}),T=!0,(c&&this.Xa(g,c)>0||l&&this.Xa(g,l)<0)&&(a=!0)):!f&&g?(t.track({type:0,doc:g}),T=!0):f&&!g&&(t.track({type:1,doc:f}),T=!0,(c||l)&&(a=!0)),T&&(g?(s=s.add(g),o=_?o.add(u):o.delete(u)):(s=s.delete(u),o=o.delete(u)))}),this.query.limit!==null)for(;s.size>this.query.limit;){let u=this.query.limitType==="F"?s.last():s.first();s=s.delete(u.key),o=o.delete(u.key),t.track({type:1,doc:u})}return{eu:s,ru:t,Ds:a,mutatedKeys:o}}iu(e,n){return e.hasLocalMutations&&n.hasCommittedMutations&&!n.hasLocalMutations}applyChanges(e,n,t,i){let o=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let s=e.ru.pa();s.sort((u,d)=>(function(g,p){let _=T=>{switch(T){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return ae(20277,{At:T})}};return _(g)-_(p)})(u.type,d.type)||this.Xa(u.doc,d.doc)),this.su(t),i=i!=null&&i;let a=n&&!i?this.ou():[],c=this.Za.size===0&&this.current&&!i?1:0,l=c!==this.Ya;return this.Ya=c,s.length!==0||l?{snapshot:new $h(this.query,e.eu,o,s,e.mutatedKeys,c===0,l,!1,!!t&&t.resumeToken.approximateByteSize()>0),_u:a}:{_u:a}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({eu:this.eu,ru:new wy,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach(n=>this.Ha=this.Ha.add(n)),e.modifiedDocuments.forEach(n=>{}),e.removedDocuments.forEach(n=>this.Ha=this.Ha.delete(n)),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=ke(),this.eu.forEach(t=>{this.au(t.key)&&(this.Za=this.Za.add(t.key))});let n=[];return e.forEach(t=>{this.Za.has(t)||n.push(new My(t))}),this.Za.forEach(t=>{e.has(t)||n.push(new Ly(t))}),n}uu(e){this.Ha=e.qs,this.Za=ke();let n=this.nu(e.documents);return this.applyChanges(n,!0)}cu(){return $h.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,this.Ya===0,this.hasCachedResults)}},Qh="SyncEngine",FL=class{constructor(e,n,t){this.query=e,this.targetId=n,this.view=t}},kL=class{constructor(e){this.key=e,this.lu=!1}},UL=class{constructor(e,n,t,i,o,s){this.localStore=e,this.remoteStore=n,this.eventManager=t,this.sharedClientState=i,this.currentUser=o,this.maxConcurrentLimboResolutions=s,this.hu={},this.Pu=new Yi(a=>CW(a),Yy),this.Tu=new Map,this.Iu=new Set,this.du=new St(se.comparator),this.Eu=new Map,this.Au=new _p,this.Ru={},this.Vu=new Map,this.mu=Vh.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return this.fu===!0}};function fse(r,e,n=!0){return I(this,null,function*(){let t=Zy(r),i,o=t.Pu.get(e);return o?(t.sharedClientState.addLocalQueryTarget(o.targetId),i=o.view.cu()):i=yield R3(t,e,n,!0),i})}function gse(r,e){return I(this,null,function*(){let n=Zy(r);yield R3(n,e,!0,!1)})}function R3(r,e,n,t){return I(this,null,function*(){let i=yield Sy(r.localStore,Yr(e)),o=i.targetId,s=r.sharedClientState.addLocalQueryTarget(o,n),a;return t&&(a=yield MM(r,e,o,s==="current",i.resumeToken)),r.isPrimaryClient&&n&&Jy(r.remoteStore,i),a})}function MM(r,e,n,t,i){return I(this,null,function*(){r.gu=(d,f,g)=>(function(_,T,D,L){return I(this,null,function*(){let B=T.view.nu(D);B.Ds&&(B=yield EL(_.localStore,T.query,!1).then(({documents:A})=>T.view.nu(A,B)));let w=L&&L.targetChanges.get(T.targetId),F=L&&L.targetMismatches.get(T.targetId)!=null,U=T.view.applyChanges(B,_.isPrimaryClient,w,F);return VL(_,T.targetId,U._u),U.snapshot})})(r,d,f,g);let o=yield EL(r.localStore,e,!0),s=new xL(e,o.qs),a=s.nu(o.documents),c=gp.createSynthesizedTargetChangeForCurrentChange(n,t&&r.onlineState!=="Offline",i),l=s.applyChanges(a,r.isPrimaryClient,c);VL(r,n,l._u);let u=new FL(e,n,s);return r.Pu.set(e,u),r.Tu.has(n)?r.Tu.get(n).push(e):r.Tu.set(n,[e]),l.snapshot})}function mse(r,e,n){return I(this,null,function*(){let t=he(r),i=t.Pu.get(e),o=t.Tu.get(i.targetId);if(o.length>1)return t.Tu.set(i.targetId,o.filter(s=>!Yy(s,e))),void t.Pu.delete(e);t.isPrimaryClient?(t.sharedClientState.removeLocalQueryTarget(i.targetId),t.sharedClientState.isActiveQueryTarget(i.targetId)||(yield Bh(t.localStore,i.targetId,!1).then(()=>{t.sharedClientState.clearQueryState(i.targetId),n&&Gh(t.remoteStore,i.targetId),jh(t,i.targetId)}).catch(ic))):(jh(t,i.targetId),yield Bh(t.localStore,i.targetId,!0))})}function pse(r,e){return I(this,null,function*(){let n=he(r),t=n.Pu.get(e),i=n.Tu.get(t.targetId);n.isPrimaryClient&&i.length===1&&(n.sharedClientState.removeLocalQueryTarget(t.targetId),Gh(n.remoteStore,t.targetId))})}function Ese(r,e,n){return I(this,null,function*(){let t=kM(r);try{let i=yield(function(s,a){let c=he(s),l=wt.now(),u=a.reduce((g,p)=>g.add(p.key),ke()),d,f;return c.persistence.runTransaction("Locally write mutations","readwrite",g=>{let p=Kr(),_=ke();return c.Os.getEntries(g,u).next(T=>{p=T,p.forEach((D,L)=>{L.isValidDocument()||(_=_.add(D))})}).next(()=>c.localDocuments.getOverlayedDocuments(g,p)).next(T=>{d=T;let D=[];for(let L of a){let B=Ooe(L,d.get(L.key).overlayedDocument);B!=null&&D.push(new Qi(L.key,B,TW(B.value.mapValue),Vn.exists(!0)))}return c.mutationQueue.addMutationBatch(g,l,D,a)}).next(T=>{f=T;let D=T.applyToLocalDocumentSet(d,_);return c.documentOverlayCache.saveOverlays(g,T.batchId,D)})}).then(()=>({batchId:f.batchId,changes:wW(d)}))})(t.localStore,e);t.sharedClientState.addPendingMutation(i.batchId),(function(s,a,c){let l=s.Ru[s.currentUser.toKey()];l||(l=new St(De)),l=l.insert(a,c),s.Ru[s.currentUser.toKey()]=l})(t,i.batchId,n),yield ac(t,i.changes),yield Kh(t.remoteStore)}catch(i){let o=OM(i,"Failed to persist write");n.reject(o)}})}function D3(r,e){return I(this,null,function*(){let n=he(r);try{let t=yield Xoe(n.localStore,e);e.targetChanges.forEach((i,o)=>{let s=n.Eu.get(o);s&&(fe(i.addedDocuments.size+i.modifiedDocuments.size+i.removedDocuments.size<=1,22616),i.addedDocuments.size>0?s.lu=!0:i.modifiedDocuments.size>0?fe(s.lu,14607):i.removedDocuments.size>0&&(fe(s.lu,42227),s.lu=!1))}),yield ac(n,t,e)}catch(t){yield ic(t)}})}function FH(r,e,n){let t=he(r);if(t.isPrimaryClient&&n===0||!t.isPrimaryClient&&n===1){let i=[];t.Pu.forEach((o,s)=>{let a=s.view.va(e);a.snapshot&&i.push(a.snapshot)}),(function(s,a){let c=he(s);c.onlineState=a;let l=!1;c.queries.forEach((u,d)=>{for(let f of d.wa)f.va(a)&&(l=!0)}),l&&LM(c)})(t.eventManager,e),i.length&&t.hu.J_(i),t.onlineState=e,t.isPrimaryClient&&t.sharedClientState.setOnlineState(e)}}function _se(r,e,n){return I(this,null,function*(){let t=he(r);t.sharedClientState.updateQueryState(e,"rejected",n);let i=t.Eu.get(e),o=i&&i.key;if(o){let s=new St(se.comparator);s=s.insert(o,mn.newNoDocument(o,Ee.min()));let a=ke().add(o),c=new fp(Ee.min(),new Map,new St(De),s,a);yield D3(t,c),t.du=t.du.remove(o),t.Eu.delete(e),FM(t)}else yield Bh(t.localStore,e,!1).then(()=>jh(t,e,n)).catch(ic)})}function Tse(r,e){return I(this,null,function*(){let n=he(r),t=e.batch.batchId;try{let i=yield Qoe(n.localStore,e);xM(n,t,null),PM(n,t),n.sharedClientState.updateMutationState(t,"acknowledged"),yield ac(n,i)}catch(i){yield ic(i)}})}function Ise(r,e,n){return I(this,null,function*(){let t=he(r);try{let i=yield(function(s,a){let c=he(s);return c.persistence.runTransaction("Reject batch","readwrite-primary",l=>{let u;return c.mutationQueue.lookupMutationBatch(l,a).next(d=>(fe(d!==null,37113),u=d.keys(),c.mutationQueue.removeMutationBatch(l,d))).next(()=>c.mutationQueue.performConsistencyCheck(l)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(l,u,a)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(l,u)).next(()=>c.localDocuments.getDocuments(l,u))})})(t.localStore,e);xM(t,e,n),PM(t,e),t.sharedClientState.updateMutationState(e,"rejected",n),yield ac(t,i)}catch(i){yield ic(i)}})}function PM(r,e){(r.Vu.get(e)||[]).forEach(n=>{n.resolve()}),r.Vu.delete(e)}function xM(r,e,n){let t=he(r),i=t.Ru[t.currentUser.toKey()];if(i){let o=i.get(e);o&&(n?o.reject(n):o.resolve(),i=i.remove(e)),t.Ru[t.currentUser.toKey()]=i}}function jh(r,e,n=null){r.sharedClientState.removeLocalQueryTarget(e);for(let t of r.Tu.get(e))r.Pu.delete(t),n&&r.hu.pu(t,n);r.Tu.delete(e),r.isPrimaryClient&&r.Au.zr(e).forEach(t=>{r.Au.containsKey(t)||C3(r,t)})}function C3(r,e){r.Iu.delete(e.path.canonicalString());let n=r.du.get(e);n!==null&&(Gh(r.remoteStore,n),r.du=r.du.remove(e),r.Eu.delete(n),FM(r))}function VL(r,e,n){for(let t of n)t instanceof Ly?(r.Au.addReference(t.key,e),vse(r,t)):t instanceof My?(X(Qh,"Document no longer in limbo: "+t.key),r.Au.removeReference(t.key,e),r.Au.containsKey(t.key)||C3(r,t.key)):ae(19791,{yu:t})}function vse(r,e){let n=e.key,t=n.path.canonicalString();r.du.get(n)||r.Iu.has(t)||(X(Qh,"New document in limbo: "+n),r.Iu.add(t),FM(r))}function FM(r){for(;r.Iu.size>0&&r.du.size<r.maxConcurrentLimboResolutions;){let e=r.Iu.values().next().value;r.Iu.delete(e);let n=new se(He.fromString(e)),t=r.mu.next();r.Eu.set(t,new kL(n)),r.du=r.du.insert(n,t),Jy(r.remoteStore,new Uh(Yr(wp(n.path)),t,"TargetPurposeLimboResolution",zr.ue))}}function ac(r,e,n){return I(this,null,function*(){let t=he(r),i=[],o=[],s=[];t.Pu.isEmpty()||(t.Pu.forEach((a,c)=>{s.push(t.gu(c,e,n).then(l=>{var u;if((l||n)&&t.isPrimaryClient){let d=l?!l.fromCache:(u=n?.targetChanges.get(c.targetId))===null||u===void 0?void 0:u.current;t.sharedClientState.updateQueryState(c.targetId,d?"current":"not-current")}if(l){i.push(l);let d=gL.Es(c.targetId,l);o.push(d)}}))}),yield Promise.all(s),t.hu.J_(i),yield(function(c,l){return I(this,null,function*(){let u=he(c);try{yield u.persistence.runTransaction("notifyLocalViewChanges","readwrite",d=>$.forEach(l,f=>$.forEach(f.Is,g=>u.persistence.referenceDelegate.addReference(d,f.targetId,g)).next(()=>$.forEach(f.ds,g=>u.persistence.referenceDelegate.removeReference(d,f.targetId,g)))))}catch(d){if(!oc(d))throw d;X(RM,"Failed to update sequence numbers: "+d)}for(let d of l){let f=d.targetId;if(!d.fromCache){let g=u.Fs.get(f),p=g.snapshotVersion,_=g.withLastLimboFreeSnapshotVersion(p);u.Fs=u.Fs.insert(f,_)}}})})(t.localStore,o))})}function yse(r,e){return I(this,null,function*(){let n=he(r);if(!n.currentUser.isEqual(e)){X(Qh,"User change. New user:",e.toKey());let t=yield d3(n.localStore,e);n.currentUser=e,(function(o,s){o.Vu.forEach(a=>{a.forEach(c=>{c.reject(new Q(W.CANCELLED,s))})}),o.Vu.clear()})(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(e,t.removedBatchIds,t.addedBatchIds),yield ac(n,t.Bs)}})}function Sse(r,e){let n=he(r),t=n.Eu.get(e);if(t&&t.lu)return ke().add(t.key);{let i=ke(),o=n.Tu.get(e);if(!o)return i;for(let s of o){let a=n.Pu.get(s);i=i.unionWith(a.view.tu)}return i}}function Ase(r,e){return I(this,null,function*(){let n=he(r),t=yield EL(n.localStore,e.query,!0),i=e.view.uu(t);return n.isPrimaryClient&&VL(n,e.targetId,i._u),i})}function Rse(r,e){return I(this,null,function*(){let n=he(r);return g3(n.localStore,e).then(t=>ac(n,t))})}function Dse(r,e,n,t){return I(this,null,function*(){let i=he(r),o=yield(function(a,c){let l=he(a),u=he(l.mutationQueue);return l.persistence.runTransaction("Lookup mutation documents","readonly",d=>u.Xn(d,c).next(f=>f?l.localDocuments.getDocuments(d,f):$.resolve(null)))})(i.localStore,e);o!==null?(n==="pending"?yield Kh(i.remoteStore):n==="acknowledged"||n==="rejected"?(xM(i,e,t||null),PM(i,e),(function(a,c){he(he(a).mutationQueue).rr(c)})(i.localStore,e)):ae(6720,"Unknown batchState",{wu:n}),yield ac(i,o)):X(Qh,"Cannot apply mutation batch with id: "+e)})}function Cse(r,e){return I(this,null,function*(){let n=he(r);if(Zy(n),kM(n),e===!0&&n.fu!==!0){let t=n.sharedClientState.getAllActiveQueryTargets(),i=yield kH(n,t.toArray());n.fu=!0,yield bL(n.remoteStore,!0);for(let o of i)Jy(n.remoteStore,o)}else if(e===!1&&n.fu!==!1){let t=[],i=Promise.resolve();n.Tu.forEach((o,s)=>{n.sharedClientState.isLocalQueryTarget(s)?t.push(s):i=i.then(()=>(jh(n,s),Bh(n.localStore,s,!0))),Gh(n.remoteStore,s)}),yield i,yield kH(n,t),(function(s){let a=he(s);a.Eu.forEach((c,l)=>{Gh(a.remoteStore,l)}),a.Au.jr(),a.Eu=new Map,a.du=new St(se.comparator)})(n),n.fu=!1,yield bL(n.remoteStore,!1)}})}function kH(r,e,n){return I(this,null,function*(){let t=he(r),i=[],o=[];for(let s of e){let a,c=t.Tu.get(s);if(c&&c.length!==0){a=yield Sy(t.localStore,Yr(c[0]));for(let l of c){let u=t.Pu.get(l),d=yield Ase(t,u);d.snapshot&&o.push(d.snapshot)}}else{let l=yield f3(t.localStore,s);a=yield Sy(t.localStore,l),yield MM(t,N3(l),s,!1,a.resumeToken)}i.push(a)}return t.hu.J_(o),i})}function N3(r){return RW(r.path,r.collectionGroup,r.orderBy,r.filters,r.limit,"F",r.startAt,r.endAt)}function Nse(r){return(function(n){return he(he(n).persistence).Ps()})(he(r).localStore)}function Ose(r,e,n,t){return I(this,null,function*(){let i=he(r);if(i.fu)return void X(Qh,"Ignoring unexpected query state notification.");let o=i.Tu.get(e);if(o&&o.length>0)switch(n){case"current":case"not-current":{let s=yield g3(i.localStore,NW(o[0])),a=fp.createSynthesizedRemoteEventForCurrentChange(e,n==="current",rn.EMPTY_BYTE_STRING);yield ac(i,s,a);break}case"rejected":yield Bh(i.localStore,e,!0),jh(i,e,t);break;default:ae(64155,n)}})}function bse(r,e,n){return I(this,null,function*(){let t=Zy(r);if(t.fu){for(let i of e){if(t.Tu.has(i)&&t.sharedClientState.isActiveQueryTarget(i)){X(Qh,"Adding an already active target "+i);continue}let o=yield f3(t.localStore,i),s=yield Sy(t.localStore,o);yield MM(t,N3(o),s.targetId,!1,s.resumeToken),Jy(t.remoteStore,s)}for(let i of n)t.Tu.has(i)&&(yield Bh(t.localStore,i,!1).then(()=>{Gh(t.remoteStore,i),jh(t,i)}).catch(ic))}})}function Zy(r){let e=he(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=D3.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=Sse.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=_se.bind(null,e),e.hu.J_=dse.bind(null,e.eventManager),e.hu.pu=hse.bind(null,e.eventManager),e}function kM(r){let e=he(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=Tse.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=Ise.bind(null,e),e}var UM=(()=>{class r{constructor(){this.kind="memory",this.synchronizeTabs=!1}initialize(n){return I(this,null,function*(){this.serializer=Qy(n.databaseInfo.databaseId),this.sharedClientState=this.bu(n),this.persistence=this.Du(n),yield this.persistence.start(),this.localStore=this.vu(n),this.gcScheduler=this.Cu(n,this.localStore),this.indexBackfillerScheduler=this.Fu(n,this.localStore)})}Cu(n,t){return null}Fu(n,t){return null}vu(n){return u3(this.persistence,new yy,n.initialUser,this.serializer)}Du(n){return new Tp(Iy.Vi,this.serializer)}bu(n){return new Dy}terminate(){return I(this,null,function*(){var n,t;(n=this.gcScheduler)===null||n===void 0||n.stop(),(t=this.indexBackfillerScheduler)===null||t===void 0||t.stop(),this.sharedClientState.shutdown(),yield this.persistence.shutdown()})}}return r.provider={build:()=>new r},r})(),BL=class extends UM{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,n){fe(this.persistence.referenceDelegate instanceof vy,46915);let t=this.persistence.referenceDelegate.garbageCollector;return new Ey(t,e.asyncQueue,n)}Du(e){let n=this.cacheSizeBytes!==void 0?Cr.withCacheSize(this.cacheSizeBytes):Cr.DEFAULT;return new Tp(t=>vy.Vi(t,n),this.serializer)}},Py=class r extends UM{constructor(e,n,t){super(),this.Mu=e,this.cacheSizeBytes=n,this.forceOwnership=t,this.kind="persistent",this.synchronizeTabs=!1}initialize(e){return I(this,null,function*(){yield Rc(r.prototype,this,"initialize").call(this,e),yield this.Mu.initialize(this,e),yield kM(this.Mu.syncEngine),yield Kh(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(e){return u3(this.persistence,new yy,e.initialUser,this.serializer)}Cu(e,n){let t=this.persistence.referenceDelegate.garbageCollector;return new Ey(t,e.asyncQueue,n)}Fu(e,n){let t=new dw(n,this.persistence);return new uw(e.asyncQueue,t)}Du(e){let n=l3(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),t=this.cacheSizeBytes!==void 0?Cr.withCacheSize(this.cacheSizeBytes):Cr.DEFAULT;return new fL(this.synchronizeTabs,n,e.clientId,t,e.asyncQueue,T3(),Wv(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new Dy}},GL=class r extends Py{constructor(e,n){super(e,n,!1),this.Mu=e,this.cacheSizeBytes=n,this.synchronizeTabs=!0}initialize(e){return I(this,null,function*(){yield Rc(r.prototype,this,"initialize").call(this,e);let n=this.Mu.syncEngine;this.sharedClientState instanceof Jm&&(this.sharedClientState.syncEngine={Do:Dse.bind(null,n),vo:Ose.bind(null,n),Co:bse.bind(null,n),Ps:Nse.bind(null,n),bo:Rse.bind(null,n)},yield this.sharedClientState.start()),yield this.persistence.ji(t=>I(this,null,function*(){yield Cse(this.Mu.syncEngine,t),this.gcScheduler&&(t&&!this.gcScheduler.started?this.gcScheduler.start():t||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(t&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():t||this.indexBackfillerScheduler.stop())}))})}bu(e){let n=T3();if(!Jm.C(n))throw new Q(W.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let t=l3(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Jm(n,e.asyncQueue,t,e.clientId,e.initialUser)}},VM=(()=>{class r{initialize(n,t){return I(this,null,function*(){this.localStore||(this.localStore=n.localStore,this.sharedClientState=n.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!n.synchronizeTabs),this.sharedClientState.onlineStateHandler=i=>FH(this.syncEngine,i,1),this.remoteStore.remoteSyncer.handleCredentialChange=yse.bind(null,this.syncEngine),yield bL(this.remoteStore,this.syncEngine.isPrimaryClient))})}createEventManager(n){return(function(){return new ML})()}createDatastore(n){let t=Qy(n.databaseInfo.databaseId),i=(function(s){return new SL(s)})(n.databaseInfo);return(function(s,a,c,l){return new CL(s,a,c,l)})(n.authCredentials,n.appCheckCredentials,i,t)}createRemoteStore(n){return(function(i,o,s,a,c){return new OL(i,o,s,a,c)})(this.localStore,this.datastore,n.asyncQueue,t=>FH(this.syncEngine,t,0),(function(){return Cy.C()?new Cy:new TL})())}createSyncEngine(n,t){return(function(o,s,a,c,l,u,d){let f=new UL(o,s,a,c,l,u);return d&&(f.fu=!0),f})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,n.initialUser,n.maxConcurrentLimboResolutions,t)}terminate(){return I(this,null,function*(){var n,t;yield(function(o){return I(this,null,function*(){let s=he(o);X(cu,"RemoteStore shutting down."),s.Ia.add(5),yield Mp(s),s.Ea.shutdown(),s.Aa.set("Unknown")})})(this.remoteStore),(n=this.datastore)===null||n===void 0||n.terminate(),(t=this.eventManager)===null||t===void 0||t.terminate()})}}return r.provider={build:()=>new r},r})();var Sp=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):Wt("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}xu(e,n){setTimeout(()=>{this.muted||e(n)},0)}};var $L=class{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}lookup(e){return I(this,null,function*(){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new Q(W.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let n=yield(function(i,o){return I(this,null,function*(){let s=he(i),a={documents:o.map(d=>mp(s.serializer,d))},c=yield s.Jo("BatchGetDocuments",s.serializer.databaseId,He.emptyPath(),a,o.length),l=new Map;c.forEach(d=>{let f=Foe(s.serializer,d);l.set(f.key.toString(),f)});let u=[];return o.forEach(d=>{let f=l.get(d.toString());fe(!!f,55234,{key:d}),u.push(f)}),u})})(this.datastore,e);return n.forEach(t=>this.recordVersion(t)),n})}set(e,n){this.write(n.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,n){try{this.write(n.toMutation(e,this.preconditionForUpdate(e)))}catch(t){this.lastTransactionError=t}this.writtenDocs.add(e.toString())}delete(e){this.write(new ou(e,this.precondition(e))),this.writtenDocs.add(e.toString())}commit(){return I(this,null,function*(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(n=>{e.delete(n.key.toString())}),e.forEach((n,t)=>{let i=se.fromPath(t);this.mutations.push(new up(i,this.precondition(i)))}),yield(function(t,i){return I(this,null,function*(){let o=he(t),s={writes:i.map(a=>pp(o.serializer,a))};yield o.Wo("Commit",o.serializer.databaseId,He.emptyPath(),s)})})(this.datastore,this.mutations),this.committed=!0})}recordVersion(e){let n;if(e.isFoundDocument())n=e.version;else{if(!e.isNoDocument())throw ae(50498,{Wu:e.constructor.name});n=Ee.min()}let t=this.readVersions.get(e.key.toString());if(t){if(!n.isEqual(t))throw new Q(W.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),n)}precondition(e){let n=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&n?n.isEqual(Ee.min())?Vn.exists(!1):Vn.updateTime(n):Vn.none()}preconditionForUpdate(e){let n=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&n){if(n.isEqual(Ee.min()))throw new Q(W.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Vn.updateTime(n)}return Vn.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}};var jL=class{constructor(e,n,t,i,o){this.asyncQueue=e,this.datastore=n,this.options=t,this.updateFunction=i,this.deferred=o,this.Gu=t.maxAttempts,this.F_=new vp(this.asyncQueue,"transaction_retry")}zu(){this.Gu-=1,this.ju()}ju(){this.F_.g_(()=>I(this,null,function*(){let e=new $L(this.datastore),n=this.Ju(e);n&&n.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(i=>{this.Hu(i)}))}).catch(t=>{this.Hu(t)})}))}Ju(e){try{let n=this.updateFunction(e);return!Np(n)&&n.catch&&n.then?n:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(n){return this.deferred.reject(n),null}}Hu(e){this.Gu>0&&this.Yu(e)?(this.Gu-=1,this.asyncQueue.enqueueAndForget(()=>(this.ju(),Promise.resolve()))):this.deferred.reject(e)}Yu(e){if(e.name==="FirebaseError"){let n=e.code;return n==="aborted"||n==="failed-precondition"||n==="already-exists"||!BW(n)}return!1}};var rc="FirestoreClient",HL=class{constructor(e,n,t,i,o){this.authCredentials=e,this.appCheckCredentials=n,this.asyncQueue=t,this.databaseInfo=i,this.user=tn.UNAUTHENTICATED,this.clientId=Zm.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=o,this.authCredentials.start(t,s=>I(this,null,function*(){X(rc,"Received user=",s.uid),yield this.authCredentialListener(s),this.user=s})),this.appCheckCredentials.start(t,s=>(X(rc,"Received new app check token=",s),this.appCheckCredentialListener(s,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(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new Nr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(()=>I(this,null,function*(){try{this._onlineComponents&&(yield this._onlineComponents.terminate()),this._offlineComponents&&(yield this._offlineComponents.terminate()),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(n){let t=OM(n,"Failed to shutdown persistence");e.reject(t)}})),e.promise}};function Zb(r,e){return I(this,null,function*(){r.asyncQueue.verifyOperationInProgress(),X(rc,"Initializing OfflineComponentProvider");let n=r.configuration;yield e.initialize(n);let t=n.initialUser;r.setCredentialChangeListener(i=>I(null,null,function*(){t.isEqual(i)||(yield d3(e.localStore,i),t=i)})),e.persistence.setDatabaseDeletedListener(()=>{ks("Terminating Firestore due to IndexedDb database deletion"),r.terminate().then(()=>{X("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(i=>{ks("Terminating Firestore due to IndexedDb database deletion failed",i)})}),r._offlineComponents=e})}function UH(r,e){return I(this,null,function*(){r.asyncQueue.verifyOperationInProgress();let n=yield wse(r);X(rc,"Initializing OnlineComponentProvider"),yield e.initialize(n,r.configuration),r.setCredentialChangeListener(t=>MH(e.remoteStore,t)),r.setAppCheckTokenChangeListener((t,i)=>MH(e.remoteStore,i)),r._onlineComponents=e})}function wse(r){return I(this,null,function*(){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){X(rc,"Using user provided OfflineComponentProvider");try{yield Zb(r,r._uninitializedComponentsProvider._offline)}catch(e){let n=e;if(!(function(i){return i.name==="FirebaseError"?i.code===W.FAILED_PRECONDITION||i.code===W.UNIMPLEMENTED:!(typeof DOMException<"u"&&i instanceof DOMException)||i.code===22||i.code===20||i.code===11})(n))throw n;ks("Error using user provided cache. Falling back to memory cache: "+n),yield Zb(r,new UM)}}else X(rc,"Using default OfflineComponentProvider"),yield Zb(r,new BL(void 0));return r._offlineComponents})}function BM(r){return I(this,null,function*(){return r._onlineComponents||(r._uninitializedComponentsProvider?(X(rc,"Using user provided OnlineComponentProvider"),yield UH(r,r._uninitializedComponentsProvider._online)):(X(rc,"Using default OnlineComponentProvider"),yield UH(r,new VM))),r._onlineComponents})}function Lse(r){return BM(r).then(e=>e.syncEngine)}function O3(r){return BM(r).then(e=>e.datastore)}function xy(r){return I(this,null,function*(){let e=yield BM(r),n=e.eventManager;return n.onListen=fse.bind(null,e.syncEngine),n.onUnlisten=mse.bind(null,e.syncEngine),n.onFirstRemoteStoreListen=gse.bind(null,e.syncEngine),n.onLastRemoteStoreUnlisten=pse.bind(null,e.syncEngine),n})}function Mse(r,e,n={}){let t=new Nr;return r.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return(function(o,s,a,c,l){let u=new Sp({next:f=>{u.Ou(),s.enqueueAndForget(()=>wM(o,d));let g=f.docs.has(a);!g&&f.fromCache?l.reject(new Q(W.UNAVAILABLE,"Failed to get document because the client is offline.")):g&&f.fromCache&&c&&c.source==="server"?l.reject(new Q(W.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.)')):l.resolve(f)},error:f=>l.reject(f)}),d=new yp(wp(a.path),u,{includeMetadataChanges:!0,ka:!0});return bM(o,d)})(yield xy(r),r.asyncQueue,e,n,t)})),t.promise}function Pse(r,e,n={}){let t=new Nr;return r.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return(function(o,s,a,c,l){let u=new Sp({next:f=>{u.Ou(),s.enqueueAndForget(()=>wM(o,d)),f.fromCache&&c.source==="server"?l.reject(new Q(W.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.)')):l.resolve(f)},error:f=>l.reject(f)}),d=new yp(a,u,{includeMetadataChanges:!0,ka:!0});return bM(o,d)})(yield xy(r),r.asyncQueue,e,n,t)})),t.promise}function xse(r,e,n){let t=new Nr;return r.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){try{let i=yield O3(r);t.resolve((function(s,a,c){return I(this,null,function*(){var l;let u=he(s),{request:d,ft:f,parent:g}=Voe(u.serializer,_oe(a),c);u.connection.Qo||delete d.parent;let p=(yield u.Jo("RunAggregationQuery",u.serializer.databaseId,g,d,1)).filter(T=>!!T.result);fe(p.length===1,64727);let _=(l=p[0].result)===null||l===void 0?void 0:l.aggregateFields;return Object.keys(_).reduce((T,D)=>(T[f[D]]=_[D],T),{})})})(i,e,n))}catch(i){t.reject(i)}})),t.promise}function b3(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var VH=new Map;var w3="firestore.googleapis.com",BH=!0,Fy=class{constructor(e){var n,t;if(e.host===void 0){if(e.ssl!==void 0)throw new Q(W.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=w3,this.ssl=BH}else this.host=e.host,this.ssl=(n=e.ssl)!==null&&n!==void 0?n:BH;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=n3;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<s3)throw new Q(W.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}Vie("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=b3((t=e.experimentalLongPollingOptions)!==null&&t!==void 0?t:{}),(function(o){if(o.timeoutSeconds!==void 0){if(isNaN(o.timeoutSeconds))throw new Q(W.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (must not be NaN)`);if(o.timeoutSeconds<5)throw new Q(W.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (minimum allowed value is 5)`);if(o.timeoutSeconds>30)throw new Q(W.INVALID_ARGUMENT,`invalid long polling timeout: ${o.timeoutSeconds} (maximum allowed value is 30)`)}})(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(function(t,i){return t.timeoutSeconds===i.timeoutSeconds})(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},lu=class{constructor(e,n,t,i){this._authCredentials=e,this._appCheckCredentials=n,this._databaseId=t,this._app=i,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Fy({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new Q(W.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(e){if(this._settingsFrozen)throw new Q(W.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 Fy(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(t){if(!t)return new ew;switch(t.type){case"firstParty":return new iw(t.sessionIndex||"0",t.iamToken||null,t.authTokenFactory||null);case"provider":return t.client;default:throw new Q(W.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.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 I(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(n){let t=VH.get(n);t&&(X("ComponentProvider","Removing Datastore"),VH.delete(n),t.terminate())})(this),Promise.resolve()}};function L3(r,e,n,t={}){var i;r=Or(r,lu);let o=$r(e),s=r._getSettings(),a=Object.assign(Object.assign({},s),{emulatorOptions:r._getEmulatorOptions()}),c=`${e}:${n}`;o&&(Ta(`https://${c}`),gl("Firestore",!0)),s.host!==w3&&s.host!==c&&ks("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let l=Object.assign(Object.assign({},s),{host:c,ssl:o,emulatorOptions:t});if(!Bi(l,a)&&(r._setSettings(l),t.mockUserToken)){let u,d;if(typeof t.mockUserToken=="string")u=t.mockUserToken,d=tn.MOCK_USER;else{u=uI(t.mockUserToken,(i=r._app)===null||i===void 0?void 0:i.options.projectId);let f=t.mockUserToken.sub||t.mockUserToken.user_id;if(!f)throw new Q(W.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");d=new tn(f)}r._authCredentials=new tw(new zv(u,d))}}var Xi=class r{constructor(e,n,t){this.converter=n,this._query=t,this.type="query",this.firestore=e}withConverter(e){return new r(this.firestore,e,this._query)}},pn=class r{constructor(e,n,t){this.converter=n,this._key=t,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new za(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}toJSON(){return{type:r._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,n,t){if(Cp(n,r._jsonSchema))return new r(e,t||null,new se(He.fromString(n.referencePath)))}};pn._jsonSchemaVersion="firestore/documentReference/1.0",pn._jsonSchema={type:nn("string",pn._jsonSchemaVersion),referencePath:nn("string")};var za=class r extends Xi{constructor(e,n,t){super(e,n,wp(t)),this._path=t,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new pn(this.firestore,null,new se(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function M3(r,e,...n){if(r=Be(r),lM("collection","path",e),r instanceof lu){let t=He.fromString(e,...n);return xj(t),new za(r,null,t)}{if(!(r instanceof pn||r instanceof za))throw new Q(W.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let t=r._path.child(He.fromString(e,...n));return xj(t),new za(r.firestore,null,t)}}function P3(r,e){if(r=Or(r,lu),lM("collectionGroup","collection id",e),e.indexOf("/")>=0)throw new Q(W.INVALID_ARGUMENT,`Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Xi(r,null,(function(t){return new zo(He.emptyPath(),t)})(e))}function x3(r,e,...n){if(r=Be(r),arguments.length===1&&(e=Zm.newId()),lM("doc","path",e),r instanceof lu){let t=He.fromString(e,...n);return Pj(t),new pn(r,null,new se(t))}{if(!(r instanceof pn||r instanceof za))throw new Q(W.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let t=r._path.child(He.fromString(e,...n));return Pj(t),new pn(r.firestore,r instanceof za?r.converter:null,new se(t))}}var GH="AsyncQueue",ky=class{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new vp(this,"async_queue_retry"),this.oc=()=>{let t=Wv();t&&X(GH,"Visibility state changed to "+t.visibilityState),this.F_.y_()},this._c=e;let n=Wv();n&&typeof n.addEventListener=="function"&&n.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let n=Wv();n&&typeof n.removeEventListener=="function"&&n.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let n=new Nr;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(e().then(n.resolve,n.reject),n.promise)).then(()=>n.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Zu.push(e),this.cc()))}cc(){return I(this,null,function*(){if(this.Zu.length!==0){try{yield this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!oc(e))throw e;X(GH,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}})}uc(e){let n=this._c.then(()=>(this.nc=!0,e().catch(t=>{throw this.tc=t,this.nc=!1,Wt("INTERNAL UNHANDLED ERROR: ",$H(t)),t}).then(t=>(this.nc=!1,t))));return this._c=n,n}enqueueAfterDelay(e,n,t){this.ac(),this.sc.indexOf(e)>-1&&(n=0);let i=wL.createAndSchedule(this,e,n,t,o=>this.lc(o));return this.ec.push(i),i}ac(){this.tc&&ae(47125,{hc:$H(this.tc)})}verifyOperationInProgress(){}Pc(){return I(this,null,function*(){let e;do e=this._c,yield e;while(e!==this._c)})}Tc(e){for(let n of this.ec)if(n.timerId===e)return!0;return!1}Ic(e){return this.Pc().then(()=>{this.ec.sort((n,t)=>n.targetTimeMs-t.targetTimeMs);for(let n of this.ec)if(n.skipDelay(),e!=="all"&&n.timerId===e)break;return this.Pc()})}dc(e){this.sc.push(e)}lc(e){let n=this.ec.indexOf(e);this.ec.splice(n,1)}};function $H(r){let e=r.message||"";return r.stack&&(e=r.stack.includes(r.message)?r.stack:r.message+`
167
- `+r.stack),e}function jH(r){return(function(n,t){if(typeof n!="object"||n===null)return!1;let i=n;for(let o of t)if(o in i&&typeof i[o]=="function")return!0;return!1})(r,["next","error","complete"])}var Ji=class extends lu{constructor(e,n,t,i){super(e,n,t,i),this.type="firestore",this._queue=new ky,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return I(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new ky(e),this._firestoreClient=void 0,yield e}})}};function eS(r,e,n){n||(n=ap);let t=Po(r,"firestore");if(t.isInitialized(n)){let i=t.getImmediate({identifier:n}),o=t.getOptions(n);if(Bi(o,e))return i;throw new Q(W.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(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new Q(W.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(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<s3)throw new Q(W.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&$r(e.host)&&Ta(e.host),t.initialize({options:e,instanceIdentifier:n})}function Xh(r,e){let n=typeof r=="object"?r:Sr(),t=typeof r=="string"?r:e||ap,i=Po(n,"firestore").getImmediate({identifier:t});if(!i._initialized){let o=kd("firestore");o&&L3(i,...o)}return i}function Jh(r){if(r._terminated)throw new Q(W.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||Fse(r),r._firestoreClient}function Fse(r){var e,n,t;let i=r._freezeSettings(),o=(function(a,c,l,u){return new mw(a,c,l,u.host,u.ssl,u.experimentalForceLongPolling,u.experimentalAutoDetectLongPolling,b3(u.experimentalLongPollingOptions),u.useFetchStreams,u.isUsingEmulator)})(r._databaseId,((e=r._app)===null||e===void 0?void 0:e.options.appId)||"",r._persistenceKey,i);r._componentsProvider||!((n=i.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((t=i.localCache)===null||t===void 0)&&t._onlineComponentProvider)&&(r._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),r._firestoreClient=new HL(r._authCredentials,r._appCheckCredentials,r._queue,o,r._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(r._componentsProvider))}var WL=class{constructor(e="count",n){this._internalFieldPath=n,this.type="AggregateField",this.aggregateType=e}},zL=class{constructor(e,n,t){this._userDataWriter=n,this._data=t,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var Fs=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(rn.fromBase64String(e))}catch(n){throw new Q(W.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(e){return new r(rn.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:r._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Cp(e,r._jsonSchema))return r.fromBase64String(e.bytes)}};Fs._jsonSchemaVersion="firestore/bytes/1.0",Fs._jsonSchema={type:nn("string",Fs._jsonSchemaVersion),bytes:nn("string")};var Hh=class{constructor(...e){for(let n=0;n<e.length;++n)if(e[n].length===0)throw new Q(W.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new gn(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var Ap=class{constructor(e){this._methodName=e}};var qa=class r{constructor(e,n){if(!isFinite(e)||e<-90||e>90)throw new Q(W.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(n)||n<-180||n>180)throw new Q(W.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=e,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return De(this._lat,e._lat)||De(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:r._jsonSchemaVersion}}static fromJSON(e){if(Cp(e,r._jsonSchema))return new r(e.latitude,e.longitude)}};qa._jsonSchemaVersion="firestore/geoPoint/1.0",qa._jsonSchema={type:nn("string",qa._jsonSchemaVersion),latitude:nn("number"),longitude:nn("number")};var Ka=class r{constructor(e){this._values=(e||[]).map(n=>n)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(t,i){if(t.length!==i.length)return!1;for(let o=0;o<t.length;++o)if(t[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:r._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Cp(e,r._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(n=>typeof n=="number"))return new r(e.vectorValues);throw new Q(W.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ka._jsonSchemaVersion="firestore/vectorValue/1.0",Ka._jsonSchema={type:nn("string",Ka._jsonSchemaVersion),vectorValues:nn("object")};var kse=/^__.*__$/,qL=class{constructor(e,n,t){this.data=e,this.fieldMask=n,this.fieldTransforms=t}toMutation(e,n){return this.fieldMask!==null?new Qi(e,this.data,this.fieldMask,n,this.fieldTransforms):new tc(e,this.data,n,this.fieldTransforms)}},Uy=class{constructor(e,n,t){this.data=e,this.fieldMask=n,this.fieldTransforms=t}toMutation(e,n){return new Qi(e,this.data,this.fieldMask,n,this.fieldTransforms)}};function F3(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw ae(40011,{Ec:r})}}var KL=class r{constructor(e,n,t,i,o,s){this.settings=e,this.databaseId=n,this.serializer=t,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new r(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var n;let t=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:t,mc:!1});return i.fc(e),i}gc(e){var n;let t=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:t,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return By(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(n=>e.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>e.isPrefixOf(n.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(F3(this.Ec)&&kse.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},YL=class{constructor(e,n,t){this.databaseId=e,this.ignoreUndefinedProperties=n,this.serializer=t||Qy(e)}Dc(e,n,t,i=!1){return new KL({Ec:e,methodName:n,bc:t,path:gn.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function tS(r){let e=r._freezeSettings(),n=Qy(r._databaseId);return new YL(r._databaseId,!!e.ignoreUndefinedProperties,n)}function k3(r,e,n,t,i,o={}){let s=r.Dc(o.merge||o.mergeFields?2:0,e,n,i);GM("Data must be an object, but it was:",s,t);let a=V3(t,s),c,l;if(o.merge)c=new qr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let u=[];for(let d of o.mergeFields){let f=QL(e,d,n);if(!s.contains(f))throw new Q(W.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);G3(u,f)||u.push(f)}c=new qr(u),l=s.fieldTransforms.filter(d=>c.covers(d.field))}else c=null,l=s.fieldTransforms;return new qL(new er(a),c,l)}var Vy=class r extends Ap{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof r}};function Use(r,e,n,t){let i=r.Dc(1,e,n);GM("Data must be an object, but it was:",i,t);let o=[],s=er.empty();sc(t,(c,l)=>{let u=$M(e,c,n);l=Be(l);let d=i.gc(u);if(l instanceof Vy)o.push(u);else{let f=Pp(l,d);f!=null&&(o.push(u),s.set(u,f))}});let a=new qr(o);return new Uy(s,a,i.fieldTransforms)}function Vse(r,e,n,t,i,o){let s=r.Dc(1,e,n),a=[QL(e,t,n)],c=[i];if(o.length%2!=0)throw new Q(W.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(QL(e,o[f])),c.push(o[f+1]);let l=[],u=er.empty();for(let f=a.length-1;f>=0;--f)if(!G3(l,a[f])){let g=a[f],p=c[f];p=Be(p);let _=s.gc(g);if(p instanceof Vy)l.push(g);else{let T=Pp(p,_);T!=null&&(l.push(g),u.set(g,T))}}let d=new qr(l);return new Uy(u,d,s.fieldTransforms)}function U3(r,e,n,t=!1){return Pp(n,r.Dc(t?4:3,e))}function Pp(r,e){if(B3(r=Be(r)))return GM("Unsupported field value:",e,r),V3(r,e);if(r instanceof Ap)return(function(t,i){if(!F3(i.Ec))throw i.wc(`${t._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${t._methodName}() is not currently supported inside arrays`);let o=t._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(r,e),null;if(r===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),r instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(t,i){let o=[],s=0;for(let a of t){let c=Pp(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(r,e)}return(function(t,i){if((t=Be(t))===null)return{nullValue:"NULL_VALUE"};if(typeof t=="number")return Aoe(i.serializer,t);if(typeof t=="boolean")return{booleanValue:t};if(typeof t=="string")return{stringValue:t};if(t instanceof Date){let o=wt.fromDate(t);return{timestampValue:kh(i.serializer,o)}}if(t instanceof wt){let o=new wt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:kh(i.serializer,o)}}if(t instanceof qa)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Fs)return{bytesValue:$W(i.serializer,t._byteString)};if(t instanceof pn){let o=i.databaseId,s=t.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:yM(t.firestore._databaseId||i.databaseId,t._key.path)}}if(t instanceof Ka)return(function(s,a){return{mapValue:{fields:{[pM]:{stringValue:EM},[Lh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return vM(a.serializer,l)})}}}}}})(t,i);throw i.wc(`Unsupported field value: ${$y(t)}`)})(r,e)}function V3(r,e){let n={};return dW(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):sc(r,(t,i)=>{let o=Pp(i,e.Vc(t));o!=null&&(n[t]=o)}),{mapValue:{fields:n}}}function B3(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof wt||r instanceof qa||r instanceof Fs||r instanceof pn||r instanceof Ap||r instanceof Ka)}function GM(r,e,n){if(!B3(n)||!YH(n)){let t=$y(n);throw t==="an object"?e.wc(r+" a custom object"):e.wc(r+" "+t)}}function QL(r,e,n){if((e=Be(e))instanceof Hh)return e._internalPath;if(typeof e=="string")return $M(r,e);throw By("Field path arguments must be of type string or ",r,!1,void 0,n)}var Bse=new RegExp("[~\\*/\\[\\]]");function $M(r,e,n){if(e.search(Bse)>=0)throw By(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,n);try{return new Hh(...e.split("."))._internalPath}catch{throw By(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,n)}}function By(r,e,n,t,i){let o=t&&!t.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${t}`),s&&(c+=` in document ${i}`),c+=")"),new Q(W.INVALID_ARGUMENT,a+r+c)}function G3(r,e){return r.some(n=>n.isEqual(e))}var uu=class{constructor(e,n,t,i,o){this._firestore=e,this._userDataWriter=n,this._key=t,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new pn(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new XL(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let n=this._document.data.field(nS("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n)}}},XL=class extends uu{data(){return super.data()}};function nS(r,e){return typeof e=="string"?$M(r,e):e instanceof Hh?e._internalPath:e._delegate._internalPath}function $3(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new Q(W.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Rp=class{},Wh=class extends Rp{};function j3(r,e,...n){let t=[];e instanceof Rp&&t.push(e),t=t.concat(n),(function(o){let s=o.filter(c=>c instanceof zh).length,a=o.filter(c=>c instanceof Dp).length;if(s>1||s>0&&a>0)throw new Q(W.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(...)))`.")})(t);for(let i of t)r=i._apply(r);return r}var Dp=class r extends Wh{constructor(e,n,t){super(),this._field=e,this._op=n,this._value=t,this.type="where"}static _create(e,n,t){return new r(e,n,t)}_apply(e){let n=this._parse(e);return Q3(e._query,n),new Xi(e.firestore,e.converter,Nw(e._query,n))}_parse(e){let n=tS(e.firestore);return(function(o,s,a,c,l,u,d){let f;if(l.isKeyField()){if(u==="array-contains"||u==="array-contains-any")throw new Q(W.INVALID_ARGUMENT,`Invalid Query. You can't perform '${u}' queries on documentId().`);if(u==="in"||u==="not-in"){WH(d,u);let p=[];for(let _ of d)p.push(HH(c,o,_));f={arrayValue:{values:p}}}else f=HH(c,o,d)}else u!=="in"&&u!=="not-in"&&u!=="array-contains-any"||WH(d,u),f=U3(a,s,d,u==="in"||u==="not-in");return Ge.create(l,u,f)})(e._query,"where",n,e.firestore._databaseId,this._field,this._op,this._value)}};function H3(r,e,n){let t=e,i=nS("where",r);return Dp._create(i,t,n)}var zh=class r extends Rp{constructor(e,n){super(),this.type=e,this._queryConstraints=n}static _create(e,n){return new r(e,n)}_parse(e){let n=this._queryConstraints.map(t=>t._parse(e)).filter(t=>t.getFilters().length>0);return n.length===1?n[0]:tt.create(n,this._getOperator())}_apply(e){let n=this._parse(e);return n.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)Q3(s,c),s=Nw(s,c)})(e._query,n),new Xi(e.firestore,e.converter,Nw(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function W3(...r){return r.forEach(e=>X3("or",e)),zh._create("or",r)}function z3(...r){return r.forEach(e=>X3("and",e)),zh._create("and",r)}var JL=class r extends Wh{constructor(e,n){super(),this._field=e,this._direction=n,this.type="orderBy"}static _create(e,n){return new r(e,n)}_apply(e){let n=(function(i,o,s){if(i.startAt!==null)throw new Q(W.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new Q(W.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new tu(o,s)})(e._query,this._field,this._direction);return new Xi(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new zo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,n))}};function q3(r,e="asc"){let n=e,t=nS("orderBy",r);return JL._create(t,n)}var ZL=class r extends Wh{constructor(e,n,t){super(),this.type=e,this._limit=n,this._limitType=t}static _create(e,n,t){return new r(e,n,t)}_apply(e){return new Xi(e.firestore,e.converter,sy(e._query,this._limit,this._limitType))}};function K3(r){return Bie("limit",r),ZL._create("limit",r,"F")}var eM=class r extends Wh{constructor(e,n,t){super(),this.type=e,this._docOrFields=n,this._inclusive=t}static _create(e,n,t){return new r(e,n,t)}_apply(e){let n=Gse(e,this.type,this._docOrFields,this._inclusive);return new Xi(e.firestore,e.converter,(function(i,o){return new zo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,n))}};function Y3(...r){return eM._create("startAfter",r,!1)}function Gse(r,e,n,t){if(n[0]=Be(n[0]),n[0]instanceof uu)return(function(o,s,a,c,l){if(!c)throw new Q(W.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let u=[];for(let d of Ih(o))if(d.field.isKeyField())u.push(eu(s,c.key));else{let f=c.data.field(d.field);if(zy(f))throw new Q(W.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+d.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=d.field.canonicalString();throw new Q(W.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}u.push(f)}return new Wo(u,l)})(r._query,r.firestore._databaseId,e,n[0]._document,t);{let i=tS(r.firestore);return(function(s,a,c,l,u,d){let f=s.explicitOrderBy;if(u.length>f.length)throw new Q(W.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let p=0;p<u.length;p++){let _=u[p];if(f[p].field.isKeyField()){if(typeof _!="string")throw new Q(W.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof _}`);if(!TM(s)&&_.indexOf("/")!==-1)throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${_}' contains a slash.`);let T=s.path.child(He.fromString(_));if(!se.isDocumentKey(T))throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${T}' is not because it contains an odd number of segments.`);let D=new se(T);g.push(eu(a,D))}else{let T=U3(c,l,_);g.push(T)}}return new Wo(g,d)})(r._query,r.firestore._databaseId,i,e,n,t)}}function HH(r,e,n){if(typeof(n=Be(n))=="string"){if(n==="")throw new Q(W.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!TM(e)&&n.indexOf("/")!==-1)throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let t=e.path.child(He.fromString(n));if(!se.isDocumentKey(t))throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${t}' is not because it has an odd number of segments (${t.length}).`);return eu(r,new se(t))}if(n instanceof pn)return eu(r,n._key);throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${$y(n)}.`)}function WH(r,e){if(!Array.isArray(r)||r.length===0)throw new Q(W.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function Q3(r,e){let n=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(r.filters,(function(i){switch(i){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[]}})(e.op));if(n!==null)throw n===e.op?new Q(W.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new Q(W.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`)}function X3(r,e){if(!(e instanceof Dp||e instanceof zh))throw new Q(W.INVALID_ARGUMENT,`Function ${r}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Gy=class{convertValue(e,n="none"){switch(Xa(e)){case 0:return null;case 1:return e.booleanValue;case 2:return bt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,n);case 5:return e.stringValue;case 6:return this.convertBytes(Vs(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,n);case 11:return this.convertObject(e.mapValue,n);case 10:return this.convertVectorValue(e.mapValue);default:throw ae(62114,{value:e})}}convertObject(e,n){return this.convertObjectMap(e.fields,n)}convertObjectMap(e,n="none"){let t={};return sc(e,(i,o)=>{t[i]=this.convertValue(o,n)}),t}convertVectorValue(e){var n,t,i;let o=(i=(t=(n=e.fields)===null||n===void 0?void 0:n[Lh].arrayValue)===null||t===void 0?void 0:t.values)===null||i===void 0?void 0:i.map(s=>bt(s.doubleValue));return new Ka(o)}convertGeoPoint(e){return new qa(bt(e.latitude),bt(e.longitude))}convertArray(e,n){return(e.values||[]).map(t=>this.convertValue(t,n))}convertServerTimestamp(e,n){switch(n){case"previous":let t=qy(e);return t==null?null:this.convertValue(t,n);case"estimate":return this.convertTimestamp(sp(e));default:return null}}convertTimestamp(e){let n=Us(e);return new wt(n.seconds,n.nanos)}convertDocumentKey(e,n){let t=He.fromString(e);fe(XW(t),9688,{name:e});let i=new wh(t.get(1),t.get(3)),o=new se(t.popFirst(5));return i.isEqual(n)||Wt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),o}};function J3(r,e,n){let t;return t=r?n&&(n.merge||n.mergeFields)?r.toFirestore(e,n):r.toFirestore(e):e,t}var tM=class extends Gy{constructor(e){super(),this.firestore=e}convertBytes(e){return new Fs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new pn(this.firestore,null,n)}};function $se(){return new WL("count")}var Wa=class{constructor(e,n){this.hasPendingWrites=e,this.fromCache=n}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},Ya=class r extends uu{constructor(e,n,t,i,o,s){super(e,n,t,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let n=new yh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,n={}){if(this._document){let t=this._document.data.field(nS("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t,n.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(W.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,n={};return n.type=r._jsonSchemaVersion,n.bundle="",n.bundleSource="DocumentSnapshot",n.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?n:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),n.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),n)}};Ya._jsonSchemaVersion="firestore/documentSnapshot/1.0",Ya._jsonSchema={type:nn("string",Ya._jsonSchemaVersion),bundleSource:nn("string","DocumentSnapshot"),bundleName:nn("string"),bundle:nn("string")};var yh=class extends Ya{data(e={}){return super.data(e)}},Zl=class r{constructor(e,n,t,i){this._firestore=e,this._userDataWriter=n,this._snapshot=i,this.metadata=new Wa(i.hasPendingWrites,i.fromCache),this.query=t}get docs(){let e=[];return this.forEach(n=>e.push(n)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,n){this._snapshot.docs.forEach(t=>{e.call(n,new yh(this._firestore,this._userDataWriter,t.key,t,new Wa(this._snapshot.mutatedKeys.has(t.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let n=!!e.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new Q(W.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===n||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new yh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new Wa(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new yh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new Wa(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,u=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),u=s.indexOf(a.doc.key)),{type:jse(a.type),doc:c,oldIndex:l,newIndex:u}})}})(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(W.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=r._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=Zm.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let n=[],t=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(n.push(o._document),t.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function jse(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return ae(61501,{type:r})}}function Z3(r){r=Or(r,pn);let e=Or(r.firestore,Ji);return Mse(Jh(e),r._key).then(n=>oz(e,r,n))}Zl._jsonSchemaVersion="firestore/querySnapshot/1.0",Zl._jsonSchema={type:nn("string",Zl._jsonSchemaVersion),bundleSource:nn("string","QuerySnapshot"),bundleName:nn("string"),bundle:nn("string")};var du=class extends Gy{constructor(e){super(),this.firestore=e}convertBytes(e){return new Fs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new pn(this.firestore,null,n)}};function ez(r){r=Or(r,Xi);let e=Or(r.firestore,Ji),n=Jh(e),t=new du(e);return $3(r._query),Pse(n,r._query).then(i=>new Zl(e,t,r,i))}function tz(r,e,n){r=Or(r,pn);let t=Or(r.firestore,Ji),i=J3(r.converter,e,n);return iz(t,[k3(tS(t),"setDoc",r._key,i,r.converter!==null,n).toMutation(r._key,Vn.none())])}function nz(r){return iz(Or(r.firestore,Ji),[new ou(r._key,Vn.none())])}function rz(r,...e){var n,t,i;r=Be(r);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||jH(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(jH(e[s])){let d=e[s];e[s]=(n=d.next)===null||n===void 0?void 0:n.bind(d),e[s+1]=(t=d.error)===null||t===void 0?void 0:t.bind(d),e[s+2]=(i=d.complete)===null||i===void 0?void 0:i.bind(d)}let c,l,u;if(r instanceof pn)l=Or(r.firestore,Ji),u=wp(r._key.path),c={next:d=>{e[s]&&e[s](oz(l,r,d))},error:e[s+1],complete:e[s+2]};else{let d=Or(r,Xi);l=Or(d.firestore,Ji),u=d._query;let f=new du(l);c={next:g=>{e[s]&&e[s](new Zl(l,f,d,g))},error:e[s+1],complete:e[s+2]},$3(r._query)}return(function(f,g,p,_){let T=new Sp(_),D=new yp(g,T,p);return f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return bM(yield xy(f),D)})),()=>{T.Ou(),f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return wM(yield xy(f),D)}))}})(Jh(l),u,a,c)}function iz(r,e){return(function(t,i){let o=new Nr;return t.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return Ese(yield Lse(t),i,o)})),o.promise})(Jh(r),e)}function oz(r,e,n){let t=n.docs.get(e._key),i=new du(r);return new Ya(r,i,e._key,t,new Wa(n.hasPendingWrites,n.fromCache),e.converter)}function sz(r){return az(r,{count:$se()})}function az(r,e){let n=Or(r.firestore,Ji),t=Jh(n),i=foe(e,(o,s)=>new Lw(s,o.aggregateType,o._internalFieldPath));return xse(t,r._query,i).then(o=>(function(a,c,l){let u=new du(a);return new zL(c,u,l)})(n,r,o))}var nM=class{constructor(e){let n;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),n=e.tabManager):(n=Hse(void 0),n._initialize(e)),this._onlineComponentProvider=n._onlineComponentProvider,this._offlineComponentProvider=n._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function jM(r){return new nM(r)}var rM=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=VM.provider,this._offlineComponentProvider={build:n=>new Py(n,e?.cacheSizeBytes,this.forceOwnership)}}},iM=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=VM.provider,this._offlineComponentProvider={build:n=>new GL(n,e?.cacheSizeBytes)}}};function Hse(r){return new rM(r?.forceOwnership)}function HM(){return new iM}var Wse={maxAttempts:5};function Hm(r,e){if((r=Be(r)).firestore!==e)throw new Q(W.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return r}var oM=class{constructor(e,n){this._firestore=e,this._transaction=n,this._dataReader=tS(e)}get(e){let n=Hm(e,this._firestore),t=new tM(this._firestore);return this._transaction.lookup([n._key]).then(i=>{if(!i||i.length!==1)return ae(24041);let o=i[0];if(o.isFoundDocument())return new uu(this._firestore,t,o.key,o,n.converter);if(o.isNoDocument())return new uu(this._firestore,t,n._key,null,n.converter);throw ae(18433,{doc:o})})}set(e,n,t){let i=Hm(e,this._firestore),o=J3(i.converter,n,t),s=k3(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,t);return this._transaction.set(i._key,s),this}update(e,n,t,...i){let o=Hm(e,this._firestore),s;return s=typeof(n=Be(n))=="string"||n instanceof Hh?Vse(this._dataReader,"Transaction.update",o._key,n,t,i):Use(this._dataReader,"Transaction.update",o._key,n),this._transaction.update(o._key,s),this}delete(e){let n=Hm(e,this._firestore);return this._transaction.delete(n._key),this}};var sM=class extends oM{constructor(e,n){super(e,n),this._firestore=e}get(e){let n=Hm(e,this._firestore),t=new du(this._firestore);return super.get(e).then(i=>new Ya(this._firestore,t,n._key,i._document,new Wa(!1,!1),n.converter))}};function cz(r,e,n){r=Or(r,Ji);let t=Object.assign(Object.assign({},Wse),n);return(function(o){if(o.maxAttempts<1)throw new Q(W.INVALID_ARGUMENT,"Max attempts must be at least 1")})(t),(function(o,s,a){let c=new Nr;return o.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){let l=yield O3(o);new jL(o.asyncQueue,l,a,s,c).zu()})),c.promise})(Jh(r),i=>e(new sM(r,i)),t)}(function(e,n=!0){(function(i){qh=i})(Sa),lr(new fn("firestore",(t,{instanceIdentifier:i,options:o})=>{let s=t.getProvider("app").getImmediate(),a=new Ji(new nw(t.getProvider("auth-internal")),new ow(s,t.getProvider("app-check-internal")),(function(l,u){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new Q(W.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new wh(l.options.projectId,u)})(s,i),s);return o=Object.assign({useFetchStreams:n},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),Ke(bj,wj,e),Ke(bj,wj,"esm2017")})();var rS=_e(z3,!0,2);var iS=_e(M3,!0,2),lz=_e(P3,!0,2);var uz=_e(nz,!0,2);var xp=_e(x3,!0,2);var dz=_e(sz,!0),WM=_e(Z3,!0);var hz=_e(ez,!0);var zse=_e(K3,!0,2);var fz=_e(rz,!0);var qse=_e(W3,!0,2),Kse=_e(q3,!0,2),gz=_e(j3,!0,2);var mz=_e(cz,!0),pz=_e(tz,!0,2);var Yse=_e(Y3,!0,2);var Ii=_e(H3,!0,2);var cc=(()=>{let e=class e{constructor(t,i,o){this.authService=t,this.configService=i,this.loggingService=o,this.db$=new Y(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=kV(c,a.v1DbHost),a?.forceLongPolling&&Nb());let l=rh(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(t){try{let o=t?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(C(Dr),C(Xn),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var qo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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 Y(null),this.commentAnnotationById$=new Y({}),this.fieldsToRemove=[],this.additionalFields=[],this.additionalSaveEvents=[],this.getCommentAnnotationById=s=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove),s.config?.additionalFields&&(this.additionalFields=s.config.additionalFields||[]),this.additionalSaveEvents=(s.config?.additionalSaveEvents||[]).map(a=>a?.event).filter(a=>!!a))})}catch(s){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.commentAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",t)}}resolveCommentAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:t}}),f(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.commentAnnotationIds||[])],T=le(M({},t),{commentAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let L=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.commentAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.commentAnnotationById$.next(M(M({},this.commentAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveCommentAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let o=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=M(M({},a),t.commentAnnotation);let c=this.getTargetComment(t.commentAnnotation,t.commentId),l=yield xt(()=>{if(o?.config?.saveConfig?.url){let u={commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,u,!1,o.config.saveConfig.credentials)}return o?.save?.({commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(t.commentAnnotation),eventType:t.eventType,commentId:t.commentId}),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}getTargetComment(t,i){if(!(!i||!t))for(let o of Object.values(t)){let s=o?.comments?.[i];if(s)return s}}deleteCommentAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let s=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?yn(i):void 0),u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.commentAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:g,commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,commentAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getAdditionalSaveEvents(){try{return this.additionalSaveEvents}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalSaveEvents:",t),this.additionalSaveEvents}}setCommentAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting comment annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Ko=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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 Y(null),this.reactionAnnotationById$=new Y({}),this.fieldsToRemove=[],this.getReactionAnnotationById=s=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove||[]))})}catch(s){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.reactionAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",t)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}resolveReactionAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:t}}),f(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.reactionAnnotationIds||[])],T=le(M({},t),{reactionAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let L=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.reactionAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.reactionAnnotationById$.next(M(M({},this.reactionAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveReactionAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let o=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=M(M({},a),t);let c={reactionAnnotation:t,event:Qt.REACTION_ADD,metadata:Object.values(t??{})?.[0]?.metadata},l=yield xt(()=>o?.config?.saveConfig?.url?$t(o.config.saveConfig.url,o.config.saveConfig.headers,c,!1,o.config.saveConfig.credentials):o?.save?.(c)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(t),eventType:c.event}),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let s=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),c=i??a?.[t]?.metadata,l=c?yn(c):void 0,u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.reactionAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:g,reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:s,reactionAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting reaction annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Zh=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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(s){this.loggingService.catch("Error in AttachmentResolverService constructor:",s)}}getProvider(t){try{let i=t||"default";return this.providers.get(i)||void 0}catch(i){this.loggingService.catch("Error in AttachmentResolverService getProvider:",i);return}}getRetrySaveConfig(t){let i=t||"default";return this.retrySaveConfigs.get(i)||this.defaultRetryConfig}getRetryDeleteConfig(t){let i=t||"default";return this.retryDeleteConfigs.get(i)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(t,i,o,s,a){return I(this,null,function*(){try{let c=typeof i=="function"?yield i():i||{},l=new FormData;l.append("file",o);let u={attachment:{attachmentId:s.attachment.attachmentId,name:s.attachment.name,mimeType:s.attachment.mimeType},metadata:s.metadata,event:s.event};l.append("request",JSON.stringify(u));let d={};Object.entries(c).forEach(([p,_])=>{p.toLowerCase()!=="content-type"&&(d[p]=_)});let f=yield fetch(t,M({method:"POST",headers:d,body:l},a?{credentials:a}:{}));return f.ok?{data:(yield f.json())?.data??{},success:!0,statusCode:200}:(j.catch(`Error in makeAttachmentConfigBasedRequest: ${f.status} ${f.statusText}`),{data:{},success:!1,statusCode:f.status})}catch(c){return j.catch("Error in makeAttachmentConfigBasedRequest:",c),{data:{},success:!1,statusCode:500}}})}saveAttachment(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let s=this.getProvider(o);if(!this.attachmentDataProviderAvailable(o))throw new Error("Attachment save data provider not available");let a=this.getRetrySaveConfig(o),c=i||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{request:t}});let l=yield xt(()=>I(this,null,function*(){if(s?.config?.saveConfig?.url){let u=t.attachment,{file:d}=u,f=NS(u,["file"]);return this.makeAttachmentConfigBasedRequest(s.config.saveConfig.url,s.config.saveConfig.headers,d,{attachment:f,event:t.eventType,metadata:t.attachment.metadata},s.config.saveConfig.credentials)}return s?.save?.({attachment:t.attachment,event:t.eventType,metadata:t.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",a);if(l?.statusCode!==200){this.loggingService.catch(l?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{error:l,request:t}});return}return this.analyticsService.trackEvent(P.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:t.attachment.attachmentId,eventType:t.eventType}),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{result:l,request:t}}),l}catch(s){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",s);let a=i||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{error:s,request:t}});return}})}deleteAttachment(a,c,l){return I(this,arguments,function*({attachmentId:t,metadata:i},o,s){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let u=this.getProvider(s);if(!this.attachmentDataProviderAvailable(s))throw new Error("Attachment delete data provider not available");let d=i?M({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0,f=this.getRetryDeleteConfig(s),g=o||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t,metadata:d}});let p=yield xt(()=>{if(u?.config?.deleteConfig?.url){let _={attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE};return $t(u.config.deleteConfig.url,u.config.deleteConfig.headers,_,!1,u.config.deleteConfig.credentials)}return u?.delete?.({attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",f);return p?.statusCode!==200?(this.loggingService.catch(p?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{error:p,attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:t}),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:f.revertOnFailure,isSuccess:!0},attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!0})}catch(u){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",u);let d=this.getRetryDeleteConfig(s),f=o||Z(),g=i?M({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0;return this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{error:u,attachmentId:t,metadata:g}}),{revertOnFailure:d.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(t,i="default"){try{if(t){this.loggingService.log(`Setting attachment data provider for scope: ${i}`);let o=t.config,s=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(s.forEach(({method:c,configKey:l})=>{let u=o?.[l]?.url,d=c in t&&typeof t[c]=="function";!u&&!d&&a.push(c)}),a.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(c);return}else this.providers.set(i,t),t.config?.saveRetryConfig&&this.retrySaveConfigs.set(i,t.config.saveRetryConfig),t.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(i,t.config.deleteRetryConfig)}}catch(o){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",o)}}attachmentDataProviderAvailable(t){try{let i=t||"default";return this.providers.has(i)}catch(i){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",i),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var lc=(()=>{let e=class e{constructor(t,i,o,s){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.attachmentResolverService=s,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 Y(null),this.recorderAnnotationById$=new Y({}),this.additionalFields=[],this.fieldsToRemove=[],this.uploadChunks=!1,this.getRecorderAnnotationById=a=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[a]:void 0}catch(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.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?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove||[]),this.uploadChunks=a.uploadChunks??!1)})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",a)}}getProvider(){try{let t=this.recorderAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",t)}}resolveRecorderAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:t}}),f(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.recorderAnnotationIds||[])],T=le(M({},t),{recorderAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let L=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.recorderAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.recorderAnnotationById$.next(M(M({},this.recorderAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveRecorderAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let o=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=M(M({},a),t.recorderAnnotation);let c=yield xt(()=>{if(o?.config?.saveConfig?.url){let l={recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(t.recorderAnnotation),eventType:t.eventType}),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let s=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let a=this.recorderAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?yn(i):void 0),u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.recorderAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:g,recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,recorderAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",i);return}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting recorder annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else t.storage&&this.attachmentResolverService.setAttachmentDataProvider(t.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(t)}}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",i)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot),C(Zh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var aS=class{};var ef=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p){this.analyticsService=t,this.authService=i,this.databaseService=o,this.domService=s,this.configService=a,this.loggingService=c,this.commentResolverService=l,this.reactionResolverService=u,this.recorderResolverService=d,this.coreActionsService=f,this.functions=g,this.serviceBook=p,this.endpointsService=J(xo),this.documentPaths$=new Y(null),this.docContext$=new Y(null),this.documentIds$=new Y([]),this.organizationConfig$=new Y(null),this.firestorePaths$=new Y(null),this.location$=new Y(null),this.excludedLocationIds$=new Y([]),this.organizationMetadata$=new Y(null),this.documentMetadata$=new Y(null),this.locationMetadata$=new Y(null),this.customerMetadata$=new Y(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Y({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Y({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ct,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.serviceBook.observe(Rd).subscribe(_=>{this.commentService=_??void 0}),z1(()=>this.documentPaths$.value?.clientDocumentId),this.setDocumentIdSubject.pipe(BS(()=>Ni(this.currentDebounceTime))).subscribe({next:_=>I(this,null,function*(){try{yield this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.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:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Rt(_=>!!_),Dt(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let T=sI(window.location.href);this.currentUrl=T}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>I(this,null,function*(){if(_&&(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.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&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(T=>({id:T.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),_?.organizationId&&_?.clientOrganizationId)){let T={organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId};this.getOrganizationConfig()||this.setOrganizationConfig({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),yield this.updateOrganizationMetadata(T)}})),this.documentPaths$.subscribe(_=>{let T={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId,folderId:_?.folderId,allDocuments:_?.allDocuments,veltFolderId:_?.veltFolderId};_?.organizationId&&(T.organizationId=_.organizationId,T.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(T),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Rt(_=>!!_),Dt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{organizationId:this.documentPaths$.value?.clientOrganizationId,folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,optimisticPermissions:this.documentPaths$.value?.optimisticPermissions}:null}catch(t){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",t),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.setOrganizationConfig(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(t=>({id:t.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(t=>t.location)].filter(t=>t!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(t){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",t)}}setUsersService(t){try{this.usersService=t}catch(i){this.loggingService.catch("Error in setUsersService:",i)}}setCommonDbService(t){try{this.commonDbService=t}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setUserPermissionService(t){try{this.userPermissionService=t}catch(i){this.loggingService.catch("Error in setUserPermissionService:",i)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let t=sI(location.href);this.currentUrl!==t&&(this.currentUrl=t,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowPopstate: ",t)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let t=sI(location.href);this.currentUrl!==t&&(this.currentUrl=t,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowClick: ",t)}}setDocument(a){return I(this,arguments,function*({documentId:t,documentMetadata:i,options:o,source:s="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),s==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,documentMetadata:i,methodName:"setDocument",source:s}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENTS,source:s,payload:{documentId:t,documentMetadata:i,options:o}}),yield this.setDocumentsImpl({documents:[{id:t,metadata:i}],options:M({organizationId:i?.organizationId},o??{}),source:s})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(t,i={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&t.length===this.pendingDocumentIds.length&&t.every(d=>this.pendingDocumentIds.includes(d.id))&&Ui(i,this.pendingOptions))return!1;let o=this.documentPaths$.value?.clientDocumentId,s=i?.rootDocumentId??t[0]?.id,a=this.documentIds$.value.map(u=>u.clientDocumentId),c=oI(this.getOptionsFromDocumentPaths()??{})??{};return!t.every(u=>a.includes(u.id))||!Ui(c,i)||o!==s}catch(o){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",o),!0}}getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:i=!1}){try{let o=[];return t.forEach(s=>{let a=s.id,c=`${Tr(a)}`;i&&s?.metadata&&typeof s.metadata=="object"&&(this.clientDocumentMetadataMap[a]=s.metadata),o.push({documentId:c,clientDocumentId:a})}),o}catch(o){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",o),[]}}setDocuments(a){return I(this,arguments,function*({documents:t,options:i,source:o="internal",skipPermissionValidation:s=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:t,options:i,methodName:"setDocuments",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENTS,source:o,payload:{documents:t,options:i}}),yield this.setDocumentsImpl({documents:t,options:i??{},source:o,skipPermissionValidation:s})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(o){return I(this,arguments,function*({document:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:Pn.SET_ROOT_DOCUMENT,source:i,payload:{document:t}});let s=this.getOptionsFromDocumentPaths()??{},a=this.documentIds$.value.map(c=>c.clientDocumentId);if(!a.includes(t.id)){let c=[...a.map(u=>({id:u})),{id:t.id}],l=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(l)}yield this.setDocumentIdImpl(t.id,this.documentPaths$.value?.clientOrganizationId,s)}catch(s){this.loggingService.catch("Error in DocService setRootDocument:",s)}})}setDocContext(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let i=JSON.parse(JSON.stringify(t??null));this.docContext$.next(i)}catch(i){this.loggingService.catch("Error in setDocContext: ",i)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(rt(Pt))}getProcessedDocContext(){return JV(this.getDocContext())}filterRelevantDocuments(s){return I(this,arguments,function*({options:t,documentIds:i,skipPermissionValidation:o=!1}){try{let a=this.authService.getUser();return!a||!this.commonDbService?.shouldUseFirestore()||(i=yield this.fetchDocumentsFromFolder(t,i,a),yield this.handlePermissionProvider(t,i,a),i=yield this.filterDocumentsByPermissions(t,i,a,o),i=i.slice(0,50)),i}catch(a){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",a),i}})}fetchDocumentsFromFolder(t,i,o){return I(this,null,function*(){if(!t?.folderId||!t?.allDocuments)return i;try{let s=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield Md({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:t?.organizationId??o?.clientOrganizationId,folderId:t?.folderId}},getSdkProxy:s,userId:o?.userId??""}))?.data?.forEach(c=>{i.find(l=>l.clientDocumentId===c.id)||i.push({documentId:_a(c.id),clientDocumentId:c.id})})}catch(s){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",s)}return i})}buildPermissionRequests(t,i,o){try{let s=[];return t.organizationId&&t.organizationId!==o.clientOrganizationId&&s.push({userId:o.userId,resource:{id:t.organizationId,type:ki.ORGANIZATION,source:Qn.SET_DOCUMENTS,organizationId:t.organizationId,context:t?.context}}),t.folderId&&s.push({userId:o.userId,resource:{id:t.folderId,type:ki.FOLDER,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context}}),i&&i.forEach(a=>{s.push({userId:o.userId,resource:M({id:a.clientDocumentId,type:ki.DOCUMENT,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context},t?.folderId&&{parentFolderId:t.folderId})})}),t?.context&&this.userPermissionService?.getIsContextEnabled()&&ZV({input:t?.context}).forEach(c=>{let l=JSON.stringify(c.access);s.push({userId:o.userId,resource:{id:l,type:ki.CONTEXT,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:c}})}),s}catch(s){return this.loggingService.catch("Error in buildPermissionRequests:",s),[]}}processAccessibleContexts(t,i){try{if(!t?.success||!t?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let o=t.data.filter(s=>s.type===ki.CONTEXT&&s.hasAccess).map(s=>s.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(o??"nil"))),o?.length){let s=i.filter(c=>o.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),a=eB({input:s});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(a??"nil"))),a?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(a??"nil"))),this.setDocContext(a))}}catch(o){this.loggingService.catch("Error in processAccessibleContexts:",o)}}handlePermissionProvider(t,i,o){return I(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil")));let s=this.buildPermissionRequests(t,i,o),a=Z();this.coreActionsService.triggerAction(H.PERMISSION_PROVIDER,{event:P.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Qn.SET_DOCUMENTS,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:s}}),this.userPermissionService?.cancelPendingRevokes(s);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:s,uniqueId:a,methodName:Qn.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(s??"nil"))),this.processAccessibleContexts(c,s)}catch(s){this.loggingService.catch("Error in handlePermissionProvider:",s)}})}filterDocumentsByPermissions(t,i,o,s=!1){return I(this,null,function*(){if(s)return i;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil"))),!(t?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(t,i,o);let c=this.currentValidationToken,l=[...i];return c&&this.validatePermissionsInBackground(t,i,o,c),l})}validateAndFilterPermissions(t,i,o){return I(this,null,function*(){try{let s=t?.organizationId??o?.clientOrganizationId,a=yield this.userPermissionService?.getUserPermissions({organizationId:s,documentIds:i.map(u=>u.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]});if(!a)return i;this.userPermissionService?.setCurrentUserPermissions(a),s&&a?.[o.userId]?.organization?.[s]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${s}`,void 0,void 0,!0),t?.folderId&&a?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(a?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Rs.PERMISSION_DENIED&&c.add(u)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...c],userId:o.userId,timestamp:new Date().getTime()}));let l=i.filter(u=>!c.has(u.clientDocumentId));return l.length===0&&i.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),l}catch(s){return this.loggingService.catch("Error in validateAndFilterPermissions:",s),i}})}validatePermissionsInBackground(t,i,o,s){let a=t?.organizationId??o?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:i.map(c=>c.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]}).then(c=>{if(this.currentValidationToken===s&&c){this.userPermissionService?.setCurrentUserPermissions(c);let l=[];Object.entries(c?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Rs.PERMISSION_DENIED&&l.push(u)}),a&&c?.[o.userId]?.organization?.[a]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),t?.folderId&&c?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0),l.length>0&&(this.loggingService.catch(`User does not have access to documents: ${l.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(l,o,s))}}).catch(c=>{this.loggingService.catch("Error in background permission validation:",c)})}handleDeniedDocumentAccess(t,i,o){try{if(this.currentValidationToken!==o)return;let s=this.documentPaths$.value;this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:t,userId:i.userId,timestamp:new Date().getTime()});let a=this.documentIds$.value||[],c=a.filter(l=>!t.includes(l.clientDocumentId));c.length!==a.length&&(c.length>0?this.setDocuments({documents:c.map(l=>({id:l.clientDocumentId})),options:{organizationId:s?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:t,userId:i.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(s){this.loggingService.catch("Error in handleDeniedDocumentAccess:",s)}}addUserInfoToOrganization(a){return I(this,arguments,function*({organizationId:t,user:i,notificationsConfig:o,currentUserId:s}){try{let c=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Md({data:M({type:"addUserInfoToOrganization",metadata:{organizationId:t},user:this.usersService?.externalUserDataProviderAvailable()?{userId:i?.userId}:i},o&&{notificationsConfig:o}),getSdkProxy:c,userId:s??i?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(a){return I(this,arguments,function*({documents:t,options:i,source:o,skipPermissionValidation:s=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(t??"nil")),"options:",JSON.parse(JSON.stringify(i??"nil"))),!this.shouldSetDocumentsAgain(t,oI(i))){o==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=Z();this.currentValidationToken=c;let l=this.getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:!0});if(l?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let u=this.authService.getUser();if(!u){this.draftDocuments=t,this.draftOptions=i;return}this.pendingDocumentIds=t.map(f=>f.id),this.pendingOptions=oI(i)??{},this.documentPaths$.value?.organizationId&&i?.organizationId&&this.documentPaths$.value?.clientOrganizationId!==i?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let d=i?.organizationId??u?.clientOrganizationId;if(d&&this.addUserInfoToOrganization({organizationId:d,user:u}),l=yield this.filterRelevantDocuments({options:i,documentIds:l,skipPermissionValidation:s}),this.documentIds$.next(l),l?.length){let f=l[0]?.clientDocumentId;i?.rootDocumentId&&l.find(g=>g.clientDocumentId===i?.rootDocumentId)&&(f=i?.rootDocumentId),yield this.debounceSetDocuments({documentId:f,clientOrganizationId:i?.organizationId,options:i})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,clientOrganizationId:i,methodName:"setDocumentId",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENT_ID,source:o,payload:{documentId:t,clientOrganizationId:i}}),yield this.setDocumentsImpl({documents:[{id:t}],options:{organizationId:i},source:o})}catch(a){this.loggingService.catch("Error in setDocumentId:",a);return}})}debounceSetDocuments(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,options:o}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let a=o?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=a;let c=Date.now(),l=c-this.lastSetDocumentIdCallTime,u=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||l>a&&u>a){yield this.setDocumentIdImpl(t,i,o),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:t,clientOrganizationId:i,options:o??void 0});return}catch(a){this.loggingService.catch("Error in debounceSetDocuments:",a)}})}setDocumentIdImpl(t,i,o){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let s=this.authService.getUser();if(!s)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let a=this.currentDocumentId;if(this.apiKey){let c=`${Tr(t)}`,l=o?.folderId,u=o?.folderId?bo(o?.folderId):void 0,d=o?.locationId,f=o?.allDocuments,g=o?.optimisticPermissions,p=s?.organizationId?i?fi(i):s?.organizationId:void 0,_=Z(),T=Nd.SET_DOCUMENTS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:_,methodName:_t.INIT_DOCUMENTS,moduleName:T,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let D=Z(),L=Od.SET_DOCUMENTS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,moduleName:L,methodName:Tt.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let B=Z(),w=bd.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,moduleName:w,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:_,moduleName:T}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:D,moduleName:L}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:B,moduleName:w})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==p){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let F=new XT,U=new aS;F.clientDocumentId=t,U.clientDocumentId=t,F.folderId=l,U.folderId=l,F.locationId=d,U.locationId=d,F.allDocuments=f,F.optimisticPermissions=g,U.allDocuments=f,U.optimisticPermissions=g,F.veltFolderId=u,U.veltFolderId=u,F.documentId=c,U.documentId=c,p&&(F.organizationId=p,F.clientOrganizationId=i??s?.clientOrganizationId,U.organizationId=p,U.clientOrganizationId=i??s?.clientOrganizationId);let A=`${this.apiKey}`,R=`apiKey/${this.apiKey}`;p&&(A=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${F.organizationId}`,R=`${R}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${F.organizationId}`),U.organization=`apiKey/${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,U.document=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,F.presence=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,F.cursor=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,F.comment=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,U.comment=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,F.multiThread=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,U.multiThread=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,F.tag=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,F.area=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,U.area=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}`,F.arrow=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,F.selection=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,F.audioHuddle=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,F.huddle=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,F.recorder=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,U.recorder=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,F.flock=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,F.syncVideoPlayer=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,F.liveState=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,F.liveStateSingleEditorMode=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,F.reaction=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,U.reaction=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,F.crdt=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,U.crdt=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,F.customerMetadata=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,F.views=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,U.notificationViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,U.documentViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,U.locationViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,F.notifications=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,F.metadata=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,F.users=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,F.documentIam=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.groupContacts=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,F.globalContacts=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,F.logins=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,F.userFeedback=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,F.userReportBugs=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,F.userContactUs=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,p&&(F.organizationMetadata=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,F.organizationIam=`${A}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.organizationGroups=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,F.organizationNotifications=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(F.organizationNotificationsWithDocumentId=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,F.heartbeatByDocument=`${A}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),F.organizationNotificationsLastNotificationTimestamp=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,F.organizationNotificationsUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,F.heartbeat=`${A}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),U.organizationUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,U.users=`${R}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,U.documentUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,U.notificationDocs=`${R}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,U.notificationUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(F),this.firestorePaths$.next(U),F?.clientOrganizationId&&F?.organizationId&&!(F?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&F?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.setOrganizationConfig({organizationId:F?.organizationId,clientOrganizationId:F?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),a&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:t}}),this.analyticsService.trackEvent(P.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:t},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(s){this.loggingService.catch("Error in setDocumentIdImpl: ",s)}})}unsetDocumentId({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:t}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:Pn.UNSET_DOCUMENT_ID,source:t}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocumentId: ",o)}}unsetDocumentImpl({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let o=JSON.parse(JSON.stringify(this.documentIds$.value??[])),s=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),a=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),i&&(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:o,folderId:s,context:a}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:t}),this.analyticsService.trackEvent(P.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:t==="external"?"User unset document id":"System unset document id",source:t},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetDocumentImpl: ",o)}}unsetDocuments({source:t,unsetDocumentPaths:i=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:t}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:t,methodName:Pn.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocuments: ",o)}}addPreDocumentIdChangeFunction(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(t,i)}catch(o){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",o)}}callPreDocumentIdChangeFunctions(t){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,o]of this.preDocumentIdChangeFunctions)try{yield o(t)}catch(s){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",s)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}fetchOrganizationMetadata(t){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig()),this.db&&t?.organizationId){let i=t?.organizationId,o=t?.clientOrganizationId,s=this.authService.getUser()?.userId??"",a=yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o});if(s&&a?.[s]?.organization?.[o]?.errorCode===Rs.PERMISSION_DENIED)return;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:i,field:"metadata"}}).then(c=>{c&&!c?.errorCode&&this.organizationMetadata$.next(le(M({},this.organizationMetadata$.value),{[i]:c}))}).catch(c=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",c)})}}catch(i){this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)}})}fetchDocumentMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value,o=this.documentMetadata$.value;if(t=t.filter(s=>!o?.[s.documentId]),t?.some(s=>!s?.documentId||!s?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let s=i?.folderId,a=[],c={organizationId:i?.clientOrganizationId,folderId:s},l=[],u=20;for(let f=0;f<t.length;f+=u)l.push(t.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchDocuments(g))});let d={};a.length>0&&(yield Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=p.metadata)})}),this.setAllDocumentMetadata(M(M({},this.documentMetadata$.value),d))}).catch(f=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",f)}))}else o?.[i?.documentId??t?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??t?.[0]?.documentId,skipObjectValues:!0}}).then(s=>{s?.documentId&&this.setDocumentMetadata(s.documentId,s)}).catch(s=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",s)})}}catch(i){this.loggingService.catch("Error in fetchDocumentMetadata: ",i)}})}fetchLocationMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentIds$.value,o=t?.folderId,s=t?.allDocuments,a=[],c={organizationId:t?.clientOrganizationId,folderId:o,allDocuments:s},l=[],u=20;for(let f=0;f<i.length;f+=u)l.push(i.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchLocations(g))});let d=this.locationMetadata$.value??{};a.length>0&&Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=le(M({},d?.[p.metadata.documentId]??{}),{[p.location.id]:p}))})}),Object.keys(d||{}).length>0&&this.locationMetadata$.next(d)}).catch(f=>{this.loggingService.catch("Error in fetchLocationMetadata: ",f)})}}catch(t){this.loggingService.catch("Error in fetchLocationMetadata: ",t)}})}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(as(i=>de(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(t){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",t)}}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(t=>t?.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(t){try{return`${Tr(t)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(t){try{return`${fi(t)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:void 0,methodName:"setLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,source:i,methodName:Pn.SET_LOCATION,payload:{locations:[t],options:void 0}}),this.setLocationsImpl({locations:[t]})}catch(s){this.loggingService.catch("Error in setLocation: ",s)}})}setLocations(s){return I(this,arguments,function*({locations:t,options:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:t,options:i,methodName:"setLocations",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:Pn.SET_LOCATIONS,source:o,payload:{locations:t,options:i}}),this.setLocationsImpl({locations:t,options:i})}catch(a){this.loggingService.catch("Error in setLocations: ",a)}})}getValidLocations(t){try{let i=[];return t&&Array.isArray(t)&&t.forEach(o=>{if(o&&typeof o=="object"){let s=!0;o?.version&&(!o?.version?.id||!o?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${o?.id}, If you're setting version then add id and name fields to version object.`),s=!1),s&&i.push(o)}}),i}catch(i){this.loggingService.catch("Error in getValidLocations: ",i)}return t}setRootLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:t,methodName:"setRootLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:Pn.SET_ROOT_LOCATION,source:i,payload:{location:t}});let s=Object.values(this.locations$.value).map(a=>a.location).filter(a=>String(a.id)!==String(t.id));this.setLocationsImpl({locations:[t,...s],options:{rootLocationId:t.id}})}catch(s){this.loggingService.catch("Error in DocService setRootLocation:",s)}})}setLocationsImpl({locations:t,options:i}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),t.length===0)return;if(!this.authService.getUser()){!i?.appendLocation&&t.length>0&&(this.draftLocationMap.options=le(M(M({},this.draftLocationMap.options??{}),i??{}),{rootLocationId:t[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...t],this.draftLocationMap.options=M(M({},this.draftLocationMap.options),i);return}let s=this.getValidLocations(t),a=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(d=>d.location.id)].filter(d=>d!==void 0);let l;if(i?.rootLocationId&&i?.rootLocationId!==this.location$.value?.location.id&&(l=s.find(d=>d.id===i?.rootLocationId),!l)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${i?.rootLocationId} not found in locations.`);return}if(i?.appendLocation){if(l){let d=Ld(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}}else{l||(l=s[0]);let d=Ld(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}let u=[];return s.slice(i?.appendLocation?0:1).forEach(d=>{if(d.id!==this.location$.value?.location.id){let f=M({},d),g=this.locations$.value;d?.id&&Object.keys(g).forEach(D=>{let L=g[D];L.location?.id===d.id&&(f=M(M({},L.location),d),delete g?.[D])});let p=this.genarateLocationId(f),_={locationId:p,location:f};f.id&&a.push({locationId:p,location:f}),u.push(_);let T=le(M({},g),{[p]:_});this.locations$.next(T)}}),this.updateDocumentLocationMetadata(a),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:Pn.SET_LOCATIONS,payload:{locations:s,options:i}}),this.analyticsService.trackEvent(P.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:s,options:i},!0,this.getUserIdForAnalytics()),u}catch(o){this.loggingService.catch("Error in setLocationImpl: ",o);return}}addLocation({location:t,source:i="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:{appendLocation:!0},methodName:"addLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:Pn.ADD_LOCATION,source:i,payload:{locations:[t],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[t],options:{appendLocation:!0}})}catch(o){this.loggingService.catch("Error in DocService addLocation:",o);return}}removeLocation({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[t],methodName:"removeLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:i,methodName:Pn.REMOVE_LOCATION,payload:{locations:[t]}}),t?this.removeLocationsImpl([t],i):i==="external"&&this.removeLocationsImpl(void 0,i)}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}removeLocations({locations:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t,methodName:"removeLocations",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:Pn.REMOVE_LOCATIONS,source:i,payload:{locations:t}}),this.removeLocationsImpl(t,i)}catch(o){this.loggingService.catch("Error in removeLocations: ",o)}}removeLocationsImpl(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t},methodName:"removeLocations",message:"System removed locations",source:i},!0,this.getUserIdForAnalytics()),t?t.forEach(o=>{let s=this.genarateLocationId(o);this.getLocation()?.locationId===s&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==o.id))),this.removeCustomLocation(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}unsetLocationIds(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:Pn.UNSET_LOCATION_IDS,source:i,payload:{locationIds:t}}),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:t},methodName:"unsetLocationIds",message:"System unset location ids",source:i},!0,this.getUserIdForAnalytics()),t?.length?t.forEach(o=>{this.getLocation()?.location.id===o&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==o))),this.removeCustomLocationId(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:Pn.REMOVE_LOCATIONS_SUCCESS,source:i,payload:{locationIds:t}}),this.analyticsService.trackEvent(P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetLocationIds: ",o)}}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(t){try{this.excludedLocationIds$.next([...t])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(t){return this.loggingService.catch("Error in getExcludedLocationIds$: ",t),de([])}}updateOrganizationMetadata(t){return I(this,null,function*(){try{!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig());let i=t?.organizationId,o=t?.clientOrganizationId,s=this.documentPaths$.value;if(this.db&&i&&s?.documentId){if(this.organizationMetadata$.value?.[i])return;let c=new ZT;c.apiKey=this.configService?.getApiKey()??"",c.organizationId=i,c.clientOrganizationId=o;let l=this.authService.getUser()?.userId??"",u=o?yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o}):null;!!(l&&o&&u?.[l]?.organization?.[o]?.errorCode===Rs.PERMISSION_DENIED)?this.loggingService.log(`%c[WB] updateOrganizationMetadata skipped \u2014 user does not have access to organization: ${o}`,"color: orange;"):this.userPermissionService?.hasEditAccess({organizationId:i})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(c)),properties:{organizationId:i,documentId:s?.documentId??""}})),yield this.fetchOrganizationMetadata(t)}}catch(i){this.loggingService.catch("Error in updateOrganizationMetadata: ",i)}})}updateFolderMetadata(){return I(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 t=this.documentPaths$.value;if(!t?.veltFolderId||!t?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:t?.organizationId??"",folderId:t?.veltFolderId??""}}))?.metadata){let o={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:t?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let s=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Md({methodName:"createFolder",data:{type:"createFolder",metadata:o},getSdkProxy:s,userId:this.authService.getUser()?.userId??""})}}}}catch(t){this.loggingService.catch("Error in updateFolderMetadata: ",t)}})}updateDocumentMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(s=>s.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});let o=i.map(s=>I(this,null,function*(){let a=new QT;this.clientDocumentMetadataMap?.[s.clientDocumentId]&&(a=M(M({},this.clientDocumentMetadataMap[s.clientDocumentId]),a)),a.apiKey=this.configService?.getApiKey()??"",a.documentId=s.documentId,a.clientDocumentId=s.clientDocumentId,a.organizationId=t.organizationId,a.clientOrganizationId=t.clientOrganizationId,a.pageInfo=Pg(s.clientDocumentId);let c=t?.folderId,l=t?.veltFolderId;a?.pageInfo?.deviceInfo&&delete a?.pageInfo?.deviceInfo;let u=!0,d=this.documentMetadata$.value?.[s.documentId];if(c&&l){let f=this.getDocumentMetadata(s?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}}));f?.clientDocumentId&&!f?.errorCode?f?.folderId&&(f?.folderId!==c||f?.veltFolderId!==l)?(this.loggingService.catch(`Folder id mismatch for document ${s?.clientDocumentId??""}`),u=!1):f?.folderId===c?(c&&(a.folderId=c),l&&(a.veltFolderId=l)):(this.loggingService.catch(`Document ${s?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(a.folderId=c),l&&(a.veltFolderId=l))}if(d){let f={};Object.entries(a).forEach(([g,p])=>{f[g]=p}),Ui(f,d)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:s?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:t?.organizationId??"",documentId:s?.documentId??""}}))}));yield Promise.allSettled(o),yield this.fetchDocumentMetadata(i)}}}catch(t){this.loggingService.catch("Error in updateDocumentMetadata: ",t)}})}updateDocumentLocationMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value;if(i){let o=this.getDocumentIds();o.find(s=>s.documentId===i.documentId)||o.push({documentId:i.documentId??"",clientDocumentId:i.clientDocumentId??""});for(let s of o){let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??"",field:"metadata"}});a?.errorCode&&(a={});let c=[];for(let l of t){let u=new JT;u.locationId=l?.locationId,u.veltLocationId=$C(l?.location?.id??""),u.location=l?.location,u.pageInfo=Pg(s?.clientDocumentId),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let d=le(M({},a),{[v.FIREBASE_PARTIAL_PATH_LOCATIONS]:le(M({},a[v.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[l?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??""}}));let f=this.locationMetadata$.value;if(f||(f={}),l?.location?.id){let g=f?.[s.documentId],p=g?.[l?.location?.id??""];f&&(g||(f[s.documentId]={}),p||(f[s.documentId][l?.location?.id??""]={}),f[s.documentId][l?.location?.id??""]=le(M({},p),{location:l?.location})),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}}yield Promise.allSettled(c)}}}}catch(i){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",i)}})}genarateLocationId(t){try{return t&&typeof t=="object"?Tr(JSON.stringify(Ld(t))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}removeCustomLocation(t,i="internal"){try{let o=this.genarateLocationId(t),s=this.locations$.value;s[o]&&(delete s[o],this.locations$.next(M({},s)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==t.id)))}catch(o){this.loggingService.catch("Error in DocService removeLocation:",o)}}removeCustomLocationId(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let o=this.locations$.value;Object.entries(o).forEach(([s,a])=>{a.location.id===t&&(delete o[s],this.locations$.next(M({},o)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==t)))})}catch(o){this.loggingService.catch("Error in DocService removeCustomLocationId:",o)}}getLocationByClientLocationId(t){try{let i=this.getLocation()?.location;if(i?.id===t)return i;{let o=this.getLocations();Object.keys(o).forEach(s=>{let a=o[s];a.location?.id===t&&(i=a.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let t=this.locations$.value,i=document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}]`),o=[];i.forEach(s=>{let a=s.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(a){let c=JSON.parse(a),l=this.genarateLocationId(c);o.push(l)}}),Object.keys(t).forEach(s=>{let a=t[s];o.includes(a.locationId)||delete t[s]}),this.locations$.next(M({},t))}catch(t){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",t)}}getLocations$(){try{return this.locations$.asObservable()}catch(t){return this.loggingService.catch("Error in DocService getLocations$:",t),de({})}}getLocations(){try{return this.locations$.value}catch(t){return this.loggingService.catch("Error in DocService getLocations:",t),{}}}getLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(t?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)?i=t:i=t.closest(`[${v.ATTRIBUTES.VELT_LOCATION}]`),i){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o){let s=JSON.parse(o);return{locationId:this.genarateLocationId(s),location:s}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let t={};return document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(o=>{if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let s=this.getLocationFromElement(o);s?.locationId&&(t[s.locationId]={element:o,location:s})}else if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let s=o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(s){let a=this.getLocationByClientLocationId(s);a?.locationId&&(t[a.locationId]={element:o,location:a});let c={id:s},l=this.genarateLocationId(c);t[s]={element:o,location:{locationId:l,location:c}}}}}),t}catch(t){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",t),{}}}getAdditionLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=t?.closest(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o)return JSON.parse(o)}else if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(o)return{id:o}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(t){try{return t?.closest(`[${v.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(v.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(t){try{return t?this.documentMetadata$.value?.[t]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata$(t){return this.getAllDocumentMetadataMap$().pipe(ge(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),rt(Pt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(t=>t||{}),rt(Pt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let t=this.documentMetadata$.value||{},i={},o=this.documentPaths$.value?.veltFolderId,s=this.documentPaths$.value?.allDocuments;if(o&&s)Object.values(t).forEach(a=>{a?.documentId&&a?.veltFolderId===o&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(c=>{let l=t?.[c.documentId];l&&(i[c.documentId]=l)});else if(this.documentPaths$.value?.documentId){let c=t?.[this.documentPaths$.value?.documentId];c&&(i[this.documentPaths$.value?.documentId]=c)}}return Object.values(i)}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",t),[]}}getDocumentMetadata$(t){return this.documentMetadata$.asObservable().pipe(ge(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),rt(Pt))}setDocumentMetadata(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let o=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));o[t]=i,this.documentMetadata$.next(o)}catch(o){this.loggingService.catch("Error in DocService setDocumentMetadata:",o)}}setAllDocumentMetadata(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(t)}catch(i){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",i)}}getOrganizationMetadata(t){return this.organizationMetadata$.value?.[t]||null}getOrganizationMetadata$(t){return this.organizationMetadata$.asObservable().pipe(ge(i=>i?.[t]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ge(t=>t||{}),rt(Pt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(rt(Pt))}getOrganizationConfig(){return this.organizationConfig$.value}setOrganizationConfig(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setOrganizationConfig","color: green;");let i=JSON.parse(JSON.stringify(t));this.organizationConfig$.next(i)}catch(i){return this.loggingService.catch("Error in DocService setOrganizationConfig:",i),!1}return!0}getMetadataFromType(t,i){try{switch(t){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(o){this.loggingService.catch("Error in DocService getMetadataFromType:",o);return}}getDefaultMetadata({clientDocumentId:t,documentId:i}){try{let o=this.documentPaths$.value;if(!o)return;let s=t||o.clientDocumentId,a=i||o.documentId,c=this.getDocumentMetadata(a);if(!c)return;let l=c?.folderId,u=c?.veltFolderId;return M(M({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:s,clientOrganizationId:o.clientOrganizationId,documentId:a,organizationId:o.organizationId},l?{folderId:l}:{}),u?{veltFolderId:u}:{})}catch(o){this.loggingService.catch("Error in DocService getDefaultMetadata:",o);return}}getBaseMetadata(t,i){try{let o,s;i?.element?o=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(o=i.clientDocumentId),o&&(s=this.generateDocumentId(o));let a=this.getMetadataFromType(t,i),c=this.getDefaultMetadata({clientDocumentId:o,documentId:s}),l=a||c||{};return l.sdkVersion=Gr(),l}catch(o){return this.loggingService.catch("Error in DocService getBaseMetadata:",o),{}}}getServerId({documentId:t,organizationId:i}){try{return t&&(t=this.generateDocumentId(t)),i&&(i=this.generateOrganizationId(i)),{documentId:t,organizationId:i}}catch(o){return this.loggingService.catch("Error in DocService getServerId:",o),null}}fetchDocuments(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(t?.folderId){let a=bo(t?.folderId);o.push(Ii("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ii("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(t){return I(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 o=[];if(!t?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(t?.folderId){let a=bo(t?.folderId);o.push(Ii("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ii("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(t){return I(this,null,function*(){try{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:o,documents:s,folderId:a}=t;if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Ds(o);if(!s||s.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let l=[],u=this.documentMetadata$.value??{};for(let d of s)if(d?.documentId){d.organizationId=c,d.clientOrganizationId=o,d.clientDocumentId=d.documentId;let f=_a(d.documentId);d.documentId=f,d.apiKey=this.configService.getApiKey()??void 0,(a||this.documentPaths$.value?.folderId)&&(d.folderId=a||this.documentPaths$.value?.folderId,d.veltFolderId=bo(a||this.documentPaths$.value?.folderId||""));let g=()=>{if(a&&this.documentPaths$.value?.folderId&&a!==this.documentPaths$.value?.folderId)return;let _=u?.[f];_?u[f]=M(M({},_),d):u[f]=d},p=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:f,organizationId:c,field:"metadata"}});if(p?.errorCode&&(p={}),p&&p.apiKey&&p.folderId&&a&&p.folderId!=d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists with different folderId: ${p.folderId}`);continue}if(p&&p.apiKey&&!p.folderId&&d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists, move this document to folder with REST API`);continue}g(),d&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:d?.documentId??""})&&l.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{organizationId:c,documentId:f}}))}yield Promise.all(l),this.setAllDocumentMetadata(u)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(t){return I(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:o,locations:s,documentIds:a}=t;if((!a||a.length===0)&&(a=this.documentIds$.value.map(d=>d.clientDocumentId)??[],a.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!s||s.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=a.map(d=>_a(d)),l=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(d=>{s.forEach(f=>{let g=this.location$.value;if(f?.id===g?.location?.id&&this.location$.next({locationId:g?.locationId,location:f}),f?.id){delete f?.metadata;let p=$C(f.id),_=u?.[d],T=_?.[f.id];u&&(_||(u[d]={}),T||(u[d][f.id]={}),u[d][f.id]=le(M({},T),{location:f})),f&&this.commonDbService&&l.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:f})),properties:{organizationId:Ds(o),documentId:d,id:p}}))}})}),yield Promise.all(l),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let s=[],a=this.generateOrganizationId(t?.organizationId);if(t?.folderId){let c=bo(t?.folderId);o=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}}),o&&(o=[o]),s=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[Ii("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}})}else o=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}});return{data:o,parentFolders:s}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(pt(t=>t?this.documentPaths$.pipe(pt(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ge(o=>o?.data?.docIamConfig??o?.data),rt((o,s)=>JSON.stringify(o??{})===JSON.stringify(s??{}))):de(null))):de(null)))}getDocumentAccessType(t){try{return t&&t.features&&t.features.all?t.features.all.restricted?Mt.RESTRICTED:Mt.PUBLIC:t&&t.documentAccessType?t.documentAccessType:Mt.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),Mt.PUBLIC}}changeDocumentAccessType(t){return I(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});if(o?.errorCode)return;switch(delete o.documentAccessType,o.features||(o.features={}),o.features.all||(o.features.all={}),t){case Mt.PUBLIC:o.features.all.restricted=!1;break;case Mt.RESTRICTED:o.features.all.restricted=!0,o.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(o)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(t){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",t),""}}setUIState(t){try{this.uiState.next(M(M({},this.uiState.value),t))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};e.\u0275fac=function(i){return new(i||e)(C(Ot),C(Dr),C(cc),C(bv),C(Xn),C(me),C(qo),C(Ko),C(lc),C(vt),C(ur),C(di))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var jt=(()=>{let e=class e{constructor(t,i,o,s,a){this.analyticsService=t,this.authService=i,this.coreActionsService=o,this.docService=s,this.loggingService=a,this.resolveOrganizationUsers=new Y(!0),this.resolveFolderUsers=new Y(!0),this.resolveDocumentUsers=new Y(!0),this.unresolvedUsers=new Y([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new mt,this.userDataProvider$=new Y(null),this.anonymousUserDataProvider$=new Y(null),this.userIdByEmailCache={},this.userById$=new Y({}),this.customContactUserById$=new Y({}),this.userByIdCalled$=new Y({}),this.pendingResolutions=new Set,this.getUserById=c=>{try{let l=this.userById$.value?.[c],u=this.customContactUserById$.value?.[c];return u?l?M(M({},l),u):u:l}catch(l){this.loggingService.catch("Error in UsersService getUserById:",l);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Rt(c=>!!c),pt(()=>this.getUnresolvedUsers$().pipe(Rt(c=>c.length>0),Mu(300),Dt(20),pt(c=>{let l=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:l,isCollection:!0,useQuery:!0,firestoreQuery:[rS(Ii("user.userId","in",c.slice(0,20)))]}}).pipe(ge(u=>u?.data),ea(u=>{if(u&&typeof u=="object"){delete u.undefined,delete u.null;let d=Object.values(u??{}),f=d.map(p=>p?.user).filter(p=>!!p&&(!!p.name||!!p.email||!!p.photoUrl));f.length>0&&this.setUserByIds(f);let g=c.filter(p=>!d.some(_=>_.user.userId===p));g.length!==c.length&&this.setUnresolvedUsers(g)}})):de([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}setCommonDbService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=t}catch(i){this.loggingService.catch("Error in UsersService setCommonDbService:",i)}}setContactService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=t}catch(i){this.loggingService.catch("Error in UsersService setContactService:",i)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(t){this.loggingService.catch("Error in UsersService ngOnDestroy:",t)}}isResolverForFeatureDisabled(t){let i=this.userDataProvider$.getValue();try{switch(t){case"allOrganizationUsers":return i?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return i?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return i?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(o){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",o),!1}}resolveUsers(u){return I(this,arguments,function*({userIds:t,forceResolve:i,feature:o,organizationId:s,skipUserCheck:a=!1,uniqueId:c,moduleName:l}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let d=!1;if(o&&(d=this.isResolverForFeatureDisabled(o)),d)return{};{let f={},g=[],p={};if(t?.forEach(_=>{let T=this.getUserById(_);T?f[_]=T:this.userByIdCalled$.getValue()[_]?i&&g.push(_):(g.push(_),this.userByIdCalled$.next(le(M({},this.userByIdCalled$.getValue()),{[_]:!0})))}),g.length>0){let _=c||Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:_,moduleName:l,methodName:Ln.RESOLVE_USERS,source:"internal",payload:{userIds:g,organizationId:s,feature:o,forceResolve:i,skipUserCheck:a,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let T={},D=!1,L=new Set;try{let B,w=new Promise((U,A)=>{B=setTimeout(()=>{A(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)}),F=yield Promise.race([this.getUsersFromDB({userIds:g,organizationId:s,skipUserCheck:a}).finally(()=>{clearTimeout(B)}),w]);F==null?D=!0:T=F,this.analyticsService.trackEvent(P.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:g}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:_,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{result:T,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(B){D=!0,this.loggingService.catch("Error in UsersService resolveUsers getUsers:",B,{userIds:g}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:B,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{let B=this.authService.getProvidedOrCurrentUserId?.();g?.forEach(w=>{if(!T[w]){let F=new Set([...this.getUnresolvedUsers(),w]);if(this.unresolvedUsers.next(Array.from(F)),D&&this.clearUserByIdCalledFlag(w),B&&w===B)return;T[w]={userId:w,name:`User ${w}`},D&&L.add(w)}})}Object.entries(T).forEach(([B,w])=>{w&&(f[B]=T?.[B],L.has(B)||(p[B]=T?.[B]))}),L.size>0&&this.authService.setOptionalPropertiesToUsers(Array.from(L).map(B=>T[B]).filter(Boolean))}return Object.keys(p).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(p)),this.mergeUsersIntoStore(Object.values(p)),Object.keys(p).forEach(_=>{let T=this.getUserById(_);T&&(f[_]=T)})),f}}catch(d){this.loggingService.catch("Error in UsersService resolveUsers:",d);let f=c||Z();return this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:d,userIds:t,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}clearUserByIdCalledFlag(t){try{let i=this.userByIdCalled$.getValue();if(i?.[t]){let o=M({},i);delete o[t],this.userByIdCalled$.next(o)}}catch(i){this.loggingService.catch("Error in UsersService clearUserByIdCalledFlag:",i)}}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(t){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",t),[]}}setUnresolvedUsers(t){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(t)){let i=JSON.parse(JSON.stringify(t));this.unresolvedUsers.next(i)}}catch(i){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",i)}}getUsersFromDB(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let a=this.userDataProvider$.getValue();if(a){if(a.config?.getConfig?.url){if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),null;let d={organizationId:i,userIds:t},f=yield $t(a.config.getConfig.url,a.config.getConfig.headers,d,!0,a.config.getConfig.credentials);return f.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${f.statusCode}. Message: ${f.message||"Unknown error"}`),null):f.data??{}}let u=yield a.get(t);if(u&&typeof u=="object"&&"success"in u&&"statusCode"in u&&typeof u.success=="boolean"&&typeof u.statusCode=="number"){let d=u;return d.statusCode===200&&d.data?d.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${d.statusCode}`),null)}return u}if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return null;let c=(yield this.getUsersFromDBWithBatching({userIds:t,organizationId:i,skipUserCheck:o}))??[];this.contactService?.setResolvedUsers(c.flat());let l={};return c.forEach(u=>{u.forEach(d=>{d?.user?.userId&&(l[d.user.userId]=d.user)})}),l}catch(a){return this.loggingService.catch("Error in UsersService getUsersFromDB:",a),null}})}getUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){try{if(!t?.length)return[];let a=[];for(let u=0;u<t.length;u+=30)a.push(t.slice(u,u+30));let c=a.map((u,d)=>I(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Ii("user.userId","in",u)],skipUserCheck:o}}))||[]}catch(f){return this.loggingService.catch(`Error in batch ${d+1}:`,f),[]}}));return yield Promise.all(c)}catch(a){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",a),[]}})}getTemporaryUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,resourceIds:o}){try{if(!t?.length||!o?.length)return[];let a=[];for(let _=0;_<t.length;_+=30)a.push(t.slice(_,_+30));let c=[];for(let _=0;_<o.length;_+=30)c.push(o.slice(_,_+30));let l=[],u=0,d=(_,T)=>I(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[rS(Ii("userId","in",_),Ii("veltResourceId","in",T))]}}))??[])||[]}catch(D){return this.loggingService.catch(`Error in batch ${u+1}:`,D),[]}});for(let _ of a)for(let T of c)l.push(d(_,T)),u++;return(yield Promise.all(l)).flat().filter((_,T,D)=>T===D.findIndex(L=>L.userId===_.userId&&L.resourceId===_.resourceId))}catch(a){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",a),[]}})}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;"),ti([this.userById$,this.customContactUserById$]).pipe(ge(([t,i])=>this.applyContactOverlay(t,i)),rt(Pt))}catch(t){return this.loggingService.catch("Error in UsersService getUserById$:",t),de({})}}applyContactOverlay(t,i){let o=M({},t??{});return Object.entries(i??{}).forEach(([s,a])=>{o[s]=M(M({},o[s]??{}),a)}),o}setUserByIds(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;"),this.mergeUsersIntoStore(t)}catch(i){this.loggingService.catch("Error in UsersService setUserByIds:",i)}}setContactListUsers(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactListUsers","color: green;");let i={};(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=JSON.parse(JSON.stringify(o)))}),this.customContactUserById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService setContactListUsers:",i)}}getContactListUser(t){try{return this.customContactUserById$.value?.[t]}catch(i){this.loggingService.catch("Error in UsersService getContactListUser:",i);return}}mergeUsersIntoStore(t){try{let i=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=M(M({},i?.[s]??{}),o))}),this.userById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService mergeUsersIntoStore:",i)}}setUserDataProvider(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let i=t.config?.getConfig?.url,o="get"in t&&typeof t.get=="function";if(!i&&!o){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(t),t.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),t.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),t.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}setAnonymousUserDataProvider(t){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in t)||typeof t.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(t)}catch(i){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",i)}}resolveUserIdsByEmail(o){return I(this,arguments,function*({emails:t,uniqueId:i}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!t?.length)return{};let s=this.anonymousUserDataProvider$.getValue();if(!s||typeof s.resolveUserIdsByEmail!="function")return{};let a=[...new Set(t.filter(w=>!!w))];if(a.length===0)return{};let c={},l=[];if(a.forEach(w=>{let F=this.userIdByEmailCache[w];F?c[w]=F:l.push(w)}),l.length===0)return c;let u=this.docService.getOrganizationConfig()?.clientOrganizationId||"",d=this.docService.getDocumentPaths()?.clientDocumentId||"",f=this.docService.getDocumentPaths()?.folderId||"",g={organizationId:u,documentId:d,folderId:f,emails:l},p=i||Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:l,organizationId:u,documentId:d,folderId:f}});let _=s.config?.resolveTimeout||this.resolveTimeout,T,D=new Promise((w,F)=>{T=setTimeout(()=>{F(new Error("resolveUserIdsByEmail timeout"))},_)}),L=s.config?.getRetryConfig||{retryCount:0,retryDelay:0},B=I(this,null,function*(){try{let w=yield xt(()=>s.resolveUserIdsByEmail(g),"resolveUserIdsByEmail",L);return w?.statusCode===200&&w?.data?w.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${w?.statusCode}. Message: ${w?.message||"Unknown error"}`),{})}finally{clearTimeout(T)}});try{let w=yield Promise.race([B,D]);return Object.entries(w).forEach(([F,U])=>{U&&(this.userIdByEmailCache[F]=U,c[F]=U,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:U,name:F,email:F},currentUserId:this.authService.getUser()?.userId??""}).catch(A=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",A)}))}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:w,emails:l}}),c}catch(w){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",w),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:w,emails:l}}),c}}catch(s){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",s),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",t),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(t){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(Ot),C(Dr),C(vt),C(ef),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var uc=class{static getFirestoreProdDbName(e,n){return n?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||n?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(n){return j.error("Error in isTestingDb:",n),!1}}};var cS=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.commentAnnotationsResolverService=c,this.attachmentResolverService=l,this.coreActionsService=u,this.endpointsService=J(xo),this.notificationActionTypeMap={[ye.NEWLY_ADDED]:Qt.COMMENT_ANNOTATION_ADD,[ye.ADDED]:Qt.COMMENT_ADD,[ye.UPDATED]:Qt.COMMENT_UPDATE,[ye.DELETED]:Qt.COMMENT_DELETE},this.additionalEventTypeMap={[ye.STATUS_CHANGED]:ar.STATUS_CHANGE,[ye.PRIORITY_CHANGED]:ar.PRIORITY_CHANGE,[ye.ASSIGNED]:ar.ASSIGN,[ye.ACCESS_MODE_CHANGED]:ar.ACCESS_MODE_CHANGE,[ye.CUSTOM_LIST_CHANGED]:ar.CUSTOM_LIST_CHANGE,[ye.APPROVED]:ar.APPROVE,[ye.ACCEPTED]:ar.ACCEPT,[ye.REJECTED]:ar.REJECT,[ye.SUGGESTION_ACCEPTED]:ar.SUGGESTION_ACCEPT,[ye.SUGGESTION_REJECTED]:ar.SUGGESTION_REJECT,[ye.REACTION_ADDED]:ar.REACTION_ADD,[ye.REACTION_DELETED]:ar.REACTION_DELETE,[ye.SUBSCRIBED]:ar.SUBSCRIBE,[ye.UNSUBSCRIBED]:ar.UNSUBSCRIBE}}setNotificationService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}setUserPermissionService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",i)}}getUserIdsToResolveFromComments(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let o of t){if(o?.from?.userId&&i.add(o?.from?.userId),o?.comments)for(let s of o?.comments){if(s?.from?.userId&&i.add(s?.from?.userId),s?.to)for(let a of s?.to)a?.userId&&i.add(a?.userId);if(s?.taggedUserContacts)for(let a of s?.taggedUserContacts)a?.userId&&i.add(a?.userId)}if(o?.assignedTo?.userId&&i.add(o?.assignedTo?.userId),o?.resolvedByUserId&&i.add(o?.resolvedByUserId),o?.suggestion?.resolvedBy?.userId&&i.add(o?.suggestion?.resolvedBy?.userId),o?.subscribedUsers)for(let s of Object.values(o?.subscribedUsers))s.user.userId&&i.add(s.user.userId);if(o?.unsubscribedUsers)for(let s of Object.values(o?.unsubscribedUsers))s.user.userId&&i.add(s.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.suggestion?.resolvedBy?.userId){let i=this.usersService.getUserById(t?.suggestion?.resolvedBy?.userId);i&&(t.suggestion.resolvedBy=i)}if(t?.comments)for(let i of t?.comments){if(i?.from?.userId){let s=this.usersService.getUserById(i?.from?.userId);s&&(i.from=s)}i?.to&&(i.to=i?.to?.map(s=>{if(s?.userId){let a=this.usersService.getUserById(s?.userId);if(a)return M(M({},s),a)}return s})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(s=>{if(s?.contact){let a=this.usersService.getUserById(s?.contact?.userId);a&&(s.contact=a,(a?.name||a?.email)&&(s.text=`@${a?.name||a?.email}`))}return s}));let o=i?.taggedUserContacts?.filter((s,a,c)=>c.findIndex(l=>l.text===s.text)===a)||[];o.sort((s,a)=>(a.text?.length||0)-(s.text?.length||0)),o.forEach(s=>{if(s?.text){let a=new RegExp(dl(`{{${s.userId}}}`),"g");i.commentText?.includes(`@User ${s.userId}`)&&(a=new RegExp(dl(`@User ${s.userId}`),"g")),i.commentText=i.commentText?.replaceAll(a,s.text),i.commentHtml=i.commentHtml?.replaceAll(a,s.text)}})}if(t?.assignedTo?.userId){let i=this.usersService.getUserById(t?.assignedTo?.userId);i&&(t.assignedTo=i)}if(t?.resolvedByUserId){let i=this.usersService.getUserById(t?.resolvedByUserId);i&&(t.resolvedByUser=i)}if(t?.subscribedUsers)for(let i of Object.values(t?.subscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.subscribedUsers?.id?.user&&(t.subscribedUsers.id.user=o)}if(t?.unsubscribedUsers)for(let i of Object.values(t?.unsubscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.unsubscribedUsers?.id?.user&&(t.unsubscribedUsers.id.user=o)}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),t}}formatCommentData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),t?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),t?.viewedBy&&delete t.viewedBy,t?.unread!==void 0&&delete t.unread,t?.resolvedByUser!==void 0&&delete t.resolvedByUser,t?.comments&&t.comments.forEach(i=>{i?.reactionAnnotations&&delete i.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.assignedTo?.userId&&(t.assignedTo={userId:t.assignedTo.userId}),t?.subscribedUsers)for(let i of Object.keys(t?.subscribedUsers))t.subscribedUsers[i].user={userId:t?.subscribedUsers[i].user.userId};if(t?.unsubscribedUsers)for(let i of Object.keys(t?.unsubscribedUsers))t.unsubscribedUsers[i].user={userId:t?.unsubscribedUsers[i].user.userId};t?.suggestion?.resolvedBy?.userId&&(t.suggestion.resolvedBy={userId:t.suggestion.resolvedBy.userId})}return t?.comments&&(t.comments=t?.comments?.map(i=>this.formatCommentThreadData(i))),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),t}}mergeStrippedDataWithCommentAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.annotationId),o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove();return i&&(t?.comments?.forEach(a=>{let c=i?.comments?.[a?.commentId];if(c){a.commentHtml=c?.commentHtml,a.commentText=c?.commentText;let l=c?.attachments;o&&l&&a.attachments?.forEach(u=>{let d=u?.attachmentId;l?.[d]&&(u.name=l?.[d]?.name,u.url=l?.[d]?.url)})}}),i?.targetTextRange?.text&&t?.targetTextRange&&(t.targetTextRange.text=i?.targetTextRange?.text),s?.length>0&&s.forEach(a=>{i?.[a]&&(t[a]=i[a])})),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),t}}mergeLocationWithCommentAnnotations(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let o=t?.location?.id,s=t?.metadata?.documentId;if(!o||!s)return t;let a=i?.[s]?.[o];return a&&(t.location=a?.location),t}catch(o){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",o),t}}isCommentsDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let o=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return o?!Ui(t,o):!0}catch(o){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",o),!0}}stripCommentsFromAnnotationData({comment:t}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!i)return t;let o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=new KT;if(Object.assign(s,t),s.isCommentResolverUsed=i,o){let a=s.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));s.attachments=a}return delete s?.commentHtml,delete s?.commentText,s}catch(i){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",i),t}}resolveTaggedUserEmails(t){return I(this,null,function*(){try{let i=new Set;if(t.comments?.forEach(o=>{o.taggedUserContacts?.forEach(s=>{s?.contact?.email&&!s?.userId&&i.add(s.contact.email)}),o.to?.forEach(s=>{s?.email&&!s?.userId&&i.add(s.email)})}),i.size>0){let o=Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(i)}});let s=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(i),uniqueId:o});Object.keys(s).length>0&&t.comments?.forEach(a=>{a.taggedUserContacts?.forEach(c=>{if(c?.contact?.email&&!c?.userId){let l=s[c.contact.email];if(l){let u=c.text;if(u){let d=dl(u),f=new RegExp(d,"g");a.commentText&&(a.commentText=a.commentText.replace(f,`{{${l}}}`)),a.commentHtml&&(a.commentHtml=a.commentHtml.replace(f,`{{${l}}}`))}c.userId=l,c.contact.userId=l,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),a.to=a.to?.map(c=>{if(c?.email&&!c?.userId){let l=s[c.email];if(l)return delete c?.email,delete c?.visibility,le(M({},c),{userId:l})}return c})})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",i),t}})}stripCommentAnnotationData(s){return I(this,arguments,function*({data:t,actionType:i,commentId:o}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),t=yield this.resolveTaggedUserEmails(t),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),l=this.commentAnnotationsResolverService.getAdditionalFields(),u,d;i&&(u=this.notificationActionTypeMap?.[i],d=this.additionalEventTypeMap?.[i]);let f=this.commentAnnotationsResolverService.getAdditionalSaveEvents(),g=Array.isArray(f)?f:[],p={},_=null,T=!1;if(t&&t.annotationId){let w=t.annotationId;if(p[w]=M(M(M(M({annotationId:w,metadata:yn(t.metadata??{}),comments:{}},t?.from&&{from:t?.from}),t?.assignedTo&&{assignedTo:t?.assignedTo}),t?.resolvedByUserId&&{resolvedByUserId:t?.resolvedByUserId}),t?.targetTextRange?.text&&{targetTextRange:{text:t?.targetTextRange?.text}}),delete t?.targetTextRange?.text,c?.length>0&&c.forEach(U=>{t?.[U]&&(p[w][U]=t[U],delete t[U])}),l?.length)for(let U of l)t?.[U]!==void 0&&(p[w][U]=JSON.parse(JSON.stringify(t[U])));t.comments?.forEach(U=>{if(U.commentId){let A;a&&(A={},U.attachments?.forEach(R=>{A[R.attachmentId]={attachmentId:R.attachmentId,name:R.name,url:R.url}})),p[w].comments[U.commentId]=M(M(M(M(M(M({commentId:U.commentId},U?.commentHtml&&{commentHtml:U?.commentHtml}),U?.commentText&&{commentText:U?.commentText}),A&&{attachments:A}),U?.from&&{from:U?.from}),U?.to&&{to:U?.to}),U?.taggedUserContacts&&{taggedUserContacts:U?.taggedUserContacts})}}),T=this.isCommentsDataChanged(p[w],w);let F=new qT;Object.assign(F,t),c?.length>0&&c.forEach(U=>{U in t||delete F[U]}),F.comments=t.comments?.map(U=>this.stripCommentsFromAnnotationData({comment:U}))||[],_=F}let D=_?.comments?.find(w=>w.commentId===o);D?.isDraft&&(u=_?.comments?.length&&_?.comments?.length>0?Qt.COMMENT_ADD:Qt.COMMENT_ANNOTATION_ADD);let L=!!i&&!!this.notificationActionTypeMap?.[i],B=!!d&&!!_&&!L&&!D?.isDraft&&g.includes(d);return B&&(u=d),{strippedData:T&&(i&&this.notificationActionTypeMap?.[i]||D?.isDraft)||B?p:null,originalData:_,eventType:u}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}})}formatCommentThreadData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to&&(t.to=t?.to?.map(o=>o?.userId?{userId:o.userId}:o)),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(o=>o?.contact?.userId?le(M({},o),{contact:{userId:o.contact.userId}}):o));let i=t?.taggedUserContacts?.filter((o,s,a)=>a.findIndex(c=>c.text===o.text)===s)||[];i.sort((o,s)=>(s.text?.length||0)-(o.text?.length||0)),i.forEach(o=>{if(o?.text&&o?.contact?.userId){let s=new RegExp(dl(o.text),"g");t.commentText=t.commentText?.replaceAll(s,a=>`{{${o.userId}}}`),t.commentHtml=t.commentHtml?.replaceAll(s,a=>`{{${o.userId}}}`)}}),i.forEach(o=>{o?.text&&o?.contact?.userId&&(o.text="")})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),t}}applyNotificationVisibility({annotation:t,extraData:i,deniedForYouUsers:o}){try{let s=jC(t);if(!s)return o??[];i&&typeof i=="object"&&(i.visibility=s);let a=Object.values(i?.annotationData?.subscribedUsers||{}).map(l=>l?.user?.userId).filter(l=>!!l),c=GV(t,a);return[...new Set([...o??[],...c])]}catch(s){return this.loggingService.catch("Error in CommentUtilsService applyNotificationVisibility:",s),o??[]}}getDeniedForYouUsers(i){return I(this,arguments,function*({extraData:t}){try{let o=Object.values(t?.annotationData?.subscribedUsers||{}).map(a=>a.user.userId)??[],s=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&o.length){let a=t?.metadata?.clientDocumentId,c=t?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?t?.annotationData?.context?.access:null,l=[];o.forEach(f=>{if(l.push({userId:f,resource:{id:a,type:ki.DOCUMENT,source:Qn.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0}}),c){let g=JSON.stringify(c);l.push({userId:f,resource:{id:g,type:ki.CONTEXT,source:Qn.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let u=Z();this.coreActionsService.triggerAction(H.PERMISSION_PROVIDER,{event:P.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Qn.SET_NOTIFICATIONS,uniqueId:u,timestamp:new Date().getTime(),source:"internal",payload:{requests:l}});let d=yield this.userPermissionService?.onResourceAccessRequired({requests:l,uniqueId:u,methodName:Qn.SET_NOTIFICATIONS});d?.success&&d?.data?.length&&d.data.forEach(f=>{f.hasAccess||s.push(f.userId)})}return s}catch(o){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",o),[]}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let l=iI(this.authService.getFirebaseConfig()?.firebaseOptions),u=Rr(this.functions,Ir({url:this.endpointsService.getSetEncryptedDataUrl(l),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d={from:t?.from,visibilityConfig:t?.visibilityConfig,context:{accessFields:t?.context?.accessFields}};if(o){o=this.notificationService?.processNotificationData(o),o.annotationData=t;let T=o?.targetAnnotationData?.commentId;if(T){let D=t?.comments?.find(L=>L?.commentId===T);D&&(o.targetAnnotationData=D)}try{let D=yield this.stripCommentAnnotationData({data:o.annotationData,actionType:o?.actionType??ye.NEWLY_ADDED});D?.originalData&&(o.annotationData=this.formatCommentData(D.originalData)),o?.targetAnnotationData&&(o.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:o.targetAnnotationData})))}catch(D){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",D)}}let f=uc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=yield this.getDeniedForYouUsers({extraData:o});g=this.applyNotificationVisibility({annotation:d,extraData:o,deniedForYouUsers:g});let p={path:i??"",data:t??{},dbId:f??"",notificationData:o||void 0,notificationURL:this.endpointsService.getNotificationsDbUrl(),feature:"comment",eventType:s??"PATCH",sdkVersion:Gr(),deniedForYouUsers:g,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),isCrossOrganizationEnabled:this.notificationService?.getCrossOrganizationConfig()?.enabled,metadata:a},_=yield hl(p,this.authService.getUser()?.userId??"");yield u({veltData:_})}catch(l){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",l)}})}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(Dr),C(ur),C(Xn),C(qo),C(Zh),C(vt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var lS=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Y(null),this.activityById$=new Y({}),this.fieldsToRemove=[],this.getActivityById=s=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ActivityResolverService getActivityById:",a);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove))})}catch(s){this.loggingService.catch("Error in ActivityResolverService constructor:",s)}}getProvider(){try{let t=this.activityDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ActivityResolverService getProvider:",t);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(t){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",t)}}resolveActivities(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:t}}),f(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.activityIds||[])],T=le(M({},t),{activityIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let L=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in ActivityResolverService resolveActivities:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.activityById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.activityById$.next(M(M({},this.activityById$.getValue()),w)),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveActivity(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let o=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=M(M({},a),t.activity);let c=yield xt(()=>{if(o?.config?.saveConfig?.url){let l={activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=a),this.loggingService.catch(c?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(t.activity),event:t.event}),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ActivityResolverService saveActivity:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{error:o,request:t}}),{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()):de(void 0)}catch(t){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",t),de(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",t),this.fieldsToRemove}}setActivityDataProvider(t){try{if(t){this.loggingService.log("Setting activity data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.activityDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",i)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var uS=(()=>{let e=class e{constructor(t,i,o,s,a,c){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.reactionAnnotationsResolverService=c,this.endpointsService=J(xo)}getUserIdsToResolveFromReactions(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o?.from?.userId),o?.reactions?.length)for(let s of o?.reactions)s?.from?.userId&&i.add(s?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{let a=iI(this.authService.getFirebaseConfig()?.firebaseOptions),c=Rr(this.functions,Ir({url:this.endpointsService.getSetEncryptedDataUrl(a),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),l=uc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",d={path:i??"",data:t??{},dbId:l??"",feature:"reaction",eventType:o??"PATCH",sdkVersion:Gr()},f=yield hl(d,u);yield c({veltData:f})}catch(a){this.loggingService.catch("Error in handleReactionEncryption:",a)}})}mergeReactionWithUser(t){try{if(this.usersService.userDataProviderAvailable()){if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.reactions?.length){for(let i of t?.reactions)if(i?.from?.userId){let o=this.usersService.getUserById(i?.from?.userId);o&&(i.from=o)}}}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),t}}formatReactionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t.reactions=t?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),t}}isReactionDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let o=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return o?!Ui(t,o):!0}catch(o){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",o),!0}}stripReactionAnnotationData(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let i={},o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(t&&t.annotationId){let s=t.annotationId;if(i[s]=M({annotationId:s,metadata:yn(t.metadata??{}),icon:t.icon},t?.from&&{from:t?.from}),o?.length>0)for(let c of o)t?.[c]!==void 0&&(i[s][c]=t[c],delete t[c]);if(!this.isReactionDataChanged(i[s],s))return{strippedData:null,originalData:t};delete t?.icon,t.isReactionResolverUsed=!0}return{strippedData:i,originalData:t}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return t;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t?.annotationId);if(i){i.icon&&(t.icon=i.icon);let o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(o?.length>0)for(let s of o)i?.[s]!==void 0&&(t[s]=i[s])}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(Dr),C(ur),C(Xn),C(Ko))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var dS=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d){this.loggingService=t,this.usersService=i,this.commentUtilsService=o,this.reactionUtilsService=s,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=c,this.recorderAnnotationsResolverService=l,this.activityResolverService=u,this.serviceBook=d}getActivityDisplayMessage(t){try{switch(t.featureType){case"comment":return this.getCommentDisplayMessage(t);case"recorder":return this.getRecorderDisplayMessage(t);case"reaction":return this.getReactionDisplayMessage(t);case"crdt":return this.getCrdtDisplayMessage(t);case"custom":return t.displayMessageTemplate&&t.displayMessageTemplateData?this.resolveTemplate(t.displayMessageTemplate,t.displayMessageTemplateData):"";default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",i),""}}resolveTemplate(t,i){try{return t.replace(/\{\{([\w.]+)\}\}/g,(o,s)=>{let a=s.split(".").reduce((c,l)=>{if(c!=null&&typeof c=="object")return c[l]},i);return a!=null?String(a):""})}catch(o){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",o),t}}buildActivityDataFromExtraData(t){try{let{feature:i,extraData:o}=t;if(!o?.actionType)return null;switch(i){case"comment":return this.buildCommentActivityData({commentAnnotation:o.annotationData,targetComment:o.targetAnnotationData,actionType:o.actionType,otherFields:o});case"recorder":return this.buildRecorderActivityData(o);case"reaction":return this.buildReactionActivityData(o);default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",i),null}}stripActivityPII(t){return I(this,null,function*(){try{let i=JSON.parse(JSON.stringify(t));if(delete i.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:i};i.actionUser?.userId&&(i.actionUser={userId:i.actionUser.userId}),i.changes&&this.stripUsersFromChanges(i.changes),i.displayMessageTemplateData&&this.stripUsersFromTemplateData(i.displayMessageTemplateData);let o=this.extractCommentChangesForResolver(i),s=this.extractFeatureEntityDataForResolver(i);yield this.stripFeatureSpecificPII(i);let a=this.extractActivityResolverData(i);return o&&(a?a.changes=M(M({},a.changes),o.changes):a=o),s&&(a?(s.entityData!==void 0&&(a.entityData=s.entityData),s.entityTargetData!==void 0&&(a.entityTargetData=s.entityTargetData)):a=s),a&&(i.isActivityResolverUsed=!0),{strippedActivity:i,activityResolverData:a}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",i),{strippedActivity:t}}})}mergeActivityWithUser(t){try{if(!this.usersService.userDataProviderAvailable())return t;if(t=JSON.parse(JSON.stringify(t)),t.actionUser?.userId){let i=this.usersService.getUserById(t.actionUser.userId);i&&(t.actionUser=i)}return t.changes&&this.rehydrateUsersInChanges(t.changes),t.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(t.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(t),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",i),t}}mergeActivityWithFeatureData(t){try{switch(t.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(t);case"reaction":return this.mergeActivityWithReactionData(t);case"recorder":return this.mergeActivityWithRecorderData(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",i),t}}getUserIdsToResolveFromActivities(t){try{let i=new Set;for(let o of t){if(o.actionUser?.userId&&i.add(o.actionUser.userId),o.changes)for(let s of Object.values(o.changes))s&&(this.extractUserIdFromValue(s.from,i),this.extractUserIdFromValue(s.to,i));if(o.displayMessageTemplateData)for(let s of Object.values(o.displayMessageTemplateData))this.extractUserIdFromValue(s,i);this.extractFeatureSpecificUserIds(o,i)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",i),[]}}getEntityIdsToResolveFromActivities(t,i){try{let o=new Set;for(let s of t)if(!(i&&s.featureType!==i))switch(s.featureType){case"comment":case"reaction":case"recorder":s.targetEntityId&&o.add(s.targetEntityId);break}return Array.from(o)}catch(o){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",o),[]}}stripFeatureSpecificPII(t){return I(this,null,function*(){try{switch(t.featureType){case"comment":yield this.stripCommentPII(t);break;case"reaction":this.stripReactionPII(t);break;case"recorder":this.stripRecorderPII(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",i)}})}extractActivityResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let i={id:t.id},o=!1,s=this.activityResolverService.getFieldsToRemove();for(let a of s)a in t&&t[a]!==void 0&&(i[a]=t[a],delete t[a],o=!0);return t.metadata&&(i.metadata=yn(t.metadata)),o?i:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",i);return}}extractCommentChangesForResolver(t){try{return!this.activityResolverService.activityDataProviderAvailable()||t.featureType!=="comment"||!t.changes?.commentText?void 0:{id:t.id,changes:{commentText:t.changes.commentText},metadata:t.metadata?yn(t.metadata):void 0}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",i);return}}extractFeatureEntityDataForResolver(t){try{if(!this.activityResolverService.activityDataProviderAvailable()||!t.entityData)return;let i=t.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),o=t.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!i&&!o)return;let s={id:t.id,metadata:t.metadata?yn(t.metadata):void 0},a=JSON.parse(JSON.stringify(t.entityData));if(i){let c=this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:a});if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}if(o){let c=this.reactionUtilsService.stripReactionAnnotationData(a);if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}return s.entityData?s:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",i);return}}mergeActivityWithResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return t;let i=this.activityResolverService.getActivityById(t.id);if(!i)return t;i.changes&&(t.changes||(t.changes={}),Object.assign(t.changes,i.changes)),i.entityData!==void 0&&(t.entityData=i.entityData),i.entityTargetData!==void 0&&(t.entityTargetData=i.entityTargetData),i.displayMessageTemplateData&&(t.displayMessageTemplateData||(t.displayMessageTemplateData={}),Object.assign(t.displayMessageTemplateData,i.displayMessageTemplateData));let o=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[s,a]of Object.entries(i))!o.has(s)&&a!==void 0&&(t[s]=a);return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",i),t}}rehydrateFeatureSpecificUserData(t){try{switch(t.featureType){case"comment":this.rehydrateCommentUserData(t);break;case"reaction":this.rehydrateReactionUserData(t);break;case"recorder":this.rehydrateRecorderUserData(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",i)}}getCommentDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Me.ANNOTATION_ADD:return`${i} added a comment`;case Me.COMMENT_ADD:return`${i} replied to a comment`;case Me.COMMENT_UPDATE:return`${i} edited a comment`;case Me.COMMENT_DELETE:return`${i} deleted a comment`;case Me.ANNOTATION_DELETE:return`${i} deleted a comment thread`;case Me.STATUS_CHANGE:{let o=t.changes?.status,s=o?.from?.name,a=o?.to?.name;return s&&a?`${i} changed status from ${s} to ${a}`:`${i} changed the status`}case Me.PRIORITY_CHANGE:{let o=t.changes?.priority,s=o?.to;if(!s)return`${i} removed the priority`;let a=typeof s=="object"?s?.name:String(s),c=o?.from,l=c&&typeof c=="object"?c?.name:c?String(c):null;return l&&a?`${i} changed priority from ${l} to ${a}`:`${i} changed priority to ${a}`}case Me.ASSIGN:{let s=t.changes?.assignedTo?.to;return s&&typeof s=="object"&&s.name?`${i} assigned to ${s.name}`:`${i} assigned the comment`}case Me.ACCESS_MODE_CHANGE:{let s=t.changes?.accessMode?.to;return s?`${i} changed access to ${s}`:`${i} changed the access mode`}case Me.CUSTOM_LIST_CHANGE:return`${i} changed the custom list`;case Me.APPROVE:return`${i} approved the comment`;case Me.ACCEPT:case Me.SUGGESTION_ACCEPT:return`${i} accepted a suggestion`;case Me.REJECT:case Me.SUGGESTION_REJECT:return`${i} rejected a suggestion`;case Me.REACTION_ADD:return`${i} reacted to a comment`;case Me.REACTION_DELETE:return`${i} removed a reaction`;case Me.SUBSCRIBE:return`${i} subscribed to the thread`;case Me.UNSUBSCRIBE:return`${i} unsubscribed from the thread`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",i),""}}getRecorderDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Cg.RECORDING_ADD:return`${i} added a recording`;case Cg.RECORDING_DELETE:return`${i} deleted a recording`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",i),""}}getReactionDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Ng.REACTION_ADD:return`${i} added a reaction`;case Ng.REACTION_DELETE:return`${i} removed a reaction`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",i),""}}getCrdtDisplayMessage(t){try{let i=t.actionUser?.name??"Someone",s=t.entityData?.editCount??0,a=t.targetEntityId??"unknown";return`${i} made ${s} edit${s!==1?"s":""} to editor ${a}`}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",i),""}}stripCommentPII(t){return I(this,null,function*(){try{let i=yield this.commentUtilsService.stripCommentAnnotationData({data:t.entityData,actionType:t.eventType??ye.NEWLY_ADDED});i?.originalData&&(t.entityData=this.commentUtilsService.formatCommentData(i.originalData)),t.entityTargetData&&(t.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:t.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&t.changes?.commentText&&delete t.changes.commentText}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",i)}})}rehydrateCommentUserData(t){try{t.entityData&&this.commentUtilsService.mergeCommentWithUser(t.entityData),t.entityTargetData&&(this.rehydrateUserInObject(t.entityTargetData,"from"),this.rehydrateUsersInArray(t.entityTargetData,"to"),this.rehydrateUsersInArray(t.entityTargetData,"taggedUserContacts"))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",i)}}stripReactionPII(t){try{if(!t.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(t.entityData),t.entityData=this.reactionUtilsService.formatReactionData(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",i)}}rehydrateReactionUserData(t){try{if(!t.entityData)return;this.reactionUtilsService.mergeReactionWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",i)}}stripRecorderPII(t){try{if(!t.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:t.entityData});return}let i=t.entityData;if(this.usersService.userDataProviderAvailable()){i.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId});let o=i.transcription;o?.from&&typeof o.from=="object"&&"userId"in o.from&&(o.from={userId:o.from.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",i)}}rehydrateRecorderUserData(t){try{if(!t.entityData)return;this.serviceBook.get(ui)?.mergeRecorderWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",i)}}mergeActivityWithCommentAnnotationData(t){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t.targetEntityId);if(!i)return t;let o=t.entityData?.comments;if(Array.isArray(o))for(let s of o){let a=s?.commentId;if(a==null)continue;let c=i.comments?.[String(a)];c&&(c.commentText&&(s.commentText=c.commentText),c.commentHtml&&(s.commentHtml=c.commentHtml))}if(t.targetSubEntityId&&t.entityTargetData){let s=i.comments?.[t.targetSubEntityId];if(s){let a=t.entityTargetData;s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml)}}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",i),t}}mergeActivityWithReactionData(t){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",i),t}}mergeActivityWithRecorderData(t){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.serviceBook.get(ui)?.mergeStrippedDataWithRecorderAnnotation(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",i),t}}buildCommentActivityData(t){try{let{commentAnnotation:i,targetComment:o,actionType:s,otherFields:a}=t,c=i,l=o,u=s===ye.DELETED&&a?.isAnnotationDelete?Me.ANNOTATION_DELETE:this.mapCommentStatusToActionType(s);if(!u)return null;let d=c?.annotationId;if(!d)return null;let f=l?.commentId,g=this.buildCommentChanges(s,l,a);return{featureType:"comment",actionType:u,targetEntityId:d,eventType:s,targetSubEntityId:f??null,changes:Object.keys(g).length>0?g:void 0,entityData:i,entityTargetData:o??void 0}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",i),null}}mapCommentStatusToActionType(t){try{switch(t){case ye.NEWLY_ADDED:return Me.ANNOTATION_ADD;case ye.ADDED:return Me.COMMENT_ADD;case ye.UPDATED:return Me.COMMENT_UPDATE;case ye.DELETED:return Me.COMMENT_DELETE;case ye.STATUS_CHANGED:return Me.STATUS_CHANGE;case ye.PRIORITY_CHANGED:return Me.PRIORITY_CHANGE;case ye.ASSIGNED:return Me.ASSIGN;case ye.ACCESS_MODE_CHANGED:return Me.ACCESS_MODE_CHANGE;case ye.CUSTOM_LIST_CHANGED:return Me.CUSTOM_LIST_CHANGE;case ye.APPROVED:return Me.APPROVE;case ye.ACCEPTED:return Me.ACCEPT;case ye.REJECTED:return Me.REJECT;case ye.SUGGESTION_ACCEPTED:return Me.SUGGESTION_ACCEPT;case ye.SUGGESTION_REJECTED:return Me.SUGGESTION_REJECT;case ye.REACTION_ADDED:return Me.REACTION_ADD;case ye.REACTION_DELETED:return Me.REACTION_DELETE;case ye.SUBSCRIBED:return Me.SUBSCRIBE;case ye.UNSUBSCRIBED:return Me.UNSUBSCRIBE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",i),null}}buildRecorderActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapRecorderStatusToActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"recorder",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",i),null}}mapRecorderStatusToActionType(t){try{switch(t){case MT.ADDED:return Cg.RECORDING_ADD;case MT.DELETED:return Cg.RECORDING_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",i),null}}buildReactionActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapReactionActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"reaction",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",i),null}}mapReactionActionType(t){try{switch(t){case"add":return Ng.REACTION_ADD;case"delete":return Ng.REACTION_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",i),null}}buildCommentChanges(t,i,o){try{let s={};switch(t){case ye.NEWLY_ADDED:case ye.ADDED:s.commentText={from:null,to:i?.commentText??null};break;case ye.UPDATED:s.commentText={from:o?.oldCommentText??null,to:i?.commentText??null};break;case ye.DELETED:s.commentText={from:i?.commentText??null,to:null};break;case ye.STATUS_CHANGED:s.status={from:o?.oldStatus??null,to:o?.newStatus??null};break;case ye.PRIORITY_CHANGED:s.priority={from:o?.oldPriority??null,to:o?.newPriority??null};break;case ye.ASSIGNED:{s.assignedTo={from:o?.oldAssignedTo??null,to:o?.newAssignedTo??null};break}case ye.ACCESS_MODE_CHANGED:s.accessMode={from:o?.oldAccessMode??null,to:o?.newAccessMode??null};break;case ye.CUSTOM_LIST_CHANGED:s.customList={from:o?.oldCustomList??null,to:o?.newCustomList??null};break}return s}catch(s){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",s),{}}}extractFeatureSpecificUserIds(t,i){try{switch(t.featureType){case"comment":this.extractCommentActivityUserIds(t,i);break;case"reaction":this.extractReactionActivityUserIds(t,i);break;case"recorder":this.extractRecorderActivityUserIds(t,i);break}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",o)}}extractCommentActivityUserIds(t,i){try{if(t.entityData){let o=this.commentUtilsService.getUserIdsToResolveFromComments([t.entityData]);for(let s of o)i.add(s)}if(t.entityTargetData){let o=t.entityTargetData;if(this.extractUserIdFromValue(o.from,i),Array.isArray(o.to))for(let s of o.to)this.extractUserIdFromValue(s,i);if(Array.isArray(o.taggedUserContacts))for(let s of o.taggedUserContacts)this.extractUserIdFromValue(s,i)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",o)}}extractReactionActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.reactionUtilsService.getUserIdsToResolveFromReactions([t.entityData]);for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",o)}}extractRecorderActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.serviceBook.get(ui)?.getUserIdsToResolveFromRecorders([t.entityData])??[];for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",o)}}stripUsersFromChanges(t){try{for(let i of Object.keys(t)){let o=t[i];o&&(o.from=this.stripUserIfPresent(o.from),o.to=this.stripUserIfPresent(o.to))}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",i)}}stripUserIfPresent(t){try{return t&&typeof t=="object"&&"userId"in t?{userId:t.userId}:t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",i),t}}stripUsersFromTemplateData(t){try{for(let i of Object.keys(t)){let o=t[i];o&&typeof o=="object"&&"userId"in o&&(t[i]={userId:o.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",i)}}rehydrateUsersInChanges(t){try{for(let i of Object.values(t))i&&(i.from=this.rehydrateIfUser(i.from),i.to=this.rehydrateIfUser(i.to))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",i)}}rehydrateIfUser(t){try{if(t&&typeof t=="object"&&"userId"in t){let i=t.userId;return this.usersService.getUserById(i)??t}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",i),t}}rehydrateUsersInTemplateData(t){try{for(let i of Object.keys(t))t[i]=this.rehydrateIfUser(t[i])}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",i)}}rehydrateUserInObject(t,i){try{let o=t[i];if(o&&typeof o=="object"&&"userId"in o){let s=o.userId,a=this.usersService.getUserById(s);a&&(t[i]=a)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",o)}}rehydrateUsersInArray(t,i){try{let o=t[i];Array.isArray(o)&&(t[i]=o.map(s=>this.rehydrateIfUser(s)))}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",o)}}extractUserIdFromValue(t,i){try{if(t&&typeof t=="object"&&"userId"in t){let o=t.userId;typeof o=="string"&&i.add(o)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",o)}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(cS),C(uS),C(qo),C(Ko),C(lc),C(lS),C(di))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var hS=class{constructor({apiKey:e,documentId:n,organizationId:t,folderId:i,veltFolderId:o,clientDocumentId:s,clientOrganizationId:a}){this.paths={},this.apiKey=e,this.documentId=n,this.organizationId=t,this.folderId=i,this.veltFolderId=o,this.clientDocumentId=s,this.clientOrganizationId=a,s&&(this.documentId=_a(s)),a&&(this.organizationId=Ds(a)),i&&(this.folderId=i,this.veltFolderId=bo(i)),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 e=`${this.apiKey}`;this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${e}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${v.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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var vz=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.usersService=o}getUserIdsToResolveFromLiveStateCustom(t){try{let i=new Set;return t?.updatedBy&&i.add(t?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(t){try{if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),t}}formatLiveStateCustomData(t){try{return this.usersService.userDataProviderAvailable()&&t?.updatedBy&&(t.updatedBy={userId:t.updatedBy.userId}),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),t}}getUserIdsToResolveFromLiveStateCustoms(t){try{let i=new Set;for(let o of t)o?.updatedBy?.userId&&i.add(o?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(t){try{let i=new Set;return t?.default?.singleEditorMode?.editor?.userId&&i.add(t?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(t){try{let i=new Set;return t?.editor?.userId&&i.add(t?.editor?.userId),t?.requestEditorAccess?.user?.userId&&i.add(t?.requestEditorAccess?.user?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",i),[]}}mergeLiveStateWithUser(t){try{if(t?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.editor?.userId);i&&(t.default.singleEditorMode.editor=i)}if(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(t.default.singleEditorMode.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),t}}mergeSingleEditorLiveStateDataWithUser(t){try{if(t?.editor?.userId){let i=this.usersService.getUserById(t?.editor?.userId);i&&(t.editor=i)}if(t?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.requestEditorAccess?.user?.userId);i&&(t.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",i),t}}resolveAndMergeSingleEditorLiveStateDataWithUser(t){return I(this,null,function*(){try{let i=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:t}});if(i.length){let o=Z(),s=Ea.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:Ln.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:s,source:"internal",payload:{userIds:i}}),yield this.usersService.resolveUsers({userIds:i,uniqueId:o,moduleName:s}),this.mergeSingleEditorLiveStateDataWithUser(t)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",i),t}})}formatLiveStateSingleEditorModeData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.editor?.userId&&(t.editor={userId:t.editor.userId}),t?.requestEditorAccess?.user?.userId&&(t.requestEditorAccess.user={userId:t.requestEditorAccess.user.userId})),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),t}}mergeLiveStateCustomsWithUsers(t){try{for(let i of t)if(i?.updatedBy?.userId){let o=this.usersService.getUserById(i?.updatedBy?.userId);o&&(i.updatedBy=o)}return t}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var fS=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Y(null),this.notificationById$=new Y({}),this.inFlightRequests=new Map,this.getNotificationById=s=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",a);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig))})}catch(s){this.loggingService.catch("Error in NotificationResolverService constructor:",s)}}getProvider(){try{let t=this.notificationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in NotificationResolverService getProvider:",t);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(t){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",t)}}resolveNotifications(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let U=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:t}}),f(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=this.notificationById$.getValue()||{},T=[...new Set(t.notificationIds||[])],D=[],L=[],B=[];for(let U of T)_[U]||(this.inFlightRequests.has(U)?(D.push(this.inFlightRequests.get(U)),L.push(U)):B.push(U));let w=le(M({},t),{notificationIds:B});I(this,null,function*(){try{if(D.length>0&&(yield Promise.allSettled(D)),B.length>0){let U=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{request:w}});let A,R=new Promise(b=>{A=b});for(let b of B)this.inFlightRequests.set(b,R.then(x=>x?.[b]));let N=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,w,!0,g.config.getConfig.credentials):g?.get?.(w)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(b=>c?{}:(u(),b&&b.statusCode!==200?(this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:b,request:w}}),this.loggingService.catch(b?.message??"Error in NotificationResolverService resolveNotifications:"),{}):b?.data)).catch(b=>{throw u(),b});try{p=(yield N)||{},A(p);for(let x of B)this.inFlightRequests.delete(x);this.analyticsService.trackEvent(P.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:B});let b={};Object.entries(p).forEach(([x,k])=>{let O=this.notificationById$.value?.[x];O?O&&JSON.stringify(O)!==JSON.stringify(k)&&(b[x]=k):b[x]=k}),Object.keys(b).length>0&&this.notificationById$.next(M(M({},this.notificationById$.getValue()),b)),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:b,request:w}}),d(b)}catch(b){A({});for(let k of B)this.inFlightRequests.delete(k);let x=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:x,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:b,request:w}}),c||f(b),d(p)}}else u(),d({})}catch(U){u();let A=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:U,request:w}}),f(U)}})})}catch(a){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}deleteNotification(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let s=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let a=o||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:t,organizationId:i}});let c=this.notificationById$.getValue(),l=M({},c);delete l?.[t],this.notificationById$._value=l;let u={notificationId:t,organizationId:i},d=yield xt(()=>s?.config?.deleteConfig?.url?$t(s.config.deleteConfig.url,s.config.deleteConfig.headers,u,!1,s.config.deleteConfig.credentials):s?.delete?.(u)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return d&&d.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),this.loggingService.catch(d?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{error:d,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:t}),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",s);let a=o||Z();return this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{error:s,notificationId:t,organizationId:i}}),{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()):de(void 0)}catch(t){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",t),de(void 0)}}setNotificationDataProvider(t){try{if(t){this.loggingService.log("Setting notification data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.notificationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",i)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Up=class{constructor({apiKey:e,documentId:n,organizationId:t,clientDocumentId:i,clientOrganizationId:o,folderId:s,veltFolderId:a}){this.paths={},this.apiKey=e,this.documentId=n,this.organizationId=t,this.veltFolderId=a,i&&(this.documentId=_a(i)),o&&(this.organizationId=Ds(o)),s&&(this.folderId=s,this.veltFolderId=bo(s)),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 e=`apiKey/${this.apiKey}`;this.paths.activities=`${e}/${v.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.userNotificationIndex=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION_INDEX}`,this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=e,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${v.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userNotificationIndex(){return this.paths.userNotificationIndex}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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Sz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(t){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(t){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),t}}formatAreaData(t){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Az=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromUserIamData(t){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(t?.length)for(let o of t)o?.user?.userId&&i.add(o?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(t){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);if(i){let o=i;t?.user&&typeof t.user=="object"&&(o=M(M({},o),t.user));let s=this.usersService.getContactListUser(t.user.userId);s&&(o=M(M({},o),s)),t=le(M({},t),{user:o})}}return t}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Rz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromMultiThreads(t){try{let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),t}}formatMultiThreadData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.commentAnnotationsMap&&(t.commentAnnotationsMap=null)),t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Dz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromSelections(t){try{let i=new Set;for(let o of t)o?.user?.userId&&i.add(o.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(t){try{if(t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);i&&(t.user=i)}return t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),t}}formatSelectionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.user?.userId&&(t.user={userId:t.user.userId}),t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Cz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromTags(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o.from.userId),o?.to?.length)for(let s of o.to)s?.userId&&i.add(s.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t?.to?.length&&(t.to=t.to.map(i=>{if(i?.userId){let o=this.usersService.getUserById(i?.userId);o&&(i=o)}return i})),t}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),t}}formatTagData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to?.length&&(t.to=t.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),t}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Nz=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,L,B,w,F,U){this.activityUtilsService=t,this.areaUtilsService=i,this.commentUtilsService=o,this.contactUtilsService=s,this.coreActionsService=a,this.liveStateUtilsService=c,this.loggingService=l,this.multiThreadUtilsService=u,this.reactionUtilsService=d,this.selectionUtilsService=f,this.tagUtilsService=g,this.usersService=p,this.docService=_,this.commentAnnotationsResolverService=T,this.reactionAnnotationsResolverService=D,this.recorderAnnotationsResolverService=L,this.notificationResolverService=B,this.activityResolverService=w,this.serviceBook=F,this.attachmentResolverService=U}getErrorForGetRequests({feature:t,error:i}){try{switch(t){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(i?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",o),null}}getFirestorePath({feature:t,properties:i,documentPaths:o,apiKey:s}){try{if(!s)return;if(t==="userNotificationIndex"){if(!i?.id)return;let d=new Up({apiKey:s});return d?.userNotificationIndex?`${d.userNotificationIndex}/${i.id}`:void 0}let{documentId:a,organizationId:c,folderId:l}=i;if(!c&&(c=o?.organizationId,!c))return;let u=new Up({apiKey:s,documentId:a?`${a}`:"",organizationId:c?`${c}`:"",veltFolderId:l?`${l}`:void 0});switch(t){case"userConfig":return i?.userId&&u?.userConfig?`${u?.userConfig}/${i?.userId}${i?.documentId?`/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:""}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;case"comment":return i?.documentId&&i?.id&&u?.comment?`${u?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${i?.id}`:void 0;case"activity":return i?.id&&u?.activities?`${u?.activities}/${i?.id}`:void 0;case"allActivities":return u?.activities?`${u?.activities}`:void 0;case"allLastActivityTimestamp":return u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return i?.id&&u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&u?.area?`${u?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&u?.area?`${u?.area}`:void 0;case"allDocuments":return u?.document?`${u?.document}`:void 0;case"allLocations":return u?.location?`${u?.location}`:void 0;case"allFolders":return u?.folder?`${u?.folder}`:void 0;case"folder":return u?.folder&&i.folderId?`${u?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&u?.reaction?`${u?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"recorderTrackEvent":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"apiKeyMetadata":return s?`apiKey/${s}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&u?.folder?`${u?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&u?.location&&i?.id?`${u?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&u?.notificationViews?`${u?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&u?.documentViews?`${u?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&u?.locationViews?`${u?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.docNotification?`${u?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${t}`)}}catch(a){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",a);return}}getFirestoreCollectionGroupPath(t){try{switch(t){case"allComments":return v.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return v.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return v.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return v.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return v.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return v.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return v.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return v.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${t}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:t,properties:i,defaultDocumentPaths:o,apiKey:s,useFirestore:a}){try{if(!s)return;let{documentId:c,organizationId:l}=i;l||(l=o?.organizationId);let u=new hS({apiKey:s,documentId:c?`${c}`:"",organizationId:l?`${l}`:""});switch(t){case"userConfig":return i?.userId&&i?.documentId&&u?.userConfig?`${u?.userConfig}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!a&&i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&u?.globalContacts?`${u?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return i?.documentId&&u?.arrow&&i.id?`${u?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return i?.documentId&&u?.cursor&&i.id?`${u?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&u?.flock&&i.id?`${u?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&u?.flock&&i.id?`${u?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&u?.presence&&i?.userId?`${u?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return i?.documentId&&u?.selection&&i?.userId?`${u?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return i?.documentId&&u?.tag&&i?.id?`${u?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!a&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!a&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!a&&i?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/data`:void 0;case"crdtSyncState":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/state`:void 0;case"crdtSyncPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence/${i.userId}`:void 0;case"allCrdtSyncPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence`:void 0;case"crdtPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence/${i.userId}`:void 0;case"allCrdtPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence`:void 0;case"crdtVersion":return i?.documentId&&u?.crdt&&i?.id&&i?.versionId?`${u?.crdt}/${i?.id}/versions/${i?.versionId}`:void 0;case"crdtVersions":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/versions`:void 0;case"crdtMessages":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/messages`:void 0;case"crdtMessage":return i?.documentId&&u?.crdt&&i?.id&&i?.messageId?`${u?.crdt}/${i?.id}/messages/${i?.messageId}`:void 0;case"crdtSnapshot":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/snapshot`:void 0;case"multiThread":return!a&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!a&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!a&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"allDocuments":return!a&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!a&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!a&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"folder":return!a&&i?.folderId&&u?.folder?`${u?.folder}${i?.folderId}`:void 0;case"documentUserAccess":return!a&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!a&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!a&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!a&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!a&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!a&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!a&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!a&&i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!a&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"heartbeat":return i?.id&&u?.heartbeat?`${u?.heartbeat}${i?.id}`:void 0;case"allHeartbeats":return u?.heartbeat?`${u?.heartbeat}`:void 0;case"heartbeatByDocument":return i?.id&&u?.heartbeatByDocument?`${u?.heartbeatByDocument}${i?.id}`:void 0;case"allHeartbeatsByDocument":return u?.heartbeatByDocument?`${u?.heartbeatByDocument}`:void 0;case"documentAccessType":return!a&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!a&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!a&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!a&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allLocationViews":return!a&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!a&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${t}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(o){return I(this,arguments,function*({data:t,feature:i}){try{if(t&&t?.length>0)switch(i){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let s=Z(),a=Nd.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:a,source:"internal",payload:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let s=Z(),a=Od.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:a,source:"internal",payload:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let s=Z(),a=bd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:a,source:"internal",payload:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}default:break}}catch(s){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,s)}})}formatResponse(g){return I(this,arguments,function*({feature:t,data:i,organizationId:o,shouldAwait:s=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:c=!1,shouldNotificationResolverAwait:l=!1,shouldActivityResolverAwait:u=!1,shouldReactionResolverAwait:d=!1,shouldRecorderResolverAwait:f=!1}){try{let p=o??this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId??"";if(this.usersService.userDataProviderAvailable()){let _=[];switch(t){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(FT)?.getUserIdsToResolveFromArrowAnnotations(Object.values(i))??[]);break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(kT)?.getUserIdsToResolveFromCursorUsers(Object.values(i))??[]);break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(Fi)?.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i))??[]);break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(Fi)?.getUserIdsToResolveFromNotifications(Object.values(i))??[]);break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(UT)?.getUserIdsToResolveFromPresenceUsers(Object.values(i))??[]);break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ui)?.getUserIdsToResolveFromRecorders(Object.values(i))??[]);break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(VT)?.getUserIdsToResolveFromHuddleAttendees(Object.values(i))??[]);break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"liveStateSingleEditorMode":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}case"allActivities":{i&&typeof i=="object"&&(_=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(i)?i:Object.values(i)));break}default:_=[]}if(_?.length){let T=Z(),D=Ea.GET_USERS;this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Ln.FORMAT_RESPONSE,source:"internal",moduleName:D,payload:{userIds:_,feature:t,forceResolve:a}}),s?yield this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D}):this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":case"allUserNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(Fi)?.getCustomNotificationIdsToResolve(i)??[],_=_.filter(D=>!this.notificationResolverService.getNotificationById(D)));break}default:_=[]}if(_?.length){let T=Z(),D=kC.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Mn.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{notificationIds:_,organizationId:p,shouldNotificationResolverAwait:l}}),l?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":{if(i&&typeof i=="object"){let D=this.serviceBook.get(Fi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let D=this.serviceBook.get(Fi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}case"allActivities":{if(i&&typeof i=="object"){let T=Array.isArray(i)?i:Object.values(i),D=this.activityUtilsService.getEntityIdsToResolveFromActivities(T,"comment");_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}default:_=[]}if(_?.length){let T=Z(),D=Nd.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{commentAnnotationIds:_,organizationId:p,shouldCommentAnnotationsResolverAwait:c}}),c?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(t==="allActivities"&&i&&typeof i=="object"){let _=Array.isArray(i)?i:Object.values(i),T=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let D=[];for(let L of _)L?.id&&!this.activityResolverService.getActivityById(L.id)&&D.push(L.id);if(D.length){let L=Z(),B=UC.GET_ACTIVITIES;this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.FORMAT_RESPONSE,moduleName:B,source:"internal",payload:{activityIds:D,organizationId:T,shouldActivityResolverAwait:u}}),u?yield this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:L,moduleName:B})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"reaction");if(D=D.filter(L=>!this.reactionAnnotationsResolverService.getAnnotationById(L)),D.length){let L=Z(),B=Od.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:B,source:"internal",payload:{reactionAnnotationIds:D,organizationId:T,shouldReactionResolverAwait:d}}),d?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"recorder");if(D=D.filter(L=>!this.recorderAnnotationsResolverService.getAnnotationById(L)),D.length){let L=Z(),B=bd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:B,source:"internal",payload:{recorderAnnotationIds:D,organizationId:T,shouldRecorderResolverAwait:f}}),f?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B})}}}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(a),o),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(Fi);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithNotification(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",o),t}}mergeActivityResolverWithData({data:t,feature:i}){try{return this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable()&&i==="allActivities"&&Array.isArray(t)?t.map(o=>this.activityUtilsService.mergeActivityWithResolverData(o)):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",o),t}}mergeNotificationsWithResolvedData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(i){case"allDocNotifications":case"allUserNotifications":{let o=this.serviceBook.get(Fi);return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeResolvedNotificationData(c):c,s),{}):Array.isArray(t)?t.map(s=>o?o.mergeResolvedNotificationData(s):s):t}default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",o),t}}mergeNotificationsWithResolvedData$({data:t,feature:i}){try{return this.notificationResolverService.getNotificationsById$().pipe(ge(()=>{let o=this.mergeNotificationsWithResolvedData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",o),de(t)}}mergeReactionAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(a),o),{}):t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",o),t}}mergeRecorderAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(i){case"allRecorders":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(ui);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithRecorderAnnotation(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",o),t}}mergeActivitiesWithFeatureData(t){return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithFeatureData(i)):t}mergeLocationMetadataWithData({data:t,feature:i,locationMetadata:o}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),o&&typeof o=="object"&&!Array.isArray(o))switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,o),s),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let s=this.serviceBook.get(Fi);return Object.entries(t).reduce((a,[c,l])=>(a[c]=s?s.mergeLocationWithNotification(l,o):l,a),{})}else return t;default:return t}return t}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",s),t}}mergeUsersWithData({feature:t,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(t){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.areaUtilsService.mergeAreaWithUser(a),o),{}):i;case"allArrows":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(FT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeArrowWithUser(c):c,s),{})}else return i;case"allCursors":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(kT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeCursorUserWithUser(c):c,s),{})}else return i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeCommentWithUser(a),o),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.multiThreadUtilsService.mergeMultiThreadWithUser(a),o),{}):i;case"allDocNotifications":if(i&&typeof i=="object"){let o=this.serviceBook.get(Fi);return i?.map(s=>o?o.mergeNotificationWithUser(s):s)}else return i;case"allUserNotifications":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(Fi);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeNotificationWithUser(c):c,s),{})}else return i;case"allPresence":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(UT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergePresenceUserWithUser(c):c,s),{})}else return i;case"allRecorders":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ui);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeRecorderWithUser(c):c,s),{})}else return i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeReactionWithUser(a),o),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.tagUtilsService.mergeTagWithUser(a),o),{}):i;case"allHuddleAttendees":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(VT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?.mergeHuddleAttendeeWithUser(c)??c,s),{})}else return i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(a),o),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"liveStateSingleEditorMode":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.selectionUtilsService.mergeSelectionWithUser(a),o),{}):i;case"allActivities":return Array.isArray(i)?i.map(o=>this.activityUtilsService.mergeActivityWithUser(o)):i;default:return i}return i}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",o),i}}mergeCommentAnnotationsWithData$({data:t,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ge(()=>{let o=this.mergeCommentAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",o),de(t)}}mergeReactionAnnotationsWithData$({data:t,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ge(()=>{let o=this.mergeReactionAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",o),de(t)}}mergeRecorderAnnotationsWithData$({data:t,feature:i}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ge(()=>{let o=this.mergeRecorderAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",o),de(t)}}mergeUsersWithData$({feature:t,data:i}){try{return this.usersService.getUserById$().pipe(ge(()=>{let o=this.mergeUsersWithData({feature:t,data:i?.data??{}});return typeof o=="object"?{data:JSON.parse(JSON.stringify(o)),operation:i?.operation??null}:{data:o,operation:i?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch(`Error in mergeUsersWithData for ${t}:`,o),de(i)}}mergeLocationMetadataWithData$({data:t,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ge(o=>{let s=this.mergeLocationMetadataWithData({data:t?.data??{},feature:i,locationMetadata:o});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,o),de(t)}}handleDataStripping(a){return I(this,arguments,function*({feature:t,data:i,actionType:o,commentId:s}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),t){case"comment":{let c=yield this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:o,commentId:s});return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()})}case"reaction":{let c=this.reactionUtilsService.stripReactionAnnotationData(i);return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()})}case"recorder":{let c=this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:i,actionType:o})??{originalData:i,strippedData:null};return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()})}default:return{originalData:i,strippedData:null}}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{originalData:i,strippedData:null}}})}filterOriginalDataForVeltDb({feature:t,result:i,providerAvailable:o}){try{return!o||!i||i.originalData===null||i.originalData===void 0?i:le(M({},i),{originalData:this.applyVeltDbFieldFilter(t,i.originalData)})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService filterOriginalDataForVeltDb:",s),i}}applyVeltDbFieldFilter(t,i){switch(t){case"comment":return nB(i,{stripAttachmentFiles:this.attachmentResolverService.attachmentDataProviderAvailable()});case"reaction":return rB(i);case"recorder":return iB(i);default:return i}}formatData({feature:t,data:i,properties:o,offset:s,isRealtimeDb:a}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+s;switch(t){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return a?i:{metadata:i};case"documentCommentMetadata":return i;case"cursor":{let l=this.serviceBook.get(kT);return l?l.formatCursorUserData(i):i}case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":{let l=this.serviceBook.get(FT);return l?l.formatArrowData(i):i}case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.serviceBook.get(ui)?.formatRecorderData(i,c)??i;case"notificationViewsTimestamp":return{views:{[o.user??""]:i}};case"documentUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"documentDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"documentMetadataViews":return a?i:{metadata:i};case"huddleMessage":return this.serviceBook.get(VT)?.formatHuddleMessageData(i)??i;case"locationMetadataViews":return a?i:{metadata:i};case"locationUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"locationDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"locationViews":return a?i:{location:i};case"docNotificationViews":return a?i:{views:i.views};case"userNotificationViews":return a?i:{views:i.views};case"presence":{let l=this.serviceBook.get(UT);return l?l.formatPresenceUserData(i):i}case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(a){return I(this,arguments,function*({feature:t,data:i,subscriber:o,operation:s=null}){try{let c=yield this.modifyData({feature:t,data:i});o.next({data:c,operation:s})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:t,change:i,cache:o}){try{if(t==="allReactions"||t==="allComments"){if(i.type==="removed")return!Object.keys(o??{}).includes(i.doc.id);if(o?.[i.doc.id]){let s=i.doc.data(),a=o?.[i.doc.id];return s?.lastUpdated===a?.lastUpdated}}return!1}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",s),!1}}modifyData(o){return I(this,arguments,function*({feature:t,data:i}){try{return yield this.formatResponse({feature:t,data:i})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",s),i}})}addMetadata(t,i){try{return t&&typeof t=="object"&&!Array.isArray(t)?le(M({},t),{metadata:t?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",o),t}}setDataInLocal(l){return I(this,arguments,function*({feature:t,data:i,observablesCache:o,eventType:s,id:a,operation:c=null}){try{let d={comment:"allComments",reaction:"allReactions"}[t];if(!d)return null;let f=i?.metadata?.documentId,g=i?.metadata?.veltFolderId;return Object.keys(o).filter(p=>p.includes(d)&&(!f||p.includes(f)||g&&p.includes(g))).forEach(p=>{let _=o[p]?.subject?.getValue()??{};s==="DELETE"?a&&_?.data?.[a]&&(delete _?.data?.[a],o[p]?.subject&&o[p].subject.next({data:_?.data,operation:c})):o[p]?.subject?.next({data:le(M({},_?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",l),t}})}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:t,firestorePath:i,eventType:o})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",a),t}})}rtdbDefaultTransactionCallback(t,i){try{let o=M({},t||{});return Object.entries(i).forEach(([s,a])=>{a==null?delete o[s]:o[s]=a}),o}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",o),t}}};e.\u0275fac=function(i){return new(i||e)(C(dS),C(Sz),C(cS),C(Az),C(vt),C(vz),C(me),C(Rz),C(uS),C(Dz),C(Cz),C(jt),C(ef),C(qo),C(Ko),C(lc),C(fS),C(lS),C(di),C(Zh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var rae={comment:{mode:"persistent",scope:"doc"},notification:{mode:"persistent",scope:"user"},notificationIndex:{mode:"persistent",scope:"user"},presence:{mode:"ephemeral",scope:"doc"},liveState:{mode:"ephemeral",scope:"doc"},cursor:{mode:"ephemeral",scope:"doc"},huddle:{mode:"ephemeral",scope:"doc"},syncVideoPlayer:{mode:"ephemeral",scope:"doc"},heartbeat:{mode:"ephemeral",scope:"org"},flockSession:{mode:"ephemeral",scope:"doc"},selection:{mode:"ephemeral",scope:"doc"}};function Oz(r){return rae[r]}var nt={getDatabase:rh,ref:ih,query:tj,get:Lm,set:ij,update:oj,remove:nj,push:ej,runTransaction:rj,onValue:Mb,onChildAdded:Q2,onChildChanged:X2,onChildRemoved:J2,off:Y2,objectVal:q2,listVal:z2,stateChanges:K2,onDisconnect:Z2},bz=(()=>{let e=class e{constructor(t,i){this.databaseService=t,this.loggingService=i}getServerTimeOffset(){return I(this,null,function*(){try{let t=this.databaseService.getDbValue();if(!t)return 0;let o=(yield Lm(ih(t,e.SERVER_TIME_OFFSET_PATH)))?.val();return typeof o=="number"?o:0}catch(t){return this.loggingService.catch("Error in FirebaseRealtimeAdapter getServerTimeOffset: ",t),0}})}onServerTimeOffset(t){let i=null,o=null;try{o=this.databaseService.getDb().subscribe(s=>{if(s){let a=ih(s,e.SERVER_TIME_OFFSET_PATH);i=Mb(a,c=>{try{t(c?.val())}catch(l){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset callback: ",l)}})}})}catch(s){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset: ",s)}return()=>{try{i&&(i(),i=null),o?.unsubscribe(),o=null}catch(s){this.loggingService.catch("Error tearing down FirebaseRealtimeAdapter onServerTimeOffset: ",s)}}}getChannelTag(t){return Oz(t)}getDatabaseInstance(t){return t?nt.getDatabase(void 0,t):nt.getDatabase()}rtdbRef(t,i){return nt.ref(t,i)}rtdbQueryRef(t,...i){return nt.query(t,...i)}rtdbGet(t){return nt.get(t)}rtdbSet(t,i,o){return this.getChannelTag(t),nt.set(i,o)}rtdbUpdate(t,i,o){return this.getChannelTag(t),nt.update(i,o)}rtdbRemove(t,i){return this.getChannelTag(t),nt.remove(i)}rtdbPush(t,i,o){return this.getChannelTag(t),o===void 0?nt.push(i):nt.push(i,o)}rtdbRunTransaction(t,i,o){return this.getChannelTag(t),nt.runTransaction(i,o)}rtdbOnValue(t,i,o,s,a){return this.getChannelTag(t),typeof s=="function"?a?nt.onValue(i,o,s,a):nt.onValue(i,o,s):s?nt.onValue(i,o,s):nt.onValue(i,o)}rtdbOnChildAdded(t,i,o,s){return this.getChannelTag(t),s?nt.onChildAdded(i,o,s):nt.onChildAdded(i,o)}rtdbOnChildChanged(t,i,o,s){return this.getChannelTag(t),s?nt.onChildChanged(i,o,s):nt.onChildChanged(i,o)}rtdbOnChildRemoved(t,i,o,s){return this.getChannelTag(t),s?nt.onChildRemoved(i,o,s):nt.onChildRemoved(i,o)}rtdbOff(t,i,o){nt.off(t,i,o)}rtdbObjectVal$(t,i){return this.getChannelTag(t),nt.objectVal(i)}rtdbListVal$(t,i){return this.getChannelTag(t),nt.listVal(i)}rtdbStateChanges$(t,i){return this.getChannelTag(t),nt.stateChanges(i)}rtdbOnDisconnectSet(t,i,o){return this.getChannelTag(t),nt.onDisconnect(i).set(o)}rtdbOnDisconnectUpdate(t,i,o){return this.getChannelTag(t),nt.onDisconnect(i).update(o)}rtdbOnDisconnectRemove(t,i){return this.getChannelTag(t),nt.onDisconnect(i).remove()}rtdbOnDisconnectCancel(t,i){return this.getChannelTag(t),nt.onDisconnect(i).cancel()}subscribe(t,i,o,s){return{unsubscribe:()=>{}}}publish(t,i,o){return I(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.publish wiring deferred to Phase A"}})}presence(t,i){return I(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.presence wiring deferred to Phase A"}})}onDisconnect(t,i){return I(this,null,function*(){return()=>{}})}};e.SERVER_TIME_OFFSET_PATH=".info/serverTimeOffset",e.\u0275fac=function(i){return new(i||e)(C(cc),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var gS=(()=>{let e=class e{constructor(t,i,o){this.configService=t,this.authService=i,this.loggingService=o,this.firestore$=new Y(null);try{ti([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Rt(([s,a])=>!!s&&!!a),Dt(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let d=sessionStorage?.getItem("veltFirestoreLogLevel")||dn?.firebaseLogLevel||"silent";aM(d)}catch(d){this.loggingService.catch("Error in FirestoreService setLogLevel: ",d)}let l=uc.getFirestoreProdDbName(a,s.firebaseOptions),u=this.configService.getProxyConfig();if(u?.v2DbHost){let d={host:u.v2DbHost,ssl:!0};u.forceLongPolling?d.experimentalForceLongPolling=!0:d.experimentalAutoDetectLongPolling=!0,c&&(d.localCache=jM({tabManager:HM()}));try{this.firestore$.next(eS(Sr(),d,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next(Xh(l))}}else if(c)try{let d=Sr(),f=eS(d,{localCache:jM({tabManager:HM()})},l);this.firestore$.next(f)}catch{this.firestore$.next(Xh(l))}else this.firestore$.next(Xh(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let t=this.getFirestoreValue()||Xh("DocumentIdDb");if(t){let i=iS(t,"generateDocumentId");return xp(i).id}return}catch(t){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",t);return}}};e.\u0275fac=function(i){return new(i||e)(C(Xn),C(Dr),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Qr={doc:xp,collection:iS,collectionGroup:lz,query:gz,getDoc:WM,getDocs:hz,getCountFromServer:dz,setDoc:pz,deleteDoc:uz,onSnapshot:fz,runTransaction:mz},Lz=(()=>{let e=class e{constructor(t,i,o){this.firestoreService=t,this.databaseService=i,this.loggingService=o}read(t){return I(this,null,function*(){if((t.store??"firestore")==="rtdb"){let a=this.databaseService.getDbValue();return a?{data:(yield Lm(ih(a,t.location)))?.val()}:{data:void 0}}let o=this.firestoreService.getFirestoreValue();return o?{data:(yield WM(xp(o,t.location)))?.data()}:{data:void 0}})}runTransaction(t){return I(this,null,function*(){return t()})}firestoreDoc(t,i){return Qr.doc(t,i)}firestoreCollection(t,i){return Qr.collection(t,i)}firestoreCollectionGroup(t,i){return Qr.collectionGroup(t,i)}firestoreQuery(t,...i){return Qr.query(t,...i)}firestoreGetDoc(t){return Qr.getDoc(t)}firestoreGetDocs(t){return Qr.getDocs(t)}firestoreGetCountFromServer(t){return Qr.getCountFromServer(t)}firestoreSetDoc(t,i,o){return o?Qr.setDoc(t,i,o):Qr.setDoc(t,i)}firestoreDeleteDoc(t){return Qr.deleteDoc(t)}firestoreOnSnapshot(t,i,o){return o?Qr.onSnapshot(t,i,o):Qr.onSnapshot(t,i)}firestoreRunTransaction(t,i){return Qr.runTransaction(t,i)}addComment(t){return this.deferred("addComment")}editComment(t){return this.deferred("editComment")}deleteComment(t){return this.deferred("deleteComment")}setCommentResolved(t){return this.deferred("setCommentResolved")}setCommentMetadata(t){return this.deferred("setCommentMetadata")}bumpCommentViews(t){return this.deferred("bumpCommentViews")}markCommentThreadRead(t){return this.deferred("markCommentThreadRead")}markNotificationRead(t){return this.deferred("markNotificationRead")}addNotification(t){return this.deferred("addNotification")}deleteNotification(t){return this.deferred("deleteNotification")}updateNotification(t){return this.deferred("updateNotification")}updatePresence(t){return this.deferred("updatePresence")}grantAccess(t){return this.deferred("grantAccess")}revokeAccess(t){return this.deferred("revokeAccess")}getAccess(t){return this.deferred("getAccess")}upsertOrgUserProfile(t){return this.deferred("upsertOrgUserProfile")}upsertDocMetadata(t){return this.deferred("upsertDocMetadata")}upsertOrgMetadata(t){return this.deferred("upsertOrgMetadata")}createActivity(t){return this.deferred("createActivity")}deferred(t){return this.loggingService.warn(`[WB] FirebaseDbAdapter.${t} called but write-op wiring is deferred to Phase A (self-hosting Step 0). The SDK uses its existing direct write path in Step 0.`),Promise.resolve({ok:!1,code:"unimplemented",message:`FirebaseDbAdapter.${t} wiring deferred to Phase A`})}};e.\u0275fac=function(i){return new(i||e)(C(gS),C(cc),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Mz=(()=>{let e=class e{allow(){return Promise.resolve({allow:!0})}canRead(t){return I(this,null,function*(){return this.allow()})}canWrite(t){return I(this,null,function*(){return this.allow()})}};e.\u0275fac=function(i){return new(i||e)},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var p1e=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,L,B,w){this.activityUtilsService=t,this.authService=i,this.commonDbUtilsService=o,this.coreActionsService=s,this.loggingService=a,this.firestoreService=c,this.databaseService=l,this.configService=u,this.docService=d,this.usersService=f,this.commentAnnotationsResolverService=g,this.reactionAnnotationsResolverService=p,this.recorderAnnotationsResolverService=_,this.notificationResolverService=T,this.serviceBook=D,this.realtimeAdapter=L,this.dbAdapter=B,this.authzAdapter=w,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.serverTimeOffsetUnsub=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.serviceBook.observe(jT).subscribe(F=>{this.activityService=F??void 0}),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(F=>{F&&(this.db=F)})),this.serverTimeOffsetUnsub=this.realtimeAdapter.onServerTimeOffset(F=>{this.offset=F}),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(F=>{F&&(this.firestore=F)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([t,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(t){this.loggingService.catch("Error in unsubscribeFromObservables:",t)}}ngOnDestroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.offsetListener&&this.offsetListener(),this.serverTimeOffsetUnsub&&(this.serverTimeOffsetUnsub(),this.serverTimeOffsetUnsub=null),this.unsubscribeFromObservables()}setupOnDisconnect(t,i,o){return I(this,null,function*(){try{if(this.db){let s=this.realtimeAdapter.rtdbRef(this.db,t);return this.realtimeAdapter.rtdbOnDisconnectUpdate(o??"commondb",s,i)}return Promise.resolve()}catch(s){return this.loggingService.catch("Error in setupOnDisconnect:",s),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(t){ti([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Rt(([i,o])=>!!i),Dt(1),ea(([i,o])=>{t({db:i,firestore:o})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(t,i,o,s,a,c){return I(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${t}`,"color: red;");return}return this.subscribeToServices(d=>I(this,[d],function*({db:l,firestore:u}){let f;i?.skipFirestore||(f=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let g=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!l){this.loggingService.warn(`%c[WB] No database or firestore found for ${t}`,"color: red;");return}try{let p,_;try{g&&(p=this.realtimeAdapter.rtdbRef(l,`${g}`))}catch{this.loggingService.catch("Error in dbRef")}try{f?.includes("/organizations")&&u&&f&&(_=this.dbAdapter.firestoreDoc(u,`${f}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield o({dbRef:p,firestoreRef:_,data:s,firestorePath:f}),c&&c({firestoreAvailable:!!u})}catch(p){this.loggingService.catch(`Error in ${t} operation: `,p),a&&a(p)}}))}catch(l){this.loggingService.catch("Error in performDatabaseOperation:",l)}})}setData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,u.dbRef,()=>JSON.parse(JSON.stringify(d))):yield this.realtimeAdapter.rtdbSet(t,u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??o?.targetCommentId});if(t==="comment"){let _=null,T=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:It.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(u.firestoreRef,d)}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in setData for ${t}`,u)}})}updateData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef&&!o?.skipRtdb){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,u.dbRef,f=>{let g;return o?.rtdbTransactionCallback?g=o.rtdbTransactionCallback(f,d):g=this.commonDbUtilsService.rtdbDefaultTransactionCallback(f,d),JSON.parse(JSON.stringify(g))}):yield this.realtimeAdapter.rtdbUpdate(t,u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(t==="comment"){let _=null,T=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:It.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(u.firestoreRef,d,{merge:!0})}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in updateData for ${t}`,u)}})}createActivityFromExtraData(t,i){try{if(!i?.actionType||!this.activityService)return;let o=this.activityUtilsService.buildActivityDataFromExtraData({feature:t,extraData:i});o&&this.activityService.createActivity(o)}catch(o){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",o)}}deleteData(c){return I(this,arguments,function*({feature:t,properties:i,callback:o,errorCallback:s,extraData:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${t}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:t,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.createActivityFromExtraData(t,a),this.performDatabaseOperation(t,i,l=>I(this,null,function*(){l.dbRef&&(yield this.realtimeAdapter.rtdbRemove(t,l.dbRef));try{if(l.firestoreRef&&!i?.skipFirestore)if(t==="comment"){let u=null,d=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_DATA,source:"internal",payload:{commentAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE",metadata:i?.metadata}))}else if(t==="reaction"){let u=null,d=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE"}))}else if(t==="recorder"){let u=null,d=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef))}else if(t==="userNotification"){let u=null,d=Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Mn.DELETE_DATA,source:"internal",payload:{notificationId:i?.id??"",organizationId:i?.organizationId??""}}),u=yield this.notificationResolverService.deleteNotification(String(i?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",d),(u?.isSuccess||u===null)&&(yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef))}else yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef)}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${t}`,u)}}),void 0,s,o)}catch(l){this.loggingService.catch(`Error in deleteData for ${t}`,l)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(t){return this.loggingService.catch("Error in shouldUseFirestore:",t),!1}}generateDocumentId(){try{let t=this.firestoreService.generateFirestoreDocumentId();return t||(t=Z()),t||"noDocumentId"}catch(t){return this.loggingService.catch("Error in generateFirestoreDocumentId:",t),Z()||"noDocumentId"}}queryData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();return!t||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):s?yield this.handleFirestoreQuery(t,i):yield this.handleRtdbQuery(t,i)}catch(s){return this.loggingService.catch(`Error in queryData for ${t}`,s),[]}})}handleFirestoreQuery(t,i){return I(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let o=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),[];try{let s=this.dbAdapter.firestoreCollection(this.firestore,o);i?.useCollectionGroup&&(s=this.dbAdapter.firestoreCollectionGroup(this.firestore,o));let a=i?.firestoreQuery??[],c=this.dbAdapter.firestoreQuery(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];if(i?.getCount)try{let l=yield this.dbAdapter.firestoreGetCountFromServer(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,u),null));return l?l.data().count:0}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,l),0}else try{let l=yield this.dbAdapter.firestoreGetDocs(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,d),null));if(!l)return[];let u=l.docs.map(d=>d.data());try{return yield this.commonDbUtilsService.modifyData({feature:t,data:u})}catch(d){return this.loggingService.catch(`Error in modifyData for ${t}`,d),u}}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,l),[]}}catch(s){return this.loggingService.catch(`Error in Firestore query for ${t}:`,s),[]}}catch(o){return this.loggingService.catch(`Error in Firestore query for ${t}:`,o),[]}})}handleRtdbQuery(t,i){return I(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let o=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No database path found for ${t}`),[];try{let s=this.realtimeAdapter.rtdbRef(this.db,o),a=i?.rtdbQuery??[],c=this.realtimeAdapter.rtdbQueryRef(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];let l=yield this.realtimeAdapter.rtdbGet(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),null));if(!l)return[];let u=l.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(s){return this.loggingService.catch(`Error in RTDB query for ${t}:`,s),[]}})}buildAuthzRequest(t,i){return{feature:t,scope:"doc",resourceId:i?.id!=null?String(i.id):void 0,apiKey:i?.apiKey??this.configService.getApiKey()??void 0,organizationId:i?.organizationId!=null?String(i.organizationId):void 0,documentId:i?.documentId!=null?String(i.documentId):void 0}}getData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();if(i?.skipFirestore&&(s=!1),!t||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(s&&this.firestore){let a=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,i))).allow)return{};let l=yield this.dbAdapter.read({feature:t,scope:"doc",location:a,store:"firestore",field:i?.field,suppressError:i?.suppressError}).catch(d=>(this.authService.getUser()&&!i?.suppressError&&this.loggingService.catch(`Error in getDoc for ${t}`,d),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:d})));if(l){if(l?.errorCode)return l}else return this.loggingService.warn(`[WB] No document found at ${a}`),{};let u=l.data;return i?.field?u?.[i.field]??{}:u??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${t}:`,c),{}}}if(this.db){let a=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${t}`),{};try{if(!this.authService.getUser())return{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,i))).allow)return{};let l=yield this.dbAdapter.read({feature:t,scope:"doc",location:a,store:"rtdb",field:i?.field,suppressError:i?.suppressError}).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:d})));if(l){if(l?.errorCode)return l}else return this.loggingService.warn(`[WB] No data found at ${a}`),{};let u=l.data;return i?.field?u?.[i.field]??{}:u??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${t}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(s){return this.loggingService.catch("Unexpected error in getData:",s),{}}})}dbListener({feature:t,properties:i}){let o=this.shouldUseFirestore();i?.skipFirestore&&(o=!1);let s=`${t}-${JSON.stringify(i)}`;return ti([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Rt(a=>!!a))]).pipe(Rt(([a,c])=>a?o&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${t}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${t}`),!1)),pt(([a,c])=>{try{if(o&&c){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleFirestoreListener(t,i,c).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.firestoreSubscriptions[s]=d}return new pe(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.firestoreSubscriptions[s]?.unsubscribe(),delete this.firestoreSubscriptions[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache[s]))}})}else if(a){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleRealtimeDbListener(t,i,a).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.rtdbSubscriptions[s]=d}return new pe(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.rtdbSubscriptions[s]?.unsubscribe(),delete this.rtdbSubscriptions?.[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache?.[s]))}})}return de({})}catch(l){return this.loggingService.catch(`Error setting up listener for ${t}:`,l),de({})}}),Lc(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${t} and key ${s}`)}))}handleFirestoreListener(t,i,o){let s=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),a=`${t}-${JSON.stringify(i)}`;return s?new pe(c=>{let l=i.isCollection?this.setupCollectionListener(o,s,t,c,i):this.setupDocumentListener(o,s,t,c,i);return()=>{c.complete(),c.unsubscribe(),l(),this.observablesCache[a]?.subject?.complete(),this.observablesCache[a]?.subject?.unsubscribe(),delete this.observablesCache[a]}}).pipe(pt(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:t,data:c})),pt(c=>["allComments","allUserNotifications"].includes(t)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:t}):de(c)),pt(c=>["allReactions"].includes(t)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:t}):de(c)),pt(c=>["allRecorders"].includes(t)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:t}):de(c)),rt(Pt)):(this.loggingService.warn(`[WB] No firestore path found for ${t} and key ${a}`),de({}))}setupCollectionListener(t,i,o,s,a){let c=`${o}-${JSON.stringify(a)}`,l=this.dbAdapter.firestoreCollection(t,i);if(a?.useCollectionGroup&&(l=this.dbAdapter.firestoreCollectionGroup(t,i)),a?.useQuery&&a?.firestoreQuery){let f=a?.firestoreQuery??[];l=this.dbAdapter.firestoreQuery(l,...f)}let u=!0,d=[];return o==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",i,"feature:",o,"properties:",JSON.stringify(a??"nil")),this.dbAdapter.firestoreOnSnapshot(l,f=>{try{let g=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),p=null,_=!1;f?.docChanges()?.length?f.docChanges().forEach(T=>{["allComments","allReactions","allRecorders"].includes(o)&&!u&&T.type!=="removed"&&d.push(T.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:o,change:T,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(_=!0,Object.assign(g,this.handleCollectionChange(T,g)),T.type==="removed"&&(p||(p={type:T.type,ids:[]}),p.ids.push(T.doc.id)))}):_=!0,_&&(["allComments","allReactions","allRecorders"].includes(o)&&d?.length&&(this.commonDbUtilsService.resolveAnnotations({data:d,feature:o}),d=[]),this.commonDbUtilsService.modifyAndSetData({feature:o,data:g,subscriber:s,operation:p})),u=!1}catch(g){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,g),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(g,o,s)}},f=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,f),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(f,o,s)})}handleCollectionChange(t,i){switch(t.type){case"added":case"modified":i[t.doc.id]=t.doc.data();break;case"removed":delete i?.[t.doc.id];break}return i}setupDocumentListener(t,i,o,s,a){let c=this.dbAdapter.firestoreDoc(t,i);return this.dbAdapter.firestoreOnSnapshot(c,l=>{try{let u=l.data()||{};a?.field&&(u=u?.[a?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:o,data:u,subscriber:s,operation:null})}catch(u){this.handleListenerError(u,o,s)}},l=>this.handleListenerError(l,o,s))}handleListenerError(t,i,o){this.loggingService.catch(`Firestore listener error for ${i}:`,t)}handleRealtimeDbListener(t,i,o){let s=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${t}`),de({});let a=this.realtimeAdapter.rtdbRef(o,s);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];a=this.realtimeAdapter.rtdbQueryRef(a,...c)}return this.objectValFromChildEvents(a,t).pipe(as(c=>(this.loggingService.catch(`RTDB listener error for ${t}:`,c),de({}))),ge(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[d,f])=>(u[d]=this.commonDbUtilsService.addMetadata(f,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),pt(c=>this.commonDbUtilsService.modifyData({feature:t,data:c})),pt(c=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:t,data:c}),operation:null})))))}pushData(s){return I(this,arguments,function*({feature:t,properties:i,data:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${t}`,"color: green;"),this.performDatabaseOperation(t,i,a=>I(this,null,function*(){if(a.dbRef){let c=this.realtimeAdapter.rtdbPush(t,a.dbRef);yield this.realtimeAdapter.rtdbSet(t,c,JSON.parse(JSON.stringify(a.data)))}}),o)}catch(a){this.loggingService.catch(`Error in pushData for ${t}`,a)}})}streamChildAdded({feature:t,properties:i,afterTs:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${t}`,"color: green;"),new pe(s=>{let a=null,c=!1,l=({db:u})=>{if(!u||c||!this.authService.getUser())return;let d=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!d)return;let g=this.realtimeAdapter.rtdbRef(u,d),p=!1,_=L=>{try{let B=L.val();if(p){if(o!=null&&B?.timestamp!=null&&B.timestamp<=o)return;s.next(B)}}catch(B){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${t}:`,B)}},T=L=>{try{this.loggingService.catch(`streamChildAdded error for ${t}:`,L),s.error(L)}catch(B){this.loggingService.catch(`streamChildAdded onError handler error for ${t}:`,B)}};this.realtimeAdapter.rtdbOnChildAdded(t,g,_,T);let D=this.realtimeAdapter.rtdbOnValue(t,g,()=>{p=!0},T,{onlyOnce:!0});a=()=>{try{D&&typeof D=="function"&&D(),this.realtimeAdapter.rtdbOff(g,"child_added",_)}catch(L){this.loggingService.catch(`streamChildAdded cleanup error for ${t}:`,L)}}};return this.subscribeToServices(l),()=>{c=!0,a&&a()}})}catch(s){return this.loggingService.catch(`Error in streamChildAdded for ${t}`,s),de(null)}}objectValFromChildEvents(t,i){return new pe(o=>{let s={},a=!1,c=null,l=T=>{try{this.loggingService.catch(`Realtime DB listener error for ${i}:`,T),o.error(T)}catch{}},u=T=>{try{if(!Ui(T,c)){let D=JSON.parse(JSON.stringify(T));c=D,o.next(D)}}catch{}},d=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(M({},s)))}catch{}},f=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(M({},s)))}catch{}},g=T=>{try{T.key&&(delete s[T.key],a&&u(M({},s)))}catch{}},p=T=>{try{if(!a){let D=s&&typeof s=="object"?JSON.parse(JSON.stringify(s)):{};c=D,o.next(D),a=!0}}catch{}};this.realtimeAdapter.rtdbOnChildAdded(i,t,d,l),this.realtimeAdapter.rtdbOnChildChanged(i,t,f,l),this.realtimeAdapter.rtdbOnChildRemoved(i,t,g,l);let _=this.realtimeAdapter.rtdbOnValue(i,t,p,l,{onlyOnce:!0});return()=>{try{_&&typeof _=="function"&&_(),this.realtimeAdapter.rtdbOff(t,"child_added",d),this.realtimeAdapter.rtdbOff(t,"child_changed",f),this.realtimeAdapter.rtdbOff(t,"child_removed",g)}catch{}}})}};e.\u0275fac=function(i){return new(i||e)(C(dS),C(Dr),C(Nz),C(vt),C(me),C(gS),C(cc),C(Xn),C(ef),C(jt),C(qo),C(Ko),C(lc),C(fS),C(di),C(bz),C(Lz),C(Mz))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();export{M as a,le as b,NS as c,aae as d,cae as e,lae as f,I as g,mt as h,pe as i,jS as j,Ct as k,Y as l,Mc as m,k6 as n,U6 as o,Oc as p,Mr as q,de as r,V6 as s,B6 as t,A6 as u,ge as v,ti as w,iA as x,G6 as y,fo as z,K6 as A,Ni as B,_6 as C,ju as D,Rt as E,c6 as F,as as G,VS as H,Mu as I,Dt as J,$S as K,rt as L,Pu as M,AE as N,WS as O,T6 as P,zS as Q,I6 as R,xu as S,pt as T,Zs as U,v6 as V,ea as W,y6 as X,D6 as Y,oe as Z,zE as _,K as $,us as aa,ee as ba,C as ca,J as da,pr as ea,zn as fa,go as ga,F0 as ha,k0 as ia,K0 as ja,Y0 as ka,lt as la,In as ma,sr as na,Pr as oa,Io as pa,Jc as qa,ni as ra,D4 as sa,un as ta,rD as ua,W4 as va,ha as wa,C_ as xa,j_ as ya,Z4 as za,Lq as Aa,Mq as Ba,Pq as Ca,xq as Da,Fq as Ea,Zq as Fa,gs as Ga,we as Ha,a8 as Ia,Q8 as Ja,X8 as Ka,So as La,tg as Ma,Es as Na,nT as Oa,dt as Pa,a5 as Qa,Do as Ra,rl as Sa,Ak as Ta,K5 as Ua,fa as Va,Co as Wa,rg as Xa,bk as Ya,i9 as Za,Mk as _a,Pk as $a,oT as ab,ga as bb,Bk as cb,Gk as db,d9 as eb,f9 as fb,g9 as gb,m9 as hb,p9 as ib,E9 as jb,_9 as kb,$k as lb,$D as mb,jD as nb,jk as ob,HD as pb,WD as qb,Hk as rb,zD as sb,qD as tb,zk as ub,A9 as vb,qk as wb,Yk as xb,Qk as yb,O9 as zb,w9 as Ab,L9 as Bb,P9 as Cb,x9 as Db,F9 as Eb,k9 as Fb,U9 as Gb,V9 as Hb,B9 as Ib,nU as Jb,rU as Kb,Z9 as Lb,tK as Mb,dK as Nb,hU as Ob,KD as Pb,fU as Qb,gU as Rb,mU as Sb,mK as Tb,pU as Ub,_U as Vb,pK as Wb,EK as Xb,_K as Yb,TK as Zb,AK as _b,RK as $b,DK as ac,CK as bc,NK as cc,OK as dc,bK as ec,wK as fc,LK as gc,MK as hc,PK as ic,xK as jc,kK as kc,VK as lc,BK as mc,GK as nc,$K as oc,jK as pc,zK as qc,lg as rc,ug as sc,ZD as tc,Uye as uc,Vye as vc,Bye as wc,yY as xc,dC as yc,Gye as zc,$ye as Ac,jye as Bc,No as Cc,YU as Dc,jY as Ec,h1 as Fc,HY as Gc,_C as Hc,WY as Ic,zY as Jc,qY as Kc,KY as Lc,QY as Mc,JY as Nc,e7 as Oc,TC as Pc,AT as Qc,RT as Rc,p7 as Sc,T7 as Tc,x1 as Uc,j7 as Vc,H7 as Wc,wC as Xc,q1 as Yc,xC as Zc,kd as _c,$r as $c,Ta as ad,uI as bd,gl as cd,vr as dd,Be as ed,fn as fd,lr as gd,Po as hd,yr as id,Sa as jd,Sr as kd,Ke as ld,$X as md,TLe as nd,ILe as od,vLe as pd,Gi as qd,Aa as rd,Ns as sd,$i as td,_e as ud,ji as vd,Os as wd,VLe as xd,BLe as yd,GLe as zd,Da as Ad,dZ as Bd,fZ as Cd,DZ as Dd,Il as Ed,vl as Fd,SPe as Gd,APe as Hd,lxe as Id,Kre as Jd,uxe as Kd,Yre as Ld,Qre as Md,Xre as Nd,ur as Od,$Pe as Pd,jPe as Qd,HPe as Rd,Q1 as Sd,lQ as Td,Og as Ud,dn as Vd,j as Wd,ye as Xd,Qt as Yd,cRe as Zd,lRe as _d,uRe as $d,dRe as ae,H as be,hRe as ce,fRe as de,gRe as ee,mRe as fe,q7 as ge,K7 as he,Y7 as ie,Q7 as je,MT as ke,X7 as le,pRe as me,J7 as ne,LC as oe,Z7 as pe,Br as qe,PT as re,eQ as se,Ad as te,Mt as ue,tQ as ve,xT as we,nQ as xe,rQ as ye,iQ as ze,ERe as Ae,_Re as Be,TRe as Ce,oQ as De,v as Ee,H1 as Fe,XRe as Ge,Cd as He,tDe as Ie,nDe as Je,hi as Ke,Nt as Le,X1 as Me,J1 as Ne,wDe as Oe,LDe as Pe,qT as Qe,FC as Re,KT as Se,Ln as Te,Ea as Ue,Oo as Ve,nV as We,rV as Xe,iV as Ye,As as Ze,rCe as _e,Qn as $e,ki as af,oV as bf,sV as cf,aV as df,cV as ef,lV as ff,uV as gf,dV as hf,hV as if,fV as jf,gV as kf,mV as lf,VCe as mf,BCe as nf,pV as of,VC as pf,EV as qf,_V as rf,IV as sf,TNe as tf,Rs as uf,uQ as vf,dQ as wf,vbe as xf,FV as yf,kV as zf,Lbe as Af,Tr as Bf,fi as Cf,_a as Df,Ds as Ef,bo as Ff,Mbe as Gf,Pbe as Hf,xbe as If,Fbe as Jf,kbe as Kf,Ube as Lf,VV as Mf,BV as Nf,Vbe as Of,Bbe as Pf,jC as Qf,GV as Rf,Gbe as Sf,$be as Tf,$V as Uf,Z as Vf,jbe as Wf,jV as Xf,Ld as Yf,bV as Zf,wV as _f,fQ as $f,gQ as ag,hl as bg,HC as cg,Hbe as dg,wo as eg,Wbe as fg,Mg as gg,Ui as hg,zbe as ig,WC as jg,dl as kg,EQ as lg,tI as mg,qbe as ng,Kbe as og,WV as pg,Pg as qg,_Q as rg,TQ as sg,IQ as tg,vQ as ug,yQ as vg,Gr as wg,Ybe as xg,GC as yg,Qbe as zg,AQ as Ag,Xbe as Bg,Jbe as Cg,qV as Dg,Zbe as Eg,ewe as Fg,twe as Gg,nwe as Hg,rwe as Ig,iwe as Jg,owe as Kg,eI as Lg,swe as Mg,awe as Ng,cwe as Og,lwe as Pg,uwe as Qg,dwe as Rg,hwe as Sg,fwe as Tg,gwe as Ug,mwe as Vg,pwe as Wg,Ewe as Xg,_we as Yg,Twe as Zg,Iwe as _g,vwe as $g,ywe as ah,Swe as bh,Awe as ch,Rwe as dh,Dwe as eh,Cwe as fh,Nwe as gh,Owe as hh,bwe as ih,NQ as jh,wwe as kh,Lwe as lh,Mwe as mh,MV as nh,Pwe as oh,xwe as ph,Pt as qh,yn as rh,Fwe as sh,xt as th,$t as uh,OQ as vh,ZV as wh,Md as xh,qC as yh,Ir as zh,kwe as Ah,PV as Bh,P as Ch,Rr as Dh,FT as Eh,ARe as Fh,RRe as Gh,Fi as Hh,DRe as Ih,kT as Jh,CRe as Kh,NRe as Lh,UT as Mh,ORe as Nh,VT as Oh,bRe as Ph,BT as Qh,wRe as Rh,ui as Sh,LRe as Th,Rd as Uh,MRe as Vh,PRe as Wh,xRe as Xh,FRe as Yh,kRe as Zh,URe as _h,VRe as $h,GT as ai,BRe as bi,GRe as ci,$T as di,jT as ei,B1 as fi,G1 as gi,$1 as hi,di as ii,Ot as ji,me as ki,Xn as li,Jee as mi,i0e as ni,xo as oi,aj as pi,vt as qi,Ov as ri,bv as si,Dr as ti,rS as ui,zse as vi,qse as wi,Kse as xi,Yse as yi,Ii as zi,cc as Ai,qo as Bi,Ko as Ci,Zh as Di,lc as Ei,ef as Fi,jt as Gi,cS as Hi,lS as Ii,dS as Ji,hS as Ki,vz as Li,fS as Mi,Nz as Ni,bz as Oi,p1e as Pi};
167
+ `+r.stack),e}function jH(r){return(function(n,t){if(typeof n!="object"||n===null)return!1;let i=n;for(let o of t)if(o in i&&typeof i[o]=="function")return!0;return!1})(r,["next","error","complete"])}var Ji=class extends lu{constructor(e,n,t,i){super(e,n,t,i),this.type="firestore",this._queue=new ky,this._persistenceKey=i?.name||"[DEFAULT]"}_terminate(){return I(this,null,function*(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new ky(e),this._firestoreClient=void 0,yield e}})}};function eS(r,e,n){n||(n=ap);let t=Po(r,"firestore");if(t.isInitialized(n)){let i=t.getImmediate({identifier:n}),o=t.getOptions(n);if(Bi(o,e))return i;throw new Q(W.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(e.cacheSizeBytes!==void 0&&e.localCache!==void 0)throw new Q(W.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(e.cacheSizeBytes!==void 0&&e.cacheSizeBytes!==-1&&e.cacheSizeBytes<s3)throw new Q(W.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return e.host&&$r(e.host)&&Ta(e.host),t.initialize({options:e,instanceIdentifier:n})}function Xh(r,e){let n=typeof r=="object"?r:Sr(),t=typeof r=="string"?r:e||ap,i=Po(n,"firestore").getImmediate({identifier:t});if(!i._initialized){let o=kd("firestore");o&&L3(i,...o)}return i}function Jh(r){if(r._terminated)throw new Q(W.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||Fse(r),r._firestoreClient}function Fse(r){var e,n,t;let i=r._freezeSettings(),o=(function(a,c,l,u){return new mw(a,c,l,u.host,u.ssl,u.experimentalForceLongPolling,u.experimentalAutoDetectLongPolling,b3(u.experimentalLongPollingOptions),u.useFetchStreams,u.isUsingEmulator)})(r._databaseId,((e=r._app)===null||e===void 0?void 0:e.options.appId)||"",r._persistenceKey,i);r._componentsProvider||!((n=i.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((t=i.localCache)===null||t===void 0)&&t._onlineComponentProvider)&&(r._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),r._firestoreClient=new HL(r._authCredentials,r._appCheckCredentials,r._queue,o,r._componentsProvider&&(function(a){let c=a?._online.build();return{_offline:a?._offline.build(c),_online:c}})(r._componentsProvider))}var WL=class{constructor(e="count",n){this._internalFieldPath=n,this.type="AggregateField",this.aggregateType=e}},zL=class{constructor(e,n,t){this._userDataWriter=n,this._data=t,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}};var Fs=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(rn.fromBase64String(e))}catch(n){throw new Q(W.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(e){return new r(rn.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:r._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Cp(e,r._jsonSchema))return r.fromBase64String(e.bytes)}};Fs._jsonSchemaVersion="firestore/bytes/1.0",Fs._jsonSchema={type:nn("string",Fs._jsonSchemaVersion),bytes:nn("string")};var Hh=class{constructor(...e){for(let n=0;n<e.length;++n)if(e[n].length===0)throw new Q(W.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new gn(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var Ap=class{constructor(e){this._methodName=e}};var qa=class r{constructor(e,n){if(!isFinite(e)||e<-90||e>90)throw new Q(W.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(n)||n<-180||n>180)throw new Q(W.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=e,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return De(this._lat,e._lat)||De(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:r._jsonSchemaVersion}}static fromJSON(e){if(Cp(e,r._jsonSchema))return new r(e.latitude,e.longitude)}};qa._jsonSchemaVersion="firestore/geoPoint/1.0",qa._jsonSchema={type:nn("string",qa._jsonSchemaVersion),latitude:nn("number"),longitude:nn("number")};var Ka=class r{constructor(e){this._values=(e||[]).map(n=>n)}toArray(){return this._values.map(e=>e)}isEqual(e){return(function(t,i){if(t.length!==i.length)return!1;for(let o=0;o<t.length;++o)if(t[o]!==i[o])return!1;return!0})(this._values,e._values)}toJSON(){return{type:r._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Cp(e,r._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(n=>typeof n=="number"))return new r(e.vectorValues);throw new Q(W.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};Ka._jsonSchemaVersion="firestore/vectorValue/1.0",Ka._jsonSchema={type:nn("string",Ka._jsonSchemaVersion),vectorValues:nn("object")};var kse=/^__.*__$/,qL=class{constructor(e,n,t){this.data=e,this.fieldMask=n,this.fieldTransforms=t}toMutation(e,n){return this.fieldMask!==null?new Qi(e,this.data,this.fieldMask,n,this.fieldTransforms):new tc(e,this.data,n,this.fieldTransforms)}},Uy=class{constructor(e,n,t){this.data=e,this.fieldMask=n,this.fieldTransforms=t}toMutation(e,n){return new Qi(e,this.data,this.fieldMask,n,this.fieldTransforms)}};function F3(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw ae(40011,{Ec:r})}}var KL=class r{constructor(e,n,t,i,o,s){this.settings=e,this.databaseId=n,this.serializer=t,this.ignoreUndefinedProperties=i,o===void 0&&this.Ac(),this.fieldTransforms=o||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new r(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var n;let t=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:t,mc:!1});return i.fc(e),i}gc(e){var n;let t=(n=this.path)===null||n===void 0?void 0:n.child(e),i=this.Rc({path:t,mc:!1});return i.Ac(),i}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return By(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find(n=>e.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>e.isPrefixOf(n.field))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(F3(this.Ec)&&kse.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},YL=class{constructor(e,n,t){this.databaseId=e,this.ignoreUndefinedProperties=n,this.serializer=t||Qy(e)}Dc(e,n,t,i=!1){return new KL({Ec:e,methodName:n,bc:t,path:gn.emptyPath(),mc:!1,Sc:i},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function tS(r){let e=r._freezeSettings(),n=Qy(r._databaseId);return new YL(r._databaseId,!!e.ignoreUndefinedProperties,n)}function k3(r,e,n,t,i,o={}){let s=r.Dc(o.merge||o.mergeFields?2:0,e,n,i);GM("Data must be an object, but it was:",s,t);let a=V3(t,s),c,l;if(o.merge)c=new qr(s.fieldMask),l=s.fieldTransforms;else if(o.mergeFields){let u=[];for(let d of o.mergeFields){let f=QL(e,d,n);if(!s.contains(f))throw new Q(W.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);G3(u,f)||u.push(f)}c=new qr(u),l=s.fieldTransforms.filter(d=>c.covers(d.field))}else c=null,l=s.fieldTransforms;return new qL(new er(a),c,l)}var Vy=class r extends Ap{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof r}};function Use(r,e,n,t){let i=r.Dc(1,e,n);GM("Data must be an object, but it was:",i,t);let o=[],s=er.empty();sc(t,(c,l)=>{let u=$M(e,c,n);l=Be(l);let d=i.gc(u);if(l instanceof Vy)o.push(u);else{let f=Pp(l,d);f!=null&&(o.push(u),s.set(u,f))}});let a=new qr(o);return new Uy(s,a,i.fieldTransforms)}function Vse(r,e,n,t,i,o){let s=r.Dc(1,e,n),a=[QL(e,t,n)],c=[i];if(o.length%2!=0)throw new Q(W.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<o.length;f+=2)a.push(QL(e,o[f])),c.push(o[f+1]);let l=[],u=er.empty();for(let f=a.length-1;f>=0;--f)if(!G3(l,a[f])){let g=a[f],p=c[f];p=Be(p);let _=s.gc(g);if(p instanceof Vy)l.push(g);else{let T=Pp(p,_);T!=null&&(l.push(g),u.set(g,T))}}let d=new qr(l);return new Uy(u,d,s.fieldTransforms)}function U3(r,e,n,t=!1){return Pp(n,r.Dc(t?4:3,e))}function Pp(r,e){if(B3(r=Be(r)))return GM("Unsupported field value:",e,r),V3(r,e);if(r instanceof Ap)return(function(t,i){if(!F3(i.Ec))throw i.wc(`${t._methodName}() can only be used with update() and set()`);if(!i.path)throw i.wc(`${t._methodName}() is not currently supported inside arrays`);let o=t._toFieldTransform(i);o&&i.fieldTransforms.push(o)})(r,e),null;if(r===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),r instanceof Array){if(e.settings.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(t,i){let o=[],s=0;for(let a of t){let c=Pp(a,i.yc(s));c==null&&(c={nullValue:"NULL_VALUE"}),o.push(c),s++}return{arrayValue:{values:o}}})(r,e)}return(function(t,i){if((t=Be(t))===null)return{nullValue:"NULL_VALUE"};if(typeof t=="number")return Aoe(i.serializer,t);if(typeof t=="boolean")return{booleanValue:t};if(typeof t=="string")return{stringValue:t};if(t instanceof Date){let o=wt.fromDate(t);return{timestampValue:kh(i.serializer,o)}}if(t instanceof wt){let o=new wt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:kh(i.serializer,o)}}if(t instanceof qa)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Fs)return{bytesValue:$W(i.serializer,t._byteString)};if(t instanceof pn){let o=i.databaseId,s=t.firestore._databaseId;if(!s.isEqual(o))throw i.wc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${o.projectId}/${o.database}`);return{referenceValue:yM(t.firestore._databaseId||i.databaseId,t._key.path)}}if(t instanceof Ka)return(function(s,a){return{mapValue:{fields:{[pM]:{stringValue:EM},[Lh]:{arrayValue:{values:s.toArray().map(l=>{if(typeof l!="number")throw a.wc("VectorValues must only contain numeric values.");return vM(a.serializer,l)})}}}}}})(t,i);throw i.wc(`Unsupported field value: ${$y(t)}`)})(r,e)}function V3(r,e){let n={};return dW(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):sc(r,(t,i)=>{let o=Pp(i,e.Vc(t));o!=null&&(n[t]=o)}),{mapValue:{fields:n}}}function B3(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof wt||r instanceof qa||r instanceof Fs||r instanceof pn||r instanceof Ap||r instanceof Ka)}function GM(r,e,n){if(!B3(n)||!YH(n)){let t=$y(n);throw t==="an object"?e.wc(r+" a custom object"):e.wc(r+" "+t)}}function QL(r,e,n){if((e=Be(e))instanceof Hh)return e._internalPath;if(typeof e=="string")return $M(r,e);throw By("Field path arguments must be of type string or ",r,!1,void 0,n)}var Bse=new RegExp("[~\\*/\\[\\]]");function $M(r,e,n){if(e.search(Bse)>=0)throw By(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,n);try{return new Hh(...e.split("."))._internalPath}catch{throw By(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,n)}}function By(r,e,n,t,i){let o=t&&!t.isEmpty(),s=i!==void 0,a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(o||s)&&(c+=" (found",o&&(c+=` in field ${t}`),s&&(c+=` in document ${i}`),c+=")"),new Q(W.INVALID_ARGUMENT,a+r+c)}function G3(r,e){return r.some(n=>n.isEqual(e))}var uu=class{constructor(e,n,t,i,o){this._firestore=e,this._userDataWriter=n,this._key=t,this._document=i,this._converter=o}get id(){return this._key.path.lastSegment()}get ref(){return new pn(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new XL(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let n=this._document.data.field(nS("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n)}}},XL=class extends uu{data(){return super.data()}};function nS(r,e){return typeof e=="string"?$M(r,e):e instanceof Hh?e._internalPath:e._delegate._internalPath}function $3(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new Q(W.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Rp=class{},Wh=class extends Rp{};function j3(r,e,...n){let t=[];e instanceof Rp&&t.push(e),t=t.concat(n),(function(o){let s=o.filter(c=>c instanceof zh).length,a=o.filter(c=>c instanceof Dp).length;if(s>1||s>0&&a>0)throw new Q(W.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(...)))`.")})(t);for(let i of t)r=i._apply(r);return r}var Dp=class r extends Wh{constructor(e,n,t){super(),this._field=e,this._op=n,this._value=t,this.type="where"}static _create(e,n,t){return new r(e,n,t)}_apply(e){let n=this._parse(e);return Q3(e._query,n),new Xi(e.firestore,e.converter,Nw(e._query,n))}_parse(e){let n=tS(e.firestore);return(function(o,s,a,c,l,u,d){let f;if(l.isKeyField()){if(u==="array-contains"||u==="array-contains-any")throw new Q(W.INVALID_ARGUMENT,`Invalid Query. You can't perform '${u}' queries on documentId().`);if(u==="in"||u==="not-in"){WH(d,u);let p=[];for(let _ of d)p.push(HH(c,o,_));f={arrayValue:{values:p}}}else f=HH(c,o,d)}else u!=="in"&&u!=="not-in"&&u!=="array-contains-any"||WH(d,u),f=U3(a,s,d,u==="in"||u==="not-in");return Ge.create(l,u,f)})(e._query,"where",n,e.firestore._databaseId,this._field,this._op,this._value)}};function H3(r,e,n){let t=e,i=nS("where",r);return Dp._create(i,t,n)}var zh=class r extends Rp{constructor(e,n){super(),this.type=e,this._queryConstraints=n}static _create(e,n){return new r(e,n)}_parse(e){let n=this._queryConstraints.map(t=>t._parse(e)).filter(t=>t.getFilters().length>0);return n.length===1?n[0]:tt.create(n,this._getOperator())}_apply(e){let n=this._parse(e);return n.getFilters().length===0?e:((function(i,o){let s=i,a=o.getFlattenedFilters();for(let c of a)Q3(s,c),s=Nw(s,c)})(e._query,n),new Xi(e.firestore,e.converter,Nw(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};function W3(...r){return r.forEach(e=>X3("or",e)),zh._create("or",r)}function z3(...r){return r.forEach(e=>X3("and",e)),zh._create("and",r)}var JL=class r extends Wh{constructor(e,n){super(),this._field=e,this._direction=n,this.type="orderBy"}static _create(e,n){return new r(e,n)}_apply(e){let n=(function(i,o,s){if(i.startAt!==null)throw new Q(W.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(i.endAt!==null)throw new Q(W.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new tu(o,s)})(e._query,this._field,this._direction);return new Xi(e.firestore,e.converter,(function(i,o){let s=i.explicitOrderBy.concat([o]);return new zo(i.path,i.collectionGroup,s,i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt)})(e._query,n))}};function q3(r,e="asc"){let n=e,t=nS("orderBy",r);return JL._create(t,n)}var ZL=class r extends Wh{constructor(e,n,t){super(),this.type=e,this._limit=n,this._limitType=t}static _create(e,n,t){return new r(e,n,t)}_apply(e){return new Xi(e.firestore,e.converter,sy(e._query,this._limit,this._limitType))}};function K3(r){return Bie("limit",r),ZL._create("limit",r,"F")}var eM=class r extends Wh{constructor(e,n,t){super(),this.type=e,this._docOrFields=n,this._inclusive=t}static _create(e,n,t){return new r(e,n,t)}_apply(e){let n=Gse(e,this.type,this._docOrFields,this._inclusive);return new Xi(e.firestore,e.converter,(function(i,o){return new zo(i.path,i.collectionGroup,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,o,i.endAt)})(e._query,n))}};function Y3(...r){return eM._create("startAfter",r,!1)}function Gse(r,e,n,t){if(n[0]=Be(n[0]),n[0]instanceof uu)return(function(o,s,a,c,l){if(!c)throw new Q(W.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${a}().`);let u=[];for(let d of Ih(o))if(d.field.isKeyField())u.push(eu(s,c.key));else{let f=c.data.field(d.field);if(zy(f))throw new Q(W.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+d.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(f===null){let g=d.field.canonicalString();throw new Q(W.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${g}' (used as the orderBy) does not exist.`)}u.push(f)}return new Wo(u,l)})(r._query,r.firestore._databaseId,e,n[0]._document,t);{let i=tS(r.firestore);return(function(s,a,c,l,u,d){let f=s.explicitOrderBy;if(u.length>f.length)throw new Q(W.INVALID_ARGUMENT,`Too many arguments provided to ${l}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let g=[];for(let p=0;p<u.length;p++){let _=u[p];if(f[p].field.isKeyField()){if(typeof _!="string")throw new Q(W.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${l}(), but got a ${typeof _}`);if(!TM(s)&&_.indexOf("/")!==-1)throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${l}() must be a plain document ID, but '${_}' contains a slash.`);let T=s.path.child(He.fromString(_));if(!se.isDocumentKey(T))throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${l}() must result in a valid document path, but '${T}' is not because it contains an odd number of segments.`);let D=new se(T);g.push(eu(a,D))}else{let T=U3(c,l,_);g.push(T)}}return new Wo(g,d)})(r._query,r.firestore._databaseId,i,e,n,t)}}function HH(r,e,n){if(typeof(n=Be(n))=="string"){if(n==="")throw new Q(W.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!TM(e)&&n.indexOf("/")!==-1)throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let t=e.path.child(He.fromString(n));if(!se.isDocumentKey(t))throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${t}' is not because it has an odd number of segments (${t.length}).`);return eu(r,new se(t))}if(n instanceof pn)return eu(r,n._key);throw new Q(W.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${$y(n)}.`)}function WH(r,e){if(!Array.isArray(r)||r.length===0)throw new Q(W.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function Q3(r,e){let n=(function(i,o){for(let s of i)for(let a of s.getFlattenedFilters())if(o.indexOf(a.op)>=0)return a.op;return null})(r.filters,(function(i){switch(i){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[]}})(e.op));if(n!==null)throw n===e.op?new Q(W.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new Q(W.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`)}function X3(r,e){if(!(e instanceof Dp||e instanceof zh))throw new Q(W.INVALID_ARGUMENT,`Function ${r}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}var Gy=class{convertValue(e,n="none"){switch(Xa(e)){case 0:return null;case 1:return e.booleanValue;case 2:return bt(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,n);case 5:return e.stringValue;case 6:return this.convertBytes(Vs(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,n);case 11:return this.convertObject(e.mapValue,n);case 10:return this.convertVectorValue(e.mapValue);default:throw ae(62114,{value:e})}}convertObject(e,n){return this.convertObjectMap(e.fields,n)}convertObjectMap(e,n="none"){let t={};return sc(e,(i,o)=>{t[i]=this.convertValue(o,n)}),t}convertVectorValue(e){var n,t,i;let o=(i=(t=(n=e.fields)===null||n===void 0?void 0:n[Lh].arrayValue)===null||t===void 0?void 0:t.values)===null||i===void 0?void 0:i.map(s=>bt(s.doubleValue));return new Ka(o)}convertGeoPoint(e){return new qa(bt(e.latitude),bt(e.longitude))}convertArray(e,n){return(e.values||[]).map(t=>this.convertValue(t,n))}convertServerTimestamp(e,n){switch(n){case"previous":let t=qy(e);return t==null?null:this.convertValue(t,n);case"estimate":return this.convertTimestamp(sp(e));default:return null}}convertTimestamp(e){let n=Us(e);return new wt(n.seconds,n.nanos)}convertDocumentKey(e,n){let t=He.fromString(e);fe(XW(t),9688,{name:e});let i=new wh(t.get(1),t.get(3)),o=new se(t.popFirst(5));return i.isEqual(n)||Wt(`Document ${o} contains a document reference within a different database (${i.projectId}/${i.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),o}};function J3(r,e,n){let t;return t=r?n&&(n.merge||n.mergeFields)?r.toFirestore(e,n):r.toFirestore(e):e,t}var tM=class extends Gy{constructor(e){super(),this.firestore=e}convertBytes(e){return new Fs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new pn(this.firestore,null,n)}};function $se(){return new WL("count")}var Wa=class{constructor(e,n){this.hasPendingWrites=e,this.fromCache=n}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},Ya=class r extends uu{constructor(e,n,t,i,o,s){super(e,n,t,i,s),this._firestore=e,this._firestoreImpl=e,this.metadata=o}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let n=new yh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,n={}){if(this._document){let t=this._document.data.field(nS("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t,n.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(W.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,n={};return n.type=r._jsonSchemaVersion,n.bundle="",n.bundleSource="DocumentSnapshot",n.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?n:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),n.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),n)}};Ya._jsonSchemaVersion="firestore/documentSnapshot/1.0",Ya._jsonSchema={type:nn("string",Ya._jsonSchemaVersion),bundleSource:nn("string","DocumentSnapshot"),bundleName:nn("string"),bundle:nn("string")};var yh=class extends Ya{data(e={}){return super.data(e)}},Zl=class r{constructor(e,n,t,i){this._firestore=e,this._userDataWriter=n,this._snapshot=i,this.metadata=new Wa(i.hasPendingWrites,i.fromCache),this.query=t}get docs(){let e=[];return this.forEach(n=>e.push(n)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,n){this._snapshot.docs.forEach(t=>{e.call(n,new yh(this._firestore,this._userDataWriter,t.key,t,new Wa(this._snapshot.mutatedKeys.has(t.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let n=!!e.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new Q(W.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===n||(this._cachedChanges=(function(i,o){if(i._snapshot.oldDocs.isEmpty()){let s=0;return i._snapshot.docChanges.map(a=>{let c=new yh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new Wa(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter);return a.doc,{type:"added",doc:c,oldIndex:-1,newIndex:s++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(a=>o||a.type!==3).map(a=>{let c=new yh(i._firestore,i._userDataWriter,a.doc.key,a.doc,new Wa(i._snapshot.mutatedKeys.has(a.doc.key),i._snapshot.fromCache),i.query.converter),l=-1,u=-1;return a.type!==0&&(l=s.indexOf(a.doc.key),s=s.delete(a.doc.key)),a.type!==1&&(s=s.add(a.doc),u=s.indexOf(a.doc.key)),{type:jse(a.type),doc:c,oldIndex:l,newIndex:u}})}})(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new Q(W.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=r._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=Zm.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let n=[],t=[],i=[];return this.docs.forEach(o=>{o._document!==null&&(n.push(o._document),t.push(this._userDataWriter.convertObjectMap(o._document.data.value.mapValue.fields,"previous")),i.push(o.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function jse(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return ae(61501,{type:r})}}function Z3(r){r=Or(r,pn);let e=Or(r.firestore,Ji);return Mse(Jh(e),r._key).then(n=>oz(e,r,n))}Zl._jsonSchemaVersion="firestore/querySnapshot/1.0",Zl._jsonSchema={type:nn("string",Zl._jsonSchemaVersion),bundleSource:nn("string","QuerySnapshot"),bundleName:nn("string"),bundle:nn("string")};var du=class extends Gy{constructor(e){super(),this.firestore=e}convertBytes(e){return new Fs(e)}convertReference(e){let n=this.convertDocumentKey(e,this.firestore._databaseId);return new pn(this.firestore,null,n)}};function ez(r){r=Or(r,Xi);let e=Or(r.firestore,Ji),n=Jh(e),t=new du(e);return $3(r._query),Pse(n,r._query).then(i=>new Zl(e,t,r,i))}function tz(r,e,n){r=Or(r,pn);let t=Or(r.firestore,Ji),i=J3(r.converter,e,n);return iz(t,[k3(tS(t),"setDoc",r._key,i,r.converter!==null,n).toMutation(r._key,Vn.none())])}function nz(r){return iz(Or(r.firestore,Ji),[new ou(r._key,Vn.none())])}function rz(r,...e){var n,t,i;r=Be(r);let o={includeMetadataChanges:!1,source:"default"},s=0;typeof e[s]!="object"||jH(e[s])||(o=e[s++]);let a={includeMetadataChanges:o.includeMetadataChanges,source:o.source};if(jH(e[s])){let d=e[s];e[s]=(n=d.next)===null||n===void 0?void 0:n.bind(d),e[s+1]=(t=d.error)===null||t===void 0?void 0:t.bind(d),e[s+2]=(i=d.complete)===null||i===void 0?void 0:i.bind(d)}let c,l,u;if(r instanceof pn)l=Or(r.firestore,Ji),u=wp(r._key.path),c={next:d=>{e[s]&&e[s](oz(l,r,d))},error:e[s+1],complete:e[s+2]};else{let d=Or(r,Xi);l=Or(d.firestore,Ji),u=d._query;let f=new du(l);c={next:g=>{e[s]&&e[s](new Zl(l,f,d,g))},error:e[s+1],complete:e[s+2]},$3(r._query)}return(function(f,g,p,_){let T=new Sp(_),D=new yp(g,T,p);return f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return bM(yield xy(f),D)})),()=>{T.Ou(),f.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return wM(yield xy(f),D)}))}})(Jh(l),u,a,c)}function iz(r,e){return(function(t,i){let o=new Nr;return t.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){return Ese(yield Lse(t),i,o)})),o.promise})(Jh(r),e)}function oz(r,e,n){let t=n.docs.get(e._key),i=new du(r);return new Ya(r,i,e._key,t,new Wa(n.hasPendingWrites,n.fromCache),e.converter)}function sz(r){return az(r,{count:$se()})}function az(r,e){let n=Or(r.firestore,Ji),t=Jh(n),i=foe(e,(o,s)=>new Lw(s,o.aggregateType,o._internalFieldPath));return xse(t,r._query,i).then(o=>(function(a,c,l){let u=new du(a);return new zL(c,u,l)})(n,r,o))}var nM=class{constructor(e){let n;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),n=e.tabManager):(n=Hse(void 0),n._initialize(e)),this._onlineComponentProvider=n._onlineComponentProvider,this._offlineComponentProvider=n._offlineComponentProvider}toJSON(){return{kind:this.kind}}};function jM(r){return new nM(r)}var rM=class{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=VM.provider,this._offlineComponentProvider={build:n=>new Py(n,e?.cacheSizeBytes,this.forceOwnership)}}},iM=class{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=VM.provider,this._offlineComponentProvider={build:n=>new GL(n,e?.cacheSizeBytes)}}};function Hse(r){return new rM(r?.forceOwnership)}function HM(){return new iM}var Wse={maxAttempts:5};function Hm(r,e){if((r=Be(r)).firestore!==e)throw new Q(W.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return r}var oM=class{constructor(e,n){this._firestore=e,this._transaction=n,this._dataReader=tS(e)}get(e){let n=Hm(e,this._firestore),t=new tM(this._firestore);return this._transaction.lookup([n._key]).then(i=>{if(!i||i.length!==1)return ae(24041);let o=i[0];if(o.isFoundDocument())return new uu(this._firestore,t,o.key,o,n.converter);if(o.isNoDocument())return new uu(this._firestore,t,n._key,null,n.converter);throw ae(18433,{doc:o})})}set(e,n,t){let i=Hm(e,this._firestore),o=J3(i.converter,n,t),s=k3(this._dataReader,"Transaction.set",i._key,o,i.converter!==null,t);return this._transaction.set(i._key,s),this}update(e,n,t,...i){let o=Hm(e,this._firestore),s;return s=typeof(n=Be(n))=="string"||n instanceof Hh?Vse(this._dataReader,"Transaction.update",o._key,n,t,i):Use(this._dataReader,"Transaction.update",o._key,n),this._transaction.update(o._key,s),this}delete(e){let n=Hm(e,this._firestore);return this._transaction.delete(n._key),this}};var sM=class extends oM{constructor(e,n){super(e,n),this._firestore=e}get(e){let n=Hm(e,this._firestore),t=new du(this._firestore);return super.get(e).then(i=>new Ya(this._firestore,t,n._key,i._document,new Wa(!1,!1),n.converter))}};function cz(r,e,n){r=Or(r,Ji);let t=Object.assign(Object.assign({},Wse),n);return(function(o){if(o.maxAttempts<1)throw new Q(W.INVALID_ARGUMENT,"Max attempts must be at least 1")})(t),(function(o,s,a){let c=new Nr;return o.asyncQueue.enqueueAndForget(()=>I(null,null,function*(){let l=yield O3(o);new jL(o.asyncQueue,l,a,s,c).zu()})),c.promise})(Jh(r),i=>e(new sM(r,i)),t)}(function(e,n=!0){(function(i){qh=i})(Sa),lr(new fn("firestore",(t,{instanceIdentifier:i,options:o})=>{let s=t.getProvider("app").getImmediate(),a=new Ji(new nw(t.getProvider("auth-internal")),new ow(s,t.getProvider("app-check-internal")),(function(l,u){if(!Object.prototype.hasOwnProperty.apply(l.options,["projectId"]))throw new Q(W.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new wh(l.options.projectId,u)})(s,i),s);return o=Object.assign({useFetchStreams:n},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),Ke(bj,wj,e),Ke(bj,wj,"esm2017")})();var rS=_e(z3,!0,2);var iS=_e(M3,!0,2),lz=_e(P3,!0,2);var uz=_e(nz,!0,2);var xp=_e(x3,!0,2);var dz=_e(sz,!0),WM=_e(Z3,!0);var hz=_e(ez,!0);var zse=_e(K3,!0,2);var fz=_e(rz,!0);var qse=_e(W3,!0,2),Kse=_e(q3,!0,2),gz=_e(j3,!0,2);var mz=_e(cz,!0),pz=_e(tz,!0,2);var Yse=_e(Y3,!0,2);var Ii=_e(H3,!0,2);var cc=(()=>{let e=class e{constructor(t,i,o){this.authService=t,this.configService=i,this.loggingService=o,this.db$=new Y(null);try{this.authService.getFirebaseConfig$().subscribe(s=>{if(s){let a=this.configService.getProxyConfig(),c=s.firebaseOptions.databaseURL;a?.v1DbHost&&c&&(c=kV(c,a.v1DbHost),a?.forceLongPolling&&Nb());let l=rh(void 0,c);a?.v1DbHost&&c&&this.lockDatabaseHost(l),this.db$.next(l)}},s=>{this.loggingService.catch("Error in DatabaseService constructor: ",s)})}catch(s){this.loggingService.catch("Error in DatabaseService constructor:",s)}}getDb(){return this.db$.asObservable()}getDbValue(){return this.db$.getValue()}lockDatabaseHost(t){try{let o=t?._repo?.repoInfo_;if(o){let s=o.host;Object.defineProperty(o,"host",{get:()=>s,set:()=>{},configurable:!0}),o.internalHost=s}}catch(i){this.loggingService.catch("Error in DatabaseService lockDatabaseHost: ",i)}}};e.\u0275fac=function(i){return new(i||e)(C(Dr),C(Xn),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var qo=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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 Y(null),this.commentAnnotationById$=new Y({}),this.fieldsToRemove=[],this.additionalFields=[],this.additionalSaveEvents=[],this.getCommentAnnotationById=s=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",a);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove),s.config?.additionalFields&&(this.additionalFields=s.config.additionalFields||[]),this.additionalSaveEvents=(s.config?.additionalSaveEvents||[]).map(a=>a?.event).filter(a=>!!a))})}catch(s){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.commentAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.commentAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",t)}}resolveCommentAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:t}}),f(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.commentAnnotationIds||[])],T=le(M({},t),{commentAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let L=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.commentAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.commentAnnotationById$.next(M(M({},this.commentAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveCommentAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let o=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=M(M({},a),t.commentAnnotation);let c=this.getTargetComment(t.commentAnnotation,t.commentId),l=yield xt(()=>{if(o?.config?.saveConfig?.url){let u={commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,u,!1,o.config.saveConfig.credentials)}return o?.save?.({commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:c,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(t.commentAnnotation),eventType:t.eventType,commentId:t.commentId}),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}getTargetComment(t,i){if(!(!i||!t))for(let o of Object.values(t)){let s=o?.comments?.[i];if(s)return s}}deleteCommentAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let s=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let a=this.commentAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?yn(i):void 0),u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.commentAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({commentAnnotationId:t.toString(),metadata:u,event:Qt.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:g,commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:_t.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:s,commentAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",i);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getAdditionalSaveEvents(){try{return this.additionalSaveEvents}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalSaveEvents:",t),this.additionalSaveEvents}}setCommentAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting comment annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.commentAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",i)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Ko=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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 Y(null),this.reactionAnnotationById$=new Y({}),this.fieldsToRemove=[],this.getReactionAnnotationById=s=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",a);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove||[]))})}catch(s){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",s)}}getProvider(){try{let t=this.reactionAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",t)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}resolveReactionAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:t}}),f(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.reactionAnnotationIds||[])],T=le(M({},t),{reactionAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length||t.folderId){let L=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.reactionAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.reactionAnnotationById$.next(M(M({},this.reactionAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveReactionAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let o=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=M(M({},a),t);let c={reactionAnnotation:t,event:Qt.REACTION_ADD,metadata:Object.values(t??{})?.[0]?.metadata},l=yield xt(()=>o?.config?.saveConfig?.url?$t(o.config.saveConfig.url,o.config.saveConfig.headers,c,!1,o.config.saveConfig.credentials):o?.save?.(c)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return l&&l.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(l?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:l,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(t),eventType:c.event}),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let s=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let a=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),c=i??a?.[t]?.metadata,l=c?yn(c):void 0,u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.reactionAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({reactionAnnotationId:t.toString(),metadata:u,event:Qt.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:g,reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Tt.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:s,reactionAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",i);return}}setReactionAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting reaction annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.reactionAnnotationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",i)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Zh=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,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(s){this.loggingService.catch("Error in AttachmentResolverService constructor:",s)}}getProvider(t){try{let i=t||"default";return this.providers.get(i)||void 0}catch(i){this.loggingService.catch("Error in AttachmentResolverService getProvider:",i);return}}getRetrySaveConfig(t){let i=t||"default";return this.retrySaveConfigs.get(i)||this.defaultRetryConfig}getRetryDeleteConfig(t){let i=t||"default";return this.retryDeleteConfigs.get(i)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(t,i,o,s,a){return I(this,null,function*(){try{let c=typeof i=="function"?yield i():i||{},l=new FormData;l.append("file",o);let u={attachment:{attachmentId:s.attachment.attachmentId,name:s.attachment.name,mimeType:s.attachment.mimeType},metadata:s.metadata,event:s.event};l.append("request",JSON.stringify(u));let d={};Object.entries(c).forEach(([p,_])=>{p.toLowerCase()!=="content-type"&&(d[p]=_)});let f=yield fetch(t,M({method:"POST",headers:d,body:l},a?{credentials:a}:{}));return f.ok?{data:(yield f.json())?.data??{},success:!0,statusCode:200}:(j.catch(`Error in makeAttachmentConfigBasedRequest: ${f.status} ${f.statusText}`),{data:{},success:!1,statusCode:f.status})}catch(c){return j.catch("Error in makeAttachmentConfigBasedRequest:",c),{data:{},success:!1,statusCode:500}}})}saveAttachment(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let s=this.getProvider(o);if(!this.attachmentDataProviderAvailable(o))throw new Error("Attachment save data provider not available");let a=this.getRetrySaveConfig(o),c=i||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{request:t}});let l=yield xt(()=>I(this,null,function*(){if(s?.config?.saveConfig?.url){let u=t.attachment,{file:d}=u,f=NS(u,["file"]);return this.makeAttachmentConfigBasedRequest(s.config.saveConfig.url,s.config.saveConfig.headers,d,{attachment:f,event:t.eventType,metadata:t.attachment.metadata},s.config.saveConfig.credentials)}return s?.save?.({attachment:t.attachment,event:t.eventType,metadata:t.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",a);if(l?.statusCode!==200){this.loggingService.catch(l?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{error:l,request:t}});return}return this.analyticsService.trackEvent(P.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:t.attachment.attachmentId,eventType:t.eventType}),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:c,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{result:l,request:t}}),l}catch(s){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",s);let a=i||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Oo.SAVE_ATTACHMENT,source:"internal",payload:{error:s,request:t}});return}})}deleteAttachment(a,c,l){return I(this,arguments,function*({attachmentId:t,metadata:i},o,s){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let u=this.getProvider(s);if(!this.attachmentDataProviderAvailable(s))throw new Error("Attachment delete data provider not available");let d=i?M({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0,f=this.getRetryDeleteConfig(s),g=o||Z();this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t,metadata:d}});let p=yield xt(()=>{if(u?.config?.deleteConfig?.url){let _={attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE};return $t(u.config.deleteConfig.url,u.config.deleteConfig.headers,_,!1,u.config.deleteConfig.credentials)}return u?.delete?.({attachmentId:t,metadata:d,event:Qt.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",f);return p?.statusCode!==200?(this.loggingService.catch(p?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{error:p,attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:t}),this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:g,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:f.revertOnFailure,isSuccess:!0},attachmentId:t,metadata:d}}),{revertOnFailure:f.revertOnFailure,isSuccess:!0})}catch(u){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",u);let d=this.getRetryDeleteConfig(s),f=o||Z(),g=i?M({apiKey:i.apiKey??null,documentId:i.documentId??null,organizationId:i.organizationId??null},i.folderId&&{folderId:i.folderId}):void 0;return this.coreActionsService.triggerAction(H.ATTACHMENT_RESOLVER,{event:P.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:Oo.DELETE_ATTACHMENT,source:"internal",payload:{error:u,attachmentId:t,metadata:g}}),{revertOnFailure:d.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(t,i="default"){try{if(t){this.loggingService.log(`Setting attachment data provider for scope: ${i}`);let o=t.config,s=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],a=[];if(s.forEach(({method:c,configKey:l})=>{let u=o?.[l]?.url,d=c in t&&typeof t[c]=="function";!u&&!d&&a.push(c)}),a.length>0){let c=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${a.join(", ")}.`;this.loggingService.catch(c);return}else this.providers.set(i,t),t.config?.saveRetryConfig&&this.retrySaveConfigs.set(i,t.config.saveRetryConfig),t.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(i,t.config.deleteRetryConfig)}}catch(o){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",o)}}attachmentDataProviderAvailable(t){try{let i=t||"default";return this.providers.has(i)}catch(i){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",i),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var lc=(()=>{let e=class e{constructor(t,i,o,s){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.attachmentResolverService=s,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 Y(null),this.recorderAnnotationById$=new Y({}),this.additionalFields=[],this.fieldsToRemove=[],this.uploadChunks=!1,this.getRecorderAnnotationById=a=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[a]:void 0}catch(c){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",c);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.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?.additionalFields&&(this.additionalFields=a.config.additionalFields||[]),a.config?.fieldsToRemove&&(this.fieldsToRemove=a.config.fieldsToRemove||[]),this.uploadChunks=a.uploadChunks??!1)})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",a)}}getProvider(){try{let t=this.recorderAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",t)}}resolveRecorderAnnotations(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:t}}),f(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.recorderAnnotationIds||[])],T=le(M({},t),{recorderAnnotationIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let L=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.recorderAnnotationById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.recorderAnnotationById$.next(M(M({},this.recorderAnnotationById$.getValue()),w)),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveRecorderAnnotation(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let o=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=M(M({},a),t.recorderAnnotation);let c=yield xt(()=>{if(o?.config?.saveConfig?.url){let l={recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(c?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(t.recorderAnnotation),eventType:t.eventType}),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:It.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let s=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let a=this.recorderAnnotationById$.getValue(),l=a?.[t]?.metadata??(i?yn(i):void 0),u=l?M({apiKey:l.apiKey??null,documentId:l.documentId??null,organizationId:l.organizationId??null},l.folderId&&{folderId:l.folderId}):void 0,d=o||Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:t.toString(),metadata:u}});let f=M({},a);delete f?.[t],this.recorderAnnotationById$._value=f;let g=yield xt(()=>{if(s?.config?.deleteConfig?.url){let p={recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE};return $t(s.config.deleteConfig.url,s.config.deleteConfig.headers,p,!1,s.config.deleteConfig.credentials)}return s?.delete?.({recorderAnnotationId:t.toString(),metadata:u,event:Qt.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=a),this.loggingService.catch(g?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:g,recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:t.toString()}),this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:t.toString(),metadata:u}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",s);let a=o||Z(),c=i?yn(i):void 0;return this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:It.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,recorderAnnotationId:t.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()):de(void 0)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",t),de(void 0)}}getAnnotationById(t){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[t]:void 0}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",i);return}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting recorder annotation data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else t.storage&&this.attachmentResolverService.setAttachmentDataProvider(t.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(t)}}catch(i){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",i)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot),C(Zh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var aS=class{};var ef=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p){this.analyticsService=t,this.authService=i,this.databaseService=o,this.domService=s,this.configService=a,this.loggingService=c,this.commentResolverService=l,this.reactionResolverService=u,this.recorderResolverService=d,this.coreActionsService=f,this.functions=g,this.serviceBook=p,this.endpointsService=J(xo),this.documentPaths$=new Y(null),this.docContext$=new Y(null),this.documentIds$=new Y([]),this.organizationConfig$=new Y(null),this.firestorePaths$=new Y(null),this.location$=new Y(null),this.excludedLocationIds$=new Y([]),this.organizationMetadata$=new Y(null),this.documentMetadata$=new Y(null),this.locationMetadata$=new Y(null),this.customerMetadata$=new Y(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new Y({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new Y({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new Ct,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.serviceBook.observe(Rd).subscribe(_=>{this.commentService=_??void 0}),z1(()=>this.documentPaths$.value?.clientDocumentId),this.setDocumentIdSubject.pipe(BS(()=>Ni(this.currentDebounceTime))).subscribe({next:_=>I(this,null,function*(){try{yield this.setDocumentIdImpl(_.documentId,_.clientOrganizationId,_.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:_=>{this.loggingService.catch("Error in setDocumentId subscription:",_),this.queueSize--}}),this.databaseService.getDb().pipe(Rt(_=>!!_),Dt(1)).subscribe(_=>{_&&(this.db=_)}),this.configService.getApiKey$().subscribe(_=>{if(this.apiKey=_,this.apiKey){if(!this.isCustomDocId){let T=sI(window.location.href);this.currentUrl=T}this.analyticsService.updateDefaultProperties({apiKey:_})}}),this.authService.getUser$().subscribe(_=>I(this,null,function*(){if(_&&(this.analyticsService.updateDefaultProperties({organizationId:_?.organizationId,clientOrganizationId:_?.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&&_?.organizationId&&this.documentPaths$.value?.organizationId!==_?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(T=>({id:T.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),_?.organizationId&&_?.clientOrganizationId)){let T={organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId};this.getOrganizationConfig()||this.setOrganizationConfig({organizationId:_?.organizationId,clientOrganizationId:_?.clientOrganizationId}),yield this.updateOrganizationMetadata(T)}})),this.documentPaths$.subscribe(_=>{let T={documentId:_?.documentId,clientDocumentId:_?.clientDocumentId,folderId:_?.folderId,allDocuments:_?.allDocuments,veltFolderId:_?.veltFolderId};_?.organizationId&&(T.organizationId=_.organizationId,T.clientOrganizationId=_.clientOrganizationId),this.analyticsService.updateDefaultProperties(T),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(_=>{this.analyticsService.updateDefaultProperties({clientLocation:_?.location,locationId:_?.locationId})}),this.organizationMetadata$.subscribe(_=>{this.authService.setUserOrganization(_?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Rt(_=>!!_),Dt(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(_){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}},_=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",_)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(_){this.loggingService.catch("Error in DocService constructor:",_)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{organizationId:this.documentPaths$.value?.clientOrganizationId,folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,optimisticPermissions:this.documentPaths$.value?.optimisticPermissions}:null}catch(t){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",t),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.setOrganizationConfig(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(t=>({id:t.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(t=>t.location)].filter(t=>t!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(t){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",t)}}setUsersService(t){try{this.usersService=t}catch(i){this.loggingService.catch("Error in setUsersService:",i)}}setCommonDbService(t){try{this.commonDbService=t}catch(i){this.loggingService.catch("Error in setCommonDbService:",i)}}setUserPermissionService(t){try{this.userPermissionService=t}catch(i){this.loggingService.catch("Error in setUserPermissionService:",i)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in setCommentService:",i)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let t=sI(location.href);this.currentUrl!==t&&(this.currentUrl=t,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowPopstate: ",t)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let t=sI(location.href);this.currentUrl!==t&&(this.currentUrl=t,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowClick: ",t)}}setDocument(a){return I(this,arguments,function*({documentId:t,documentMetadata:i,options:o,source:s="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),s==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,documentMetadata:i,methodName:"setDocument",source:s}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENTS,source:s,payload:{documentId:t,documentMetadata:i,options:o}}),yield this.setDocumentsImpl({documents:[{id:t,metadata:i}],options:M({organizationId:i?.organizationId},o??{}),source:s})}catch(c){this.loggingService.catch("Error in DocService setDocument:",c)}})}shouldSetDocumentsAgain(t,i={}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;"),this.pendingDocumentIds.length>0&&t.length===this.pendingDocumentIds.length&&t.every(d=>this.pendingDocumentIds.includes(d.id))&&Ui(i,this.pendingOptions))return!1;let o=this.documentPaths$.value?.clientDocumentId,s=i?.rootDocumentId??t[0]?.id,a=this.documentIds$.value.map(u=>u.clientDocumentId),c=oI(this.getOptionsFromDocumentPaths()??{})??{};return!t.every(u=>a.includes(u.id))||!Ui(c,i)||o!==s}catch(o){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",o),!0}}getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:i=!1}){try{let o=[];return t.forEach(s=>{let a=s.id,c=`${Tr(a)}`;i&&s?.metadata&&typeof s.metadata=="object"&&(this.clientDocumentMetadataMap[a]=s.metadata),o.push({documentId:c,clientDocumentId:a})}),o}catch(o){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",o),[]}}setDocuments(a){return I(this,arguments,function*({documents:t,options:i,source:o="internal",skipPermissionValidation:s=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:t,options:i,methodName:"setDocuments",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENTS,source:o,payload:{documents:t,options:i}}),yield this.setDocumentsImpl({documents:t,options:i??{},source:o,skipPermissionValidation:s})}catch(c){this.loggingService.catch("Error in DocService setDocuments:",c)}})}setRootDocument(o){return I(this,arguments,function*({document:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:Pn.SET_ROOT_DOCUMENT,source:i,payload:{document:t}});let s=this.getOptionsFromDocumentPaths()??{},a=this.documentIds$.value.map(c=>c.clientDocumentId);if(!a.includes(t.id)){let c=[...a.map(u=>({id:u})),{id:t.id}],l=this.getDocumentIdsFromDocuments({documents:c,setClientDocumentMetadataMap:!0});this.documentIds$.next(l)}yield this.setDocumentIdImpl(t.id,this.documentPaths$.value?.clientOrganizationId,s)}catch(s){this.loggingService.catch("Error in DocService setRootDocument:",s)}})}setDocContext(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let i=JSON.parse(JSON.stringify(t??null));this.docContext$.next(i)}catch(i){this.loggingService.catch("Error in setDocContext: ",i)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(rt(Pt))}getProcessedDocContext(){return JV(this.getDocContext())}filterRelevantDocuments(s){return I(this,arguments,function*({options:t,documentIds:i,skipPermissionValidation:o=!1}){try{let a=this.authService.getUser();return!a||!this.commonDbService?.shouldUseFirestore()||(i=yield this.fetchDocumentsFromFolder(t,i,a),yield this.handlePermissionProvider(t,i,a),i=yield this.filterDocumentsByPermissions(t,i,a,o),i=i.slice(0,50)),i}catch(a){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",a),i}})}fetchDocumentsFromFolder(t,i,o){return I(this,null,function*(){if(!t?.folderId||!t?.allDocuments)return i;try{let s=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));(yield Md({methodName:"getDocuments",data:{type:"getDocuments",metadata:{organizationId:t?.organizationId??o?.clientOrganizationId,folderId:t?.folderId}},getSdkProxy:s,userId:o?.userId??""}))?.data?.forEach(c=>{i.find(l=>l.clientDocumentId===c.id)||i.push({documentId:_a(c.id),clientDocumentId:c.id})})}catch(s){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",s)}return i})}buildPermissionRequests(t,i,o){try{let s=[];return t.organizationId&&t.organizationId!==o.clientOrganizationId&&s.push({userId:o.userId,resource:{id:t.organizationId,type:ki.ORGANIZATION,source:Qn.SET_DOCUMENTS,organizationId:t.organizationId,context:t?.context}}),t.folderId&&s.push({userId:o.userId,resource:{id:t.folderId,type:ki.FOLDER,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context}}),i&&i.forEach(a=>{s.push({userId:o.userId,resource:M({id:a.clientDocumentId,type:ki.DOCUMENT,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:t?.context},t?.folderId&&{parentFolderId:t.folderId})})}),t?.context&&this.userPermissionService?.getIsContextEnabled()&&ZV({input:t?.context}).forEach(c=>{let l=JSON.stringify(c.access);s.push({userId:o.userId,resource:{id:l,type:ki.CONTEXT,source:Qn.SET_DOCUMENTS,organizationId:t?.organizationId??o?.clientOrganizationId??"",context:c}})}),s}catch(s){return this.loggingService.catch("Error in buildPermissionRequests:",s),[]}}processAccessibleContexts(t,i){try{if(!t?.success||!t?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let o=t.data.filter(s=>s.type===ki.CONTEXT&&s.hasAccess).map(s=>s.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(o??"nil"))),o?.length){let s=i.filter(c=>o.includes(c.resource.id)).map(c=>c.resource.context).filter(c=>!!c),a=eB({input:s});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(a??"nil"))),a?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(a??"nil"))),this.setDocContext(a))}}catch(o){this.loggingService.catch("Error in processAccessibleContexts:",o)}}handlePermissionProvider(t,i,o){return I(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil")));let s=this.buildPermissionRequests(t,i,o),a=Z();this.coreActionsService.triggerAction(H.PERMISSION_PROVIDER,{event:P.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Qn.SET_DOCUMENTS,uniqueId:a,timestamp:new Date().getTime(),source:"internal",payload:{requests:s}}),this.userPermissionService?.cancelPendingRevokes(s);let c=yield this.userPermissionService?.onResourceAccessRequired({requests:s,uniqueId:a,methodName:Qn.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(c??"nil")),"requests:",JSON.parse(JSON.stringify(s??"nil"))),this.processAccessibleContexts(c,s)}catch(s){this.loggingService.catch("Error in handlePermissionProvider:",s)}})}filterDocumentsByPermissions(t,i,o,s=!1){return I(this,null,function*(){if(s)return i;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(i??"nil")),"user:",JSON.parse(JSON.stringify(o??"nil"))),!(t?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(t,i,o);let c=this.currentValidationToken,l=[...i];return c&&this.validatePermissionsInBackground(t,i,o,c),l})}validateAndFilterPermissions(t,i,o){return I(this,null,function*(){try{let s=t?.organizationId??o?.clientOrganizationId,a=yield this.userPermissionService?.getUserPermissions({organizationId:s,documentIds:i.map(u=>u.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]});if(!a)return i;this.userPermissionService?.setCurrentUserPermissions(a),s&&a?.[o.userId]?.organization?.[s]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${s}`,void 0,void 0,!0),t?.folderId&&a?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0);let c=new Set;Object.entries(a?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Rs.PERMISSION_DENIED&&c.add(u)}),c.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...c].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...c],userId:o.userId,timestamp:new Date().getTime()}));let l=i.filter(u=>!c.has(u.clientDocumentId));return l.length===0&&i.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),l}catch(s){return this.loggingService.catch("Error in validateAndFilterPermissions:",s),i}})}validatePermissionsInBackground(t,i,o,s){let a=t?.organizationId??o?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:a,documentIds:i.map(c=>c.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]}).then(c=>{if(this.currentValidationToken===s&&c){this.userPermissionService?.setCurrentUserPermissions(c);let l=[];Object.entries(c?.[o.userId]?.documents??{}).forEach(([u,d])=>{d?.errorCode===Rs.PERMISSION_DENIED&&l.push(u)}),a&&c?.[o.userId]?.organization?.[a]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${a}`,void 0,void 0,!0),t?.folderId&&c?.[o.userId]?.folders?.[t?.folderId]?.errorCode===Rs.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0),l.length>0&&(this.loggingService.catch(`User does not have access to documents: ${l.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(l,o,s))}}).catch(c=>{this.loggingService.catch("Error in background permission validation:",c)})}handleDeniedDocumentAccess(t,i,o){try{if(this.currentValidationToken!==o)return;let s=this.documentPaths$.value;this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:t,userId:i.userId,timestamp:new Date().getTime()});let a=this.documentIds$.value||[],c=a.filter(l=>!t.includes(l.clientDocumentId));c.length!==a.length&&(c.length>0?this.setDocuments({documents:c.map(l=>({id:l.clientDocumentId})),options:{organizationId:s?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(H.ERROR,{event:P.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:t,userId:i.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(s){this.loggingService.catch("Error in handleDeniedDocumentAccess:",s)}}addUserInfoToOrganization(a){return I(this,arguments,function*({organizationId:t,user:i,notificationsConfig:o,currentUserId:s}){try{let c=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Md({data:M({type:"addUserInfoToOrganization",metadata:{organizationId:t},user:this.usersService?.externalUserDataProviderAvailable()?{userId:i?.userId}:i},o&&{notificationsConfig:o}),getSdkProxy:c,userId:s??i?.userId??""})}catch(c){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",c)}})}setDocumentsImpl(a){return I(this,arguments,function*({documents:t,options:i,source:o,skipPermissionValidation:s=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(t??"nil")),"options:",JSON.parse(JSON.stringify(i??"nil"))),!this.shouldSetDocumentsAgain(t,oI(i))){o==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let c=Z();this.currentValidationToken=c;let l=this.getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:!0});if(l?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let u=this.authService.getUser();if(!u){this.draftDocuments=t,this.draftOptions=i;return}this.pendingDocumentIds=t.map(f=>f.id),this.pendingOptions=oI(i)??{},this.documentPaths$.value?.organizationId&&i?.organizationId&&this.documentPaths$.value?.clientOrganizationId!==i?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let d=i?.organizationId??u?.clientOrganizationId;if(d&&this.addUserInfoToOrganization({organizationId:d,user:u}),l=yield this.filterRelevantDocuments({options:i,documentIds:l,skipPermissionValidation:s}),this.documentIds$.next(l),l?.length){let f=l[0]?.clientDocumentId;i?.rootDocumentId&&l.find(g=>g.clientDocumentId===i?.rootDocumentId)&&(f=i?.rootDocumentId),yield this.debounceSetDocuments({documentId:f,clientOrganizationId:i?.organizationId,options:i})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(c){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",c)}})}setDocumentId(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,clientOrganizationId:i,methodName:"setDocumentId",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:Pn.SET_DOCUMENT_ID,source:o,payload:{documentId:t,clientOrganizationId:i}}),yield this.setDocumentsImpl({documents:[{id:t}],options:{organizationId:i},source:o})}catch(a){this.loggingService.catch("Error in setDocumentId:",a);return}})}debounceSetDocuments(s){return I(this,arguments,function*({documentId:t,clientOrganizationId:i,options:o}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let a=o?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=a;let c=Date.now(),l=c-this.lastSetDocumentIdCallTime,u=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||l>a&&u>a){yield this.setDocumentIdImpl(t,i,o),this.lastSetDocumentIdExecutionTime=c;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:t,clientOrganizationId:i,options:o??void 0});return}catch(a){this.loggingService.catch("Error in debounceSetDocuments:",a)}})}setDocumentIdImpl(t,i,o){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let s=this.authService.getUser();if(!s)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let a=this.currentDocumentId;if(this.apiKey){let c=`${Tr(t)}`,l=o?.folderId,u=o?.folderId?bo(o?.folderId):void 0,d=o?.locationId,f=o?.allDocuments,g=o?.optimisticPermissions,p=s?.organizationId?i?fi(i):s?.organizationId:void 0,_=Z(),T=Nd.SET_DOCUMENTS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:_,methodName:_t.INIT_DOCUMENTS,moduleName:T,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let D=Z(),L=Od.SET_DOCUMENTS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,moduleName:L,methodName:Tt.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}});let B=Z(),w=bd.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:B,moduleName:w,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:_,moduleName:T}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:D,moduleName:L}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(F=>F.clientDocumentId),organizationId:i??s?.clientOrganizationId??""},uniqueId:B,moduleName:w})]),this.currentDocumentId!==c||this.documentPaths$.value?.organizationId!==p){this.loggingService.log("setting new docid"),this.currentDocumentId=c;let F=new XT,U=new aS;F.clientDocumentId=t,U.clientDocumentId=t,F.folderId=l,U.folderId=l,F.locationId=d,U.locationId=d,F.allDocuments=f,F.optimisticPermissions=g,U.allDocuments=f,U.optimisticPermissions=g,F.veltFolderId=u,U.veltFolderId=u,F.documentId=c,U.documentId=c,p&&(F.organizationId=p,F.clientOrganizationId=i??s?.clientOrganizationId,U.organizationId=p,U.clientOrganizationId=i??s?.clientOrganizationId);let A=`${this.apiKey}`,R=`apiKey/${this.apiKey}`;p&&(A=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${F.organizationId}`,R=`${R}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${F.organizationId}`),U.organization=`apiKey/${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,U.document=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,F.presence=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,F.cursor=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,F.comment=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,U.comment=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,F.multiThread=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,U.multiThread=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,F.tag=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,F.area=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,U.area=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AREA}`,F.arrow=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,F.selection=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,F.audioHuddle=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,F.huddle=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,F.recorder=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,U.recorder=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,F.flock=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,F.syncVideoPlayer=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,F.liveState=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,F.liveStateSingleEditorMode=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,F.reaction=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,U.reaction=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,F.crdt=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,U.crdt=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,F.customerMetadata=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,F.views=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,U.notificationViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,U.documentViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,U.locationViews=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,F.notifications=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,F.metadata=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,F.users=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,F.documentIam=`${A}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.workspaceIam=`${this.apiKey}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.groupContacts=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,F.globalContacts=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,F.logins=`${A}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,F.userFeedback=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,F.userReportBugs=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,F.userContactUs=`${A}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,p&&(F.organizationMetadata=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,F.organizationIam=`${A}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,F.organizationGroups=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,F.organizationNotifications=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,c&&(F.organizationNotificationsWithDocumentId=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/`,F.heartbeatByDocument=`${A}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${c}/`),F.organizationNotificationsLastNotificationTimestamp=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,F.organizationNotificationsUsers=`${A}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,F.heartbeat=`${A}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),U.organizationUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,U.users=`${R}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,U.documentUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${c}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,U.notificationDocs=`${R}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,U.notificationUsers=`${R}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(F),this.firestorePaths$.next(U),F?.clientOrganizationId&&F?.organizationId&&!(F?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&F?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.setOrganizationConfig({organizationId:F?.organizationId,clientOrganizationId:F?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),a&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:c,clientDocumentId:t}}),this.analyticsService.trackEvent(P.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:c,clientDocumentId:t},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(s){this.loggingService.catch("Error in setDocumentIdImpl: ",s)}})}unsetDocumentId({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:t}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:Pn.UNSET_DOCUMENT_ID,source:t}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocumentId: ",o)}}unsetDocumentImpl({source:t,unsetDocumentPaths:i}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let o=JSON.parse(JSON.stringify(this.documentIds$.value??[])),s=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),a=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),i&&(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:o,folderId:s,context:a}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:t}),this.analyticsService.trackEvent(P.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:t==="external"?"User unset document id":"System unset document id",source:t},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetDocumentImpl: ",o)}}unsetDocuments({source:t,unsetDocumentPaths:i=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:t}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:t,methodName:Pn.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:i})}catch(o){this.loggingService.catch("Error in unsetDocuments: ",o)}}addPreDocumentIdChangeFunction(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(t,i)}catch(o){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",o)}}callPreDocumentIdChangeFunctions(t){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[i,o]of this.preDocumentIdChangeFunctions)try{yield o(t)}catch(s){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",s)}}catch(i){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",i)}})}fetchOrganizationMetadata(t){return I(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig()),this.db&&t?.organizationId){let i=t?.organizationId,o=t?.clientOrganizationId,s=this.authService.getUser()?.userId??"",a=yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o});if(s&&a?.[s]?.organization?.[o]?.errorCode===Rs.PERMISSION_DENIED)return;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:i,field:"metadata"}}).then(c=>{c&&!c?.errorCode&&this.organizationMetadata$.next(le(M({},this.organizationMetadata$.value),{[i]:c}))}).catch(c=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",c)})}}catch(i){this.loggingService.catch("Error in fetchOrganizationMetadata: ",i)}})}fetchDocumentMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value,o=this.documentMetadata$.value;if(t=t.filter(s=>!o?.[s.documentId]),t?.some(s=>!s?.documentId||!s?.clientDocumentId)||!i)return;if(this.commonDbService?.shouldUseFirestore()){let s=i?.folderId,a=[],c={organizationId:i?.clientOrganizationId,folderId:s},l=[],u=20;for(let f=0;f<t.length;f+=u)l.push(t.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchDocuments(g))});let d={};a.length>0&&(yield Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=p.metadata)})}),this.setAllDocumentMetadata(M(M({},this.documentMetadata$.value),d))}).catch(f=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",f)}))}else o?.[i?.documentId??t?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:i?.organizationId,documentId:i?.documentId??t?.[0]?.documentId,skipObjectValues:!0}}).then(s=>{s?.documentId&&this.setDocumentMetadata(s.documentId,s)}).catch(s=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",s)})}}catch(i){this.loggingService.catch("Error in fetchDocumentMetadata: ",i)}})}fetchLocationMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value,i=this.documentIds$.value,o=t?.folderId,s=t?.allDocuments,a=[],c={organizationId:t?.clientOrganizationId,folderId:o,allDocuments:s},l=[],u=20;for(let f=0;f<i.length;f+=u)l.push(i.slice(f,f+u));l.forEach(f=>{let g=JSON.parse(JSON.stringify(c));g.documentIds=f.map(p=>p.clientDocumentId),a.push(this.fetchLocations(g))});let d=this.locationMetadata$.value??{};a.length>0&&Promise.all(a).then(f=>{f?.forEach(g=>{g?.forEach(p=>{p?.metadata?.documentId&&(d[p.metadata.documentId]=le(M({},d?.[p.metadata.documentId]??{}),{[p.location.id]:p}))})}),Object.keys(d||{}).length>0&&this.locationMetadata$.next(d)}).catch(f=>{this.loggingService.catch("Error in fetchLocationMetadata: ",f)})}}catch(t){this.loggingService.catch("Error in fetchLocationMetadata: ",t)}})}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(as(i=>de(null))).subscribe(i=>{this.customerMetadata$.next(i?.data)}))}catch(t){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",t)}}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(t=>t?.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(t){try{return`${Tr(t)}`}catch(i){return this.loggingService.catch("Error in generateDocumentId: ",i),""}}generateOrganizationId(t){try{return`${fi(t)}`}catch(i){return this.loggingService.catch("Error in generateOrganizationId: ",i),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:void 0,methodName:"setLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,source:i,methodName:Pn.SET_LOCATION,payload:{locations:[t],options:void 0}}),this.setLocationsImpl({locations:[t]})}catch(s){this.loggingService.catch("Error in setLocation: ",s)}})}setLocations(s){return I(this,arguments,function*({locations:t,options:i,source:o="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),o==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:t,options:i,methodName:"setLocations",source:o}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:Pn.SET_LOCATIONS,source:o,payload:{locations:t,options:i}}),this.setLocationsImpl({locations:t,options:i})}catch(a){this.loggingService.catch("Error in setLocations: ",a)}})}getValidLocations(t){try{let i=[];return t&&Array.isArray(t)&&t.forEach(o=>{if(o&&typeof o=="object"){let s=!0;o?.version&&(!o?.version?.id||!o?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${o?.id}, If you're setting version then add id and name fields to version object.`),s=!1),s&&i.push(o)}}),i}catch(i){this.loggingService.catch("Error in getValidLocations: ",i)}return t}setRootLocation(o){return I(this,arguments,function*({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:t,methodName:"setRootLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:Pn.SET_ROOT_LOCATION,source:i,payload:{location:t}});let s=Object.values(this.locations$.value).map(a=>a.location).filter(a=>String(a.id)!==String(t.id));this.setLocationsImpl({locations:[t,...s],options:{rootLocationId:t.id}})}catch(s){this.loggingService.catch("Error in DocService setRootLocation:",s)}})}setLocationsImpl({locations:t,options:i}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),t.length===0)return;if(!this.authService.getUser()){!i?.appendLocation&&t.length>0&&(this.draftLocationMap.options=le(M(M({},this.draftLocationMap.options??{}),i??{}),{rootLocationId:t[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...t],this.draftLocationMap.options=M(M({},this.draftLocationMap.options),i);return}let s=this.getValidLocations(t),a=[],c=[];this.location$.value?.location.id&&c.push(this.location$.value?.location.id),c=[...c,...Object.values(this.locations$.value).map(d=>d.location.id)].filter(d=>d!==void 0);let l;if(i?.rootLocationId&&i?.rootLocationId!==this.location$.value?.location.id&&(l=s.find(d=>d.id===i?.rootLocationId),!l)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${i?.rootLocationId} not found in locations.`);return}if(i?.appendLocation){if(l){let d=Ld(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}}else{l||(l=s[0]);let d=Ld(l),f=Tr(JSON.stringify(d));d.id&&a.push({locationId:f,location:d}),this.location$.next({locationId:f,location:d})}let u=[];return s.slice(i?.appendLocation?0:1).forEach(d=>{if(d.id!==this.location$.value?.location.id){let f=M({},d),g=this.locations$.value;d?.id&&Object.keys(g).forEach(D=>{let L=g[D];L.location?.id===d.id&&(f=M(M({},L.location),d),delete g?.[D])});let p=this.genarateLocationId(f),_={locationId:p,location:f};f.id&&a.push({locationId:p,location:f}),u.push(_);let T=le(M({},g),{[p]:_});this.locations$.next(T)}}),this.updateDocumentLocationMetadata(a),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:Pn.SET_LOCATIONS,payload:{locations:s,options:i}}),this.analyticsService.trackEvent(P.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:s,options:i},!0,this.getUserIdForAnalytics()),u}catch(o){this.loggingService.catch("Error in setLocationImpl: ",o);return}}addLocation({location:t,source:i="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:{appendLocation:!0},methodName:"addLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:Pn.ADD_LOCATION,source:i,payload:{locations:[t],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[t],options:{appendLocation:!0}})}catch(o){this.loggingService.catch("Error in DocService addLocation:",o);return}}removeLocation({location:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[t],methodName:"removeLocation",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:i,methodName:Pn.REMOVE_LOCATION,payload:{locations:[t]}}),t?this.removeLocationsImpl([t],i):i==="external"&&this.removeLocationsImpl(void 0,i)}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}removeLocations({locations:t,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t,methodName:"removeLocations",source:i}}),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:Pn.REMOVE_LOCATIONS,source:i,payload:{locations:t}}),this.removeLocationsImpl(t,i)}catch(o){this.loggingService.catch("Error in removeLocations: ",o)}}removeLocationsImpl(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t},methodName:"removeLocations",message:"System removed locations",source:i},!0,this.getUserIdForAnalytics()),t?t.forEach(o=>{let s=this.genarateLocationId(o);this.getLocation()?.locationId===s&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==o.id))),this.removeCustomLocation(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in removeLocation: ",o)}}unsetLocationIds(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:Pn.UNSET_LOCATION_IDS,source:i,payload:{locationIds:t}}),i==="internal"&&this.analyticsService.trackEvent(P.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:t},methodName:"unsetLocationIds",message:"System unset location ids",source:i},!0,this.getUserIdForAnalytics()),t?.length?t.forEach(o=>{this.getLocation()?.location.id===o&&(this.location$.next(null),i!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==o))),this.removeCustomLocationId(o)}):(this.location$.next(null),this.locations$.next({}),i!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(H.INIT_UPDATE,{event:P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:Pn.REMOVE_LOCATIONS_SUCCESS,source:i,payload:{locationIds:t}}),this.analyticsService.trackEvent(P.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:t},source:i},!0,this.getUserIdForAnalytics())}catch(o){this.loggingService.catch("Error in unsetLocationIds: ",o)}}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(t){try{this.excludedLocationIds$.next([...t])}catch(i){this.loggingService.catch("Error in excludeLocationIds: ",i)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(t){return this.loggingService.catch("Error in getExcludedLocationIds$: ",t),de([])}}updateOrganizationMetadata(t){return I(this,null,function*(){try{!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig());let i=t?.organizationId,o=t?.clientOrganizationId,s=this.documentPaths$.value;if(this.db&&i&&s?.documentId){if(this.organizationMetadata$.value?.[i])return;let c=new ZT;c.apiKey=this.configService?.getApiKey()??"",c.organizationId=i,c.clientOrganizationId=o;let l=this.authService.getUser()?.userId??"",u=o?yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:o}):null;!!(l&&o&&u?.[l]?.organization?.[o]?.errorCode===Rs.PERMISSION_DENIED)?this.loggingService.log(`%c[WB] updateOrganizationMetadata skipped \u2014 user does not have access to organization: ${o}`,"color: orange;"):this.userPermissionService?.hasEditAccess({organizationId:i})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(c)),properties:{organizationId:i,documentId:s?.documentId??""}})),yield this.fetchOrganizationMetadata(t)}}catch(i){this.loggingService.catch("Error in updateOrganizationMetadata: ",i)}})}updateFolderMetadata(){return I(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 t=this.documentPaths$.value;if(!t?.veltFolderId||!t?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:t?.organizationId??"",folderId:t?.veltFolderId??""}}))?.metadata){let o={folderId:this.documentPaths$.value?.folderId,clientOrganizationId:t?.clientOrganizationId,parentFolderId:"root"};if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let s=Rr(this.functions,Ir({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield Md({methodName:"createFolder",data:{type:"createFolder",metadata:o},getSdkProxy:s,userId:this.authService.getUser()?.userId??""})}}}}catch(t){this.loggingService.catch("Error in updateFolderMetadata: ",t)}})}updateDocumentMetadata(){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let i=this.getDocumentIds();i.find(s=>s.documentId===t.documentId)||i.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""});let o=i.map(s=>I(this,null,function*(){let a=new QT;this.clientDocumentMetadataMap?.[s.clientDocumentId]&&(a=M(M({},this.clientDocumentMetadataMap[s.clientDocumentId]),a)),a.apiKey=this.configService?.getApiKey()??"",a.documentId=s.documentId,a.clientDocumentId=s.clientDocumentId,a.organizationId=t.organizationId,a.clientOrganizationId=t.clientOrganizationId,a.pageInfo=Pg(s.clientDocumentId);let c=t?.folderId,l=t?.veltFolderId;a?.pageInfo?.deviceInfo&&delete a?.pageInfo?.deviceInfo;let u=!0,d=this.documentMetadata$.value?.[s.documentId];if(c&&l){let f=this.getDocumentMetadata(s?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}}));f?.clientDocumentId&&!f?.errorCode?f?.folderId&&(f?.folderId!==c||f?.veltFolderId!==l)?(this.loggingService.catch(`Folder id mismatch for document ${s?.clientDocumentId??""}`),u=!1):f?.folderId===c?(c&&(a.folderId=c),l&&(a.veltFolderId=l)):(this.loggingService.catch(`Document ${s?.clientDocumentId??""} is not in the folder ${c??""}`),u=!1):(c&&(a.folderId=c),l&&(a.veltFolderId=l))}if(d){let f={};Object.entries(a).forEach(([g,p])=>{f[g]=p}),Ui(f,d)&&(u=!1)}u&&this.userPermissionService?.hasEditAccess({documentId:s?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(a)),properties:{organizationId:t?.organizationId??"",documentId:s?.documentId??""}}))}));yield Promise.allSettled(o),yield this.fetchDocumentMetadata(i)}}}catch(t){this.loggingService.catch("Error in updateDocumentMetadata: ",t)}})}updateDocumentLocationMetadata(t){return I(this,null,function*(){try{if(this.db&&this.authService.getUser()){let i=this.documentPaths$.value;if(i){let o=this.getDocumentIds();o.find(s=>s.documentId===i.documentId)||o.push({documentId:i.documentId??"",clientDocumentId:i.clientDocumentId??""});for(let s of o){let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??"",field:"metadata"}});a?.errorCode&&(a={});let c=[];for(let l of t){let u=new JT;u.locationId=l?.locationId,u.veltLocationId=$C(l?.location?.id??""),u.location=l?.location,u.pageInfo=Pg(s?.clientDocumentId),u?.pageInfo?.deviceInfo&&delete u?.pageInfo?.deviceInfo;let d=le(M({},a),{[v.FIREBASE_PARTIAL_PATH_LOCATIONS]:le(M({},a[v.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[l?.locationId]:u})});this.commonDbService?.shouldUseFirestore()||c.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{documentId:s?.documentId??"",organizationId:i?.organizationId??""}}));let f=this.locationMetadata$.value;if(f||(f={}),l?.location?.id){let g=f?.[s.documentId],p=g?.[l?.location?.id??""];f&&(g||(f[s.documentId]={}),p||(f[s.documentId][l?.location?.id??""]={}),f[s.documentId][l?.location?.id??""]=le(M({},p),{location:l?.location})),Object.keys(f||{}).length>0&&this.locationMetadata$.next(f)}}yield Promise.allSettled(c)}}}}catch(i){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",i)}})}genarateLocationId(t){try{return t&&typeof t=="object"?Tr(JSON.stringify(Ld(t))):0}catch(i){return this.loggingService.catch("Error in genarateLocationId: ",i),0}}removeCustomLocation(t,i="internal"){try{let o=this.genarateLocationId(t),s=this.locations$.value;s[o]&&(delete s[o],this.locations$.next(M({},s)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(a=>a.id!==t.id)))}catch(o){this.loggingService.catch("Error in DocService removeLocation:",o)}}removeCustomLocationId(t,i="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let o=this.locations$.value;Object.entries(o).forEach(([s,a])=>{a.location.id===t&&(delete o[s],this.locations$.next(M({},o)),i!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(c=>c.id!==t)))})}catch(o){this.loggingService.catch("Error in DocService removeCustomLocationId:",o)}}getLocationByClientLocationId(t){try{let i=this.getLocation()?.location;if(i?.id===t)return i;{let o=this.getLocations();Object.keys(o).forEach(s=>{let a=o[s];a.location?.id===t&&(i=a.location)})}return i}catch(i){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",i);return}}removeLocationIfNotInDom(){try{let t=this.locations$.value,i=document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}]`),o=[];i.forEach(s=>{let a=s.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(a){let c=JSON.parse(a),l=this.genarateLocationId(c);o.push(l)}}),Object.keys(t).forEach(s=>{let a=t[s];o.includes(a.locationId)||delete t[s]}),this.locations$.next(M({},t))}catch(t){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",t)}}getLocations$(){try{return this.locations$.asObservable()}catch(t){return this.loggingService.catch("Error in DocService getLocations$:",t),de({})}}getLocations(){try{return this.locations$.value}catch(t){return this.loggingService.catch("Error in DocService getLocations:",t),{}}}getLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let i=null;if(t?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)?i=t:i=t.closest(`[${v.ATTRIBUTES.VELT_LOCATION}]`),i){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o){let s=JSON.parse(o);return{locationId:this.genarateLocationId(s),location:s}}}return null}catch(i){return this.loggingService.catch("Error in DocService getLocationFromElement:",i),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let t={};return document.querySelectorAll(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(o=>{if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let s=this.getLocationFromElement(o);s?.locationId&&(t[s.locationId]={element:o,location:s})}else if(o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let s=o.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(s){let a=this.getLocationByClientLocationId(s);a?.locationId&&(t[a.locationId]={element:o,location:a});let c={id:s},l=this.genarateLocationId(c);t[s]={element:o,location:{locationId:l,location:c}}}}}),t}catch(t){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",t),{}}}getAdditionLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let i;if(i=t?.closest(`[${v.ATTRIBUTES.VELT_LOCATION}], [${v.ATTRIBUTES.VELT_LOCATION_ID}]`),i){if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION);if(o)return JSON.parse(o)}else if(i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID)){let o=i?.getAttribute(v.ATTRIBUTES.VELT_LOCATION_ID);if(o)return{id:o}}}return null}catch(i){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",i),null}}getAdditionalDocumentIdFromElement(t){try{return t?.closest(`[${v.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(v.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(i){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",i),null}}getDocumentMetadata(t){try{return t?this.documentMetadata$.value?.[t]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(i){return this.loggingService.catch("Error in DocService getDocumentMetadata:",i),null}}getAllDocumentMetadata$(t){return this.getAllDocumentMetadataMap$().pipe(ge(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),rt(Pt))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(ge(t=>t||{}),rt(Pt))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let t=this.documentMetadata$.value||{},i={},o=this.documentPaths$.value?.veltFolderId,s=this.documentPaths$.value?.allDocuments;if(o&&s)Object.values(t).forEach(a=>{a?.documentId&&a?.veltFolderId===o&&(i[a.documentId]=a)});else{let a=this.documentIds$.value;if(a?.length)a.forEach(c=>{let l=t?.[c.documentId];l&&(i[c.documentId]=l)});else if(this.documentPaths$.value?.documentId){let c=t?.[this.documentPaths$.value?.documentId];c&&(i[this.documentPaths$.value?.documentId]=c)}}return Object.values(i)}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",t),[]}}getDocumentMetadata$(t){return this.documentMetadata$.asObservable().pipe(ge(i=>i?.[t??this.documentPaths$.value?.documentId??""]||null),rt(Pt))}setDocumentMetadata(t,i){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let o=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));o[t]=i,this.documentMetadata$.next(o)}catch(o){this.loggingService.catch("Error in DocService setDocumentMetadata:",o)}}setAllDocumentMetadata(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(t)}catch(i){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",i)}}getOrganizationMetadata(t){return this.organizationMetadata$.value?.[t]||null}getOrganizationMetadata$(t){return this.organizationMetadata$.asObservable().pipe(ge(i=>i?.[t]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(ge(t=>t||{}),rt(Pt))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(rt(Pt))}getOrganizationConfig(){return this.organizationConfig$.value}setOrganizationConfig(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setOrganizationConfig","color: green;");let i=JSON.parse(JSON.stringify(t));this.organizationConfig$.next(i)}catch(i){return this.loggingService.catch("Error in DocService setOrganizationConfig:",i),!1}return!0}getMetadataFromType(t,i){try{switch(t){case"area":return;case"comment":return i?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(i.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return i?.commentAnnotationId?this.commentService?.getAnnotationById(i.commentAnnotationId)?.metadata:void 0;default:return}}catch(o){this.loggingService.catch("Error in DocService getMetadataFromType:",o);return}}getDefaultMetadata({clientDocumentId:t,documentId:i}){try{let o=this.documentPaths$.value;if(!o)return;let s=t||o.clientDocumentId,a=i||o.documentId,c=this.getDocumentMetadata(a);if(!c)return;let l=c?.folderId,u=c?.veltFolderId;return M(M({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:s,clientOrganizationId:o.clientOrganizationId,documentId:a,organizationId:o.organizationId},l?{folderId:l}:{}),u?{veltFolderId:u}:{})}catch(o){this.loggingService.catch("Error in DocService getDefaultMetadata:",o);return}}getBaseMetadata(t,i){try{let o,s;i?.element?o=this.getAdditionalDocumentIdFromElement(i.element)||void 0:i?.clientDocumentId&&(o=i.clientDocumentId),o&&(s=this.generateDocumentId(o));let a=this.getMetadataFromType(t,i),c=this.getDefaultMetadata({clientDocumentId:o,documentId:s}),l=a||c||{};return l.sdkVersion=Gr(),l}catch(o){return this.loggingService.catch("Error in DocService getBaseMetadata:",o),{}}}getServerId({documentId:t,organizationId:i}){try{return t&&(t=this.generateDocumentId(t)),i&&(i=this.generateOrganizationId(i)),{documentId:t,organizationId:i}}catch(o){return this.loggingService.catch("Error in DocService getServerId:",o),null}}fetchDocuments(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(t?.folderId){let a=bo(t?.folderId);o.push(Ii("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ii("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchDocuments:",i),[]}})}fetchLocations(t){return I(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 o=[];if(!t?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(t?.folderId){let a=bo(t?.folderId);o.push(Ii("metadata.veltFolderId","==",a))}return t?.documentIds?.length&&!t?.allDocuments&&o.push(Ii("metadata.documentId","in",t?.documentIds?.map(a=>this.generateDocumentId(a)).slice(0,30))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:o,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(i){return this.loggingService.catch("Error in DocService fetchLocations:",i),[]}})}updateDocuments(t){return I(this,null,function*(){try{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t??{}))),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:o,documents:s,folderId:a}=t;if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let c=Ds(o);if(!s||s.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let l=[],u=this.documentMetadata$.value??{};for(let d of s)if(d?.documentId){d.organizationId=c,d.clientOrganizationId=o,d.clientDocumentId=d.documentId;let f=_a(d.documentId);d.documentId=f,d.apiKey=this.configService.getApiKey()??void 0,(a||this.documentPaths$.value?.folderId)&&(d.folderId=a||this.documentPaths$.value?.folderId,d.veltFolderId=bo(a||this.documentPaths$.value?.folderId||""));let g=()=>{if(a&&this.documentPaths$.value?.folderId&&a!==this.documentPaths$.value?.folderId)return;let _=u?.[f];_?u[f]=M(M({},_),d):u[f]=d},p=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:f,organizationId:c,field:"metadata"}});if(p?.errorCode&&(p={}),p&&p.apiKey&&p.folderId&&a&&p.folderId!=d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists with different folderId: ${p.folderId}`);continue}if(p&&p.apiKey&&!p.folderId&&d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists, move this document to folder with REST API`);continue}g(),d&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:d?.documentId??""})&&l.push(this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{organizationId:c,documentId:f}}))}yield Promise.all(l),this.setAllDocumentMetadata(u)}catch(i){return this.loggingService.catch("Error in DocService updateDocuments:",i),[]}})}updateLocations(t){return I(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:o,locations:s,documentIds:a}=t;if((!a||a.length===0)&&(a=this.documentIds$.value.map(d=>d.clientDocumentId)??[],a.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!o&&(o=this.documentPaths$.value?.clientOrganizationId,!o))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!s||s.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let c=a.map(d=>_a(d)),l=[],u=this.locationMetadata$.value;u||(u={}),c.forEach(d=>{s.forEach(f=>{let g=this.location$.value;if(f?.id===g?.location?.id&&this.location$.next({locationId:g?.locationId,location:f}),f?.id){delete f?.metadata;let p=$C(f.id),_=u?.[d],T=_?.[f.id];u&&(_||(u[d]={}),T||(u[d][f.id]={}),u[d][f.id]=le(M({},T),{location:f})),f&&this.commonDbService&&l.push(this.commonDbService.updateData({feature:"locationMetadata",data:JSON.parse(JSON.stringify({location:f})),properties:{organizationId:Ds(o),documentId:d,id:p}}))}})}),yield Promise.all(l),Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(i){return this.loggingService.catch("Error in DocService updateLocations:",i),[]}})}fetchFolders(t){return I(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 o=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};let s=[],a=this.generateOrganizationId(t?.organizationId);if(t?.folderId){let c=bo(t?.folderId);o=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}}),o&&(o=[o]),s=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[Ii("metadata.veltParentFolderId","==",c)],folderId:c,apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}})}else o=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:a,documentId:this.documentPaths$.value?.documentId}});return{data:o,parentFolders:s}}catch(i){return this.loggingService.catch("Error in DocService getFoldersRequest:",i),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(pt(t=>t?this.documentPaths$.pipe(pt(i=>i?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:i.documentId,organizationId:i.organizationId,isCollection:!1}}).pipe(ge(o=>o?.data?.docIamConfig??o?.data),rt((o,s)=>JSON.stringify(o??{})===JSON.stringify(s??{}))):de(null))):de(null)))}getDocumentAccessType(t){try{return t&&t.features&&t.features.all?t.features.all.restricted?Mt.RESTRICTED:Mt.PUBLIC:t&&t.documentAccessType?t.documentAccessType:Mt.PUBLIC}catch(i){return this.loggingService.catch("Error in DocService getDocumentAccessType:",i),Mt.PUBLIC}}changeDocumentAccessType(t){return I(this,null,function*(){try{let i=this.documentPaths$.value;if(i){let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",field:"docIamConfig"}});if(o?.errorCode)return;switch(delete o.documentAccessType,o.features||(o.features={}),o.features.all||(o.features.all={}),t){case Mt.PUBLIC:o.features.all.restricted=!1;break;case Mt.RESTRICTED:o.features.all.restricted=!0,o.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(o)),properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??""}})}}catch(i){this.loggingService.catch("Error in DocService changeDocumentAccessType:",i)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(t){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",t),""}}setUIState(t){try{this.uiState.next(M(M({},this.uiState.value),t))}catch(i){this.loggingService.catch("Error in DocService setUIState:",i)}}getUIState$(){return this.uiState.asObservable()}};e.\u0275fac=function(i){return new(i||e)(C(Ot),C(Dr),C(cc),C(bv),C(Xn),C(me),C(qo),C(Ko),C(lc),C(vt),C(ur),C(di))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var jt=(()=>{let e=class e{constructor(t,i,o,s,a){this.analyticsService=t,this.authService=i,this.coreActionsService=o,this.docService=s,this.loggingService=a,this.resolveOrganizationUsers=new Y(!0),this.resolveFolderUsers=new Y(!0),this.resolveDocumentUsers=new Y(!0),this.unresolvedUsers=new Y([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new mt,this.userDataProvider$=new Y(null),this.anonymousUserDataProvider$=new Y(null),this.userIdByEmailCache={},this.userById$=new Y({}),this.customContactUserById$=new Y({}),this.userByIdCalled$=new Y({}),this.pendingResolutions=new Set,this.getUserById=c=>{try{let l=this.userById$.value?.[c],u=this.customContactUserById$.value?.[c];return u?l?M(M({},l),u):u:l}catch(l){this.loggingService.catch("Error in UsersService getUserById:",l);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.docService.getDocumentPaths$().pipe(Rt(c=>!!c),pt(()=>this.getUnresolvedUsers$().pipe(Rt(c=>c.length>0),Mu(300),Dt(20),pt(c=>{let l=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:l,isCollection:!0,useQuery:!0,firestoreQuery:[rS(Ii("user.userId","in",c.slice(0,20)))]}}).pipe(ge(u=>u?.data),ea(u=>{if(u&&typeof u=="object"){delete u.undefined,delete u.null;let d=Object.values(u??{}),f=d.map(p=>p?.user).filter(p=>!!p&&(!!p.name||!!p.email||!!p.photoUrl));f.length>0&&this.setUserByIds(f);let g=c.filter(p=>!d.some(_=>_.user.userId===p));g.length!==c.length&&this.setUnresolvedUsers(g)}})):de([])})))).subscribe()}catch(c){this.loggingService.catch("Error in UsersService constructor:",c)}}setCommonDbService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=t}catch(i){this.loggingService.catch("Error in UsersService setCommonDbService:",i)}}setContactService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=t}catch(i){this.loggingService.catch("Error in UsersService setContactService:",i)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.pendingResolutions.clear(),this.resolveAttempts.clear()}catch(t){this.loggingService.catch("Error in UsersService ngOnDestroy:",t)}}isResolverForFeatureDisabled(t){let i=this.userDataProvider$.getValue();try{switch(t){case"allOrganizationUsers":return i?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return i?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return i?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(o){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",o),!1}}resolveUsers(u){return I(this,arguments,function*({userIds:t,forceResolve:i,feature:o,organizationId:s,skipUserCheck:a=!1,uniqueId:c,moduleName:l}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let d=!1;if(o&&(d=this.isResolverForFeatureDisabled(o)),d)return{};{let f={},g=[],p={};if(t?.forEach(_=>{let T=this.getUserById(_);T?f[_]=T:this.userByIdCalled$.getValue()[_]?i&&g.push(_):(g.push(_),this.userByIdCalled$.next(le(M({},this.userByIdCalled$.getValue()),{[_]:!0})))}),g.length>0){let _=c||Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:_,moduleName:l,methodName:Ln.RESOLVE_USERS,source:"internal",payload:{userIds:g,organizationId:s,feature:o,forceResolve:i,skipUserCheck:a,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let T={},D=!1,L=new Set;try{let B,w=new Promise((U,A)=>{B=setTimeout(()=>{A(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)}),F=yield Promise.race([this.getUsersFromDB({userIds:g,organizationId:s,skipUserCheck:a}).finally(()=>{clearTimeout(B)}),w]);F==null?D=!0:T=F,this.analyticsService.trackEvent(P.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:g}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:_,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{result:T,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(B){D=!0,this.loggingService.catch("Error in UsersService resolveUsers getUsers:",B,{userIds:g}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:_,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:B,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{let B=this.authService.getProvidedOrCurrentUserId?.();g?.forEach(w=>{if(!T[w]){let F=new Set([...this.getUnresolvedUsers(),w]);if(this.unresolvedUsers.next(Array.from(F)),D&&this.clearUserByIdCalledFlag(w),B&&w===B)return;T[w]={userId:w,name:`User ${w}`},D&&L.add(w)}})}Object.entries(T).forEach(([B,w])=>{w&&(f[B]=T?.[B],L.has(B)||(p[B]=T?.[B]))}),L.size>0&&this.authService.setOptionalPropertiesToUsers(Array.from(L).map(B=>T[B]).filter(Boolean))}return Object.keys(p).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(p)),this.mergeUsersIntoStore(Object.values(p)),Object.keys(p).forEach(_=>{let T=this.getUserById(_);T&&(f[_]=T)})),f}}catch(d){this.loggingService.catch("Error in UsersService resolveUsers:",d);let f=c||Z();return this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:Ln.RESOLVE_USERS,moduleName:l,source:"internal",payload:{error:d,userIds:t,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}clearUserByIdCalledFlag(t){try{let i=this.userByIdCalled$.getValue();if(i?.[t]){let o=M({},i);delete o[t],this.userByIdCalled$.next(o)}}catch(i){this.loggingService.catch("Error in UsersService clearUserByIdCalledFlag:",i)}}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(t){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",t),[]}}setUnresolvedUsers(t){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(t)){let i=JSON.parse(JSON.stringify(t));this.unresolvedUsers.next(i)}}catch(i){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",i)}}getUsersFromDB(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let a=this.userDataProvider$.getValue();if(a){if(a.config?.getConfig?.url){if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),null;let d={organizationId:i,userIds:t},f=yield $t(a.config.getConfig.url,a.config.getConfig.headers,d,!0,a.config.getConfig.credentials);return f.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${f.statusCode}. Message: ${f.message||"Unknown error"}`),null):f.data??{}}let u=yield a.get(t);if(u&&typeof u=="object"&&"success"in u&&"statusCode"in u&&typeof u.success=="boolean"&&typeof u.statusCode=="number"){let d=u;return d.statusCode===200&&d.data?d.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${d.statusCode}`),null)}return u}if(i||(i=this.docService.getOrganizationConfig()?.organizationId),!i)return null;let c=(yield this.getUsersFromDBWithBatching({userIds:t,organizationId:i,skipUserCheck:o}))??[];this.contactService?.setResolvedUsers(c.flat());let l={};return c.forEach(u=>{u.forEach(d=>{d?.user?.userId&&(l[d.user.userId]=d.user)})}),l}catch(a){return this.loggingService.catch("Error in UsersService getUsersFromDB:",a),null}})}getUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,skipUserCheck:o=!1}){try{if(!t?.length)return[];let a=[];for(let u=0;u<t.length;u+=30)a.push(t.slice(u,u+30));let c=a.map((u,d)=>I(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[Ii("user.userId","in",u)],skipUserCheck:o}}))||[]}catch(f){return this.loggingService.catch(`Error in batch ${d+1}:`,f),[]}}));return yield Promise.all(c)}catch(a){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",a),[]}})}getTemporaryUsersFromDBWithBatching(s){return I(this,arguments,function*({userIds:t,organizationId:i,resourceIds:o}){try{if(!t?.length||!o?.length)return[];let a=[];for(let _=0;_<t.length;_+=30)a.push(t.slice(_,_+30));let c=[];for(let _=0;_<o.length;_+=30)c.push(o.slice(_,_+30));let l=[],u=0,d=(_,T)=>I(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:i,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[rS(Ii("userId","in",_),Ii("veltResourceId","in",T))]}}))??[])||[]}catch(D){return this.loggingService.catch(`Error in batch ${u+1}:`,D),[]}});for(let _ of a)for(let T of c)l.push(d(_,T)),u++;return(yield Promise.all(l)).flat().filter((_,T,D)=>T===D.findIndex(L=>L.userId===_.userId&&L.resourceId===_.resourceId))}catch(a){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",a),[]}})}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;"),ti([this.userById$,this.customContactUserById$]).pipe(ge(([t,i])=>this.applyContactOverlay(t,i)),rt(Pt))}catch(t){return this.loggingService.catch("Error in UsersService getUserById$:",t),de({})}}applyContactOverlay(t,i){let o=M({},t??{});return Object.entries(i??{}).forEach(([s,a])=>{o[s]=M(M({},o[s]??{}),a)}),o}setUserByIds(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;"),this.mergeUsersIntoStore(t)}catch(i){this.loggingService.catch("Error in UsersService setUserByIds:",i)}}setContactListUsers(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactListUsers","color: green;");let i={};(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=JSON.parse(JSON.stringify(o)))}),this.customContactUserById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService setContactListUsers:",i)}}getContactListUser(t){try{return this.customContactUserById$.value?.[t]}catch(i){this.loggingService.catch("Error in UsersService getContactListUser:",i);return}}mergeUsersIntoStore(t){try{let i=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));(t??[]).forEach(o=>{let s=o?.userId;s&&(i[s]=M(M({},i?.[s]??{}),o))}),this.userById$.next(i)}catch(i){this.loggingService.catch("Error in UsersService mergeUsersIntoStore:",i)}}setUserDataProvider(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let i=t.config?.getConfig?.url,o="get"in t&&typeof t.get=="function";if(!i&&!o){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(t),t.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),t.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),t.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(i){this.loggingService.catch("Error in UsersService setUserDataProvider:",i)}}setAnonymousUserDataProvider(t){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in t)||typeof t.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(t)}catch(i){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",i)}}resolveUserIdsByEmail(o){return I(this,arguments,function*({emails:t,uniqueId:i}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!t?.length)return{};let s=this.anonymousUserDataProvider$.getValue();if(!s||typeof s.resolveUserIdsByEmail!="function")return{};let a=[...new Set(t.filter(w=>!!w))];if(a.length===0)return{};let c={},l=[];if(a.forEach(w=>{let F=this.userIdByEmailCache[w];F?c[w]=F:l.push(w)}),l.length===0)return c;let u=this.docService.getOrganizationConfig()?.clientOrganizationId||"",d=this.docService.getDocumentPaths()?.clientDocumentId||"",f=this.docService.getDocumentPaths()?.folderId||"",g={organizationId:u,documentId:d,folderId:f,emails:l},p=i||Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:l,organizationId:u,documentId:d,folderId:f}});let _=s.config?.resolveTimeout||this.resolveTimeout,T,D=new Promise((w,F)=>{T=setTimeout(()=>{F(new Error("resolveUserIdsByEmail timeout"))},_)}),L=s.config?.getRetryConfig||{retryCount:0,retryDelay:0},B=I(this,null,function*(){try{let w=yield xt(()=>s.resolveUserIdsByEmail(g),"resolveUserIdsByEmail",L);return w?.statusCode===200&&w?.data?w.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${w?.statusCode}. Message: ${w?.message||"Unknown error"}`),{})}finally{clearTimeout(T)}});try{let w=yield Promise.race([B,D]);return Object.entries(w).forEach(([F,U])=>{U&&(this.userIdByEmailCache[F]=U,c[F]=U,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:U,name:F,email:F},currentUserId:this.authService.getUser()?.userId??""}).catch(A=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",A)}))}),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:w,emails:l}}),c}catch(w){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",w),this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:w,emails:l}}),c}}catch(s){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",s),{}}})}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",t),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(t){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(Ot),C(Dr),C(vt),C(ef),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var uc=class{static getFirestoreProdDbName(e,n){return n?.databaseURL?.includes("snippyly-plugin.firebaseio.com")||n?.databaseURL?.includes("snippyly-plugin-staging.firebaseio.com")?"sfdb":n?.storeDbId??(this.isTestingDb(n?.databaseURL??"")?"sdktest":`apikey${e.toLowerCase()}`)}static isTestingDb(e){try{return e.includes("-test")}catch(n){return j.error("Error in isTestingDb:",n),!1}}};var cS=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.commentAnnotationsResolverService=c,this.attachmentResolverService=l,this.coreActionsService=u,this.endpointsService=J(xo),this.notificationActionTypeMap={[ye.NEWLY_ADDED]:Qt.COMMENT_ANNOTATION_ADD,[ye.ADDED]:Qt.COMMENT_ADD,[ye.UPDATED]:Qt.COMMENT_UPDATE,[ye.DELETED]:Qt.COMMENT_DELETE},this.additionalEventTypeMap={[ye.STATUS_CHANGED]:ar.STATUS_CHANGE,[ye.PRIORITY_CHANGED]:ar.PRIORITY_CHANGE,[ye.ASSIGNED]:ar.ASSIGN,[ye.ACCESS_MODE_CHANGED]:ar.ACCESS_MODE_CHANGE,[ye.CUSTOM_LIST_CHANGED]:ar.CUSTOM_LIST_CHANGE,[ye.APPROVED]:ar.APPROVE,[ye.ACCEPTED]:ar.ACCEPT,[ye.REJECTED]:ar.REJECT,[ye.SUGGESTION_ACCEPTED]:ar.SUGGESTION_ACCEPT,[ye.SUGGESTION_REJECTED]:ar.SUGGESTION_REJECT,[ye.REACTION_ADDED]:ar.REACTION_ADD,[ye.REACTION_DELETED]:ar.REACTION_DELETE,[ye.SUBSCRIBED]:ar.SUBSCRIBE,[ye.UNSUBSCRIBED]:ar.UNSUBSCRIBE}}setNotificationService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",i)}}setUserPermissionService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=t}catch(i){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",i)}}getUserIdsToResolveFromComments(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let i=new Set;for(let o of t){if(o?.from?.userId&&i.add(o?.from?.userId),o?.comments)for(let s of o?.comments){if(s?.from?.userId&&i.add(s?.from?.userId),s?.to)for(let a of s?.to)a?.userId&&i.add(a?.userId);if(s?.taggedUserContacts)for(let a of s?.taggedUserContacts)a?.userId&&i.add(a?.userId)}if(o?.assignedTo?.userId&&i.add(o?.assignedTo?.userId),o?.resolvedByUserId&&i.add(o?.resolvedByUserId),o?.suggestion?.resolvedBy?.userId&&i.add(o?.suggestion?.resolvedBy?.userId),o?.subscribedUsers)for(let s of Object.values(o?.subscribedUsers))s.user.userId&&i.add(s.user.userId);if(o?.unsubscribedUsers)for(let s of Object.values(o?.unsubscribedUsers))s.user.userId&&i.add(s.user.userId)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",i),[]}}mergeCommentWithUser(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.suggestion?.resolvedBy?.userId){let i=this.usersService.getUserById(t?.suggestion?.resolvedBy?.userId);i&&(t.suggestion.resolvedBy=i)}if(t?.comments)for(let i of t?.comments){if(i?.from?.userId){let s=this.usersService.getUserById(i?.from?.userId);s&&(i.from=s)}i?.to&&(i.to=i?.to?.map(s=>{if(s?.userId){let a=this.usersService.getUserById(s?.userId);if(a)return M(M({},s),a)}return s})),i?.taggedUserContacts&&(i.taggedUserContacts=i?.taggedUserContacts?.map(s=>{if(s?.contact){let a=this.usersService.getUserById(s?.contact?.userId);a&&(s.contact=a,(a?.name||a?.email)&&(s.text=`@${a?.name||a?.email}`))}return s}));let o=i?.taggedUserContacts?.filter((s,a,c)=>c.findIndex(l=>l.text===s.text)===a)||[];o.sort((s,a)=>(a.text?.length||0)-(s.text?.length||0)),o.forEach(s=>{if(s?.text){let a=new RegExp(dl(`{{${s.userId}}}`),"g");i.commentText?.includes(`@User ${s.userId}`)&&(a=new RegExp(dl(`@User ${s.userId}`),"g")),i.commentText=i.commentText?.replaceAll(a,s.text),i.commentHtml=i.commentHtml?.replaceAll(a,s.text)}})}if(t?.assignedTo?.userId){let i=this.usersService.getUserById(t?.assignedTo?.userId);i&&(t.assignedTo=i)}if(t?.resolvedByUserId){let i=this.usersService.getUserById(t?.resolvedByUserId);i&&(t.resolvedByUser=i)}if(t?.subscribedUsers)for(let i of Object.values(t?.subscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.subscribedUsers?.id?.user&&(t.subscribedUsers.id.user=o)}if(t?.unsubscribedUsers)for(let i of Object.values(t?.unsubscribedUsers)){let o=this.usersService.getUserById(i.user.userId);o&&t?.unsubscribedUsers?.id?.user&&(t.unsubscribedUsers.id.user=o)}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",i),t}}formatCommentData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),t?.comments?.forEach(i=>{i?.commentText&&i?.commentText?.length>0&&(i.isCommentTextAvailable=!0)}),t?.viewedBy&&delete t.viewedBy,t?.unread!==void 0&&delete t.unread,t?.resolvedByUser!==void 0&&delete t.resolvedByUser,t?.comments&&t.comments.forEach(i=>{i?.reactionAnnotations&&delete i.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.assignedTo?.userId&&(t.assignedTo={userId:t.assignedTo.userId}),t?.subscribedUsers)for(let i of Object.keys(t?.subscribedUsers))t.subscribedUsers[i].user={userId:t?.subscribedUsers[i].user.userId};if(t?.unsubscribedUsers)for(let i of Object.keys(t?.unsubscribedUsers))t.unsubscribedUsers[i].user={userId:t?.unsubscribedUsers[i].user.userId};t?.suggestion?.resolvedBy?.userId&&(t.suggestion.resolvedBy={userId:t.suggestion.resolvedBy.userId})}return t?.comments&&(t.comments=t?.comments?.map(i=>this.formatCommentThreadData(i))),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",i),t}}mergeStrippedDataWithCommentAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.annotationId),o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove();return i&&(t?.comments?.forEach(a=>{let c=i?.comments?.[a?.commentId];if(c){a.commentHtml=c?.commentHtml,a.commentText=c?.commentText;let l=c?.attachments;o&&l&&a.attachments?.forEach(u=>{let d=u?.attachmentId;l?.[d]&&(u.name=l?.[d]?.name,u.url=l?.[d]?.url)})}}),i?.targetTextRange?.text&&t?.targetTextRange&&(t.targetTextRange.text=i?.targetTextRange?.text),s?.length>0&&s.forEach(a=>{i?.[a]&&(t[a]=i[a])})),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",i),t}}mergeLocationWithCommentAnnotations(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let o=t?.location?.id,s=t?.metadata?.documentId;if(!o||!s)return t;let a=i?.[s]?.[o];return a&&(t.location=a?.location),t}catch(o){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",o),t}}isCommentsDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let o=this.commentAnnotationsResolverService.getCommentAnnotationById(i);return o?!Ui(t,o):!0}catch(o){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",o),!0}}stripCommentsFromAnnotationData({comment:t}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!i)return t;let o=this.attachmentResolverService.attachmentDataProviderAvailable(),s=new KT;if(Object.assign(s,t),s.isCommentResolverUsed=i,o){let a=s.attachments?.map(c=>(c.isAttachmentResolverUsed=!0,delete c?.name,delete c?.url,c));s.attachments=a}return delete s?.commentHtml,delete s?.commentText,s}catch(i){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",i),t}}resolveTaggedUserEmails(t){return I(this,null,function*(){try{let i=new Set;if(t.comments?.forEach(o=>{o.taggedUserContacts?.forEach(s=>{s?.contact?.email&&!s?.userId&&i.add(s.contact.email)}),o.to?.forEach(s=>{s?.email&&!s?.userId&&i.add(s.email)})}),i.size>0){let o=Z();this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:Ln.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(i)}});let s=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(i),uniqueId:o});Object.keys(s).length>0&&t.comments?.forEach(a=>{a.taggedUserContacts?.forEach(c=>{if(c?.contact?.email&&!c?.userId){let l=s[c.contact.email];if(l){let u=c.text;if(u){let d=dl(u),f=new RegExp(d,"g");a.commentText&&(a.commentText=a.commentText.replace(f,`{{${l}}}`)),a.commentHtml&&(a.commentHtml=a.commentHtml.replace(f,`{{${l}}}`))}c.userId=l,c.contact.userId=l,delete c.contact?.email,delete c.contact?.visibility,c.text=""}}}),a.to=a.to?.map(c=>{if(c?.email&&!c?.userId){let l=s[c.email];if(l)return delete c?.email,delete c?.visibility,le(M({},c),{userId:l})}return c})})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",i),t}})}stripCommentAnnotationData(s){return I(this,arguments,function*({data:t,actionType:i,commentId:o}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),t=yield this.resolveTaggedUserEmails(t),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let a=this.attachmentResolverService.attachmentDataProviderAvailable(),c=this.commentAnnotationsResolverService.getFieldsToRemove(),l=this.commentAnnotationsResolverService.getAdditionalFields(),u,d;i&&(u=this.notificationActionTypeMap?.[i],d=this.additionalEventTypeMap?.[i]);let f=this.commentAnnotationsResolverService.getAdditionalSaveEvents(),g=Array.isArray(f)?f:[],p={},_=null,T=!1;if(t&&t.annotationId){let w=t.annotationId;if(p[w]=M(M(M(M({annotationId:w,metadata:yn(t.metadata??{}),comments:{}},t?.from&&{from:t?.from}),t?.assignedTo&&{assignedTo:t?.assignedTo}),t?.resolvedByUserId&&{resolvedByUserId:t?.resolvedByUserId}),t?.targetTextRange?.text&&{targetTextRange:{text:t?.targetTextRange?.text}}),delete t?.targetTextRange?.text,c?.length>0&&c.forEach(U=>{t?.[U]&&(p[w][U]=t[U],delete t[U])}),l?.length)for(let U of l)t?.[U]!==void 0&&(p[w][U]=JSON.parse(JSON.stringify(t[U])));t.comments?.forEach(U=>{if(U.commentId){let A;a&&(A={},U.attachments?.forEach(R=>{A[R.attachmentId]={attachmentId:R.attachmentId,name:R.name,url:R.url}})),p[w].comments[U.commentId]=M(M(M(M(M(M({commentId:U.commentId},U?.commentHtml&&{commentHtml:U?.commentHtml}),U?.commentText&&{commentText:U?.commentText}),A&&{attachments:A}),U?.from&&{from:U?.from}),U?.to&&{to:U?.to}),U?.taggedUserContacts&&{taggedUserContacts:U?.taggedUserContacts})}}),T=this.isCommentsDataChanged(p[w],w);let F=new qT;Object.assign(F,t),c?.length>0&&c.forEach(U=>{U in t||delete F[U]}),F.comments=t.comments?.map(U=>this.stripCommentsFromAnnotationData({comment:U}))||[],_=F}let D=_?.comments?.find(w=>w.commentId===o);D?.isDraft&&(u=_?.comments?.length&&_?.comments?.length>0?Qt.COMMENT_ADD:Qt.COMMENT_ANNOTATION_ADD);let L=!!i&&!!this.notificationActionTypeMap?.[i],B=!!d&&!!_&&!L&&!D?.isDraft&&g.includes(d);return B&&(u=d),{strippedData:T&&(i&&this.notificationActionTypeMap?.[i]||D?.isDraft)||B?p:null,originalData:_,eventType:u}}catch(a){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",a),{strippedData:null,originalData:null}}})}formatCommentThreadData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to&&(t.to=t?.to?.map(o=>o?.userId?{userId:o.userId}:o)),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(o=>o?.contact?.userId?le(M({},o),{contact:{userId:o.contact.userId}}):o));let i=t?.taggedUserContacts?.filter((o,s,a)=>a.findIndex(c=>c.text===o.text)===s)||[];i.sort((o,s)=>(s.text?.length||0)-(o.text?.length||0)),i.forEach(o=>{if(o?.text&&o?.contact?.userId){let s=new RegExp(dl(o.text),"g");t.commentText=t.commentText?.replaceAll(s,a=>`{{${o.userId}}}`),t.commentHtml=t.commentHtml?.replaceAll(s,a=>`{{${o.userId}}}`)}}),i.forEach(o=>{o?.text&&o?.contact?.userId&&(o.text="")})}return t}catch(i){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",i),t}}applyNotificationVisibility({annotation:t,extraData:i,deniedForYouUsers:o}){try{let s=jC(t);if(!s)return o??[];i&&typeof i=="object"&&(i.visibility=s);let a=Object.values(i?.annotationData?.subscribedUsers||{}).map(l=>l?.user?.userId).filter(l=>!!l),c=GV(t,a);return[...new Set([...o??[],...c])]}catch(s){return this.loggingService.catch("Error in CommentUtilsService applyNotificationVisibility:",s),o??[]}}getDeniedForYouUsers(i){return I(this,arguments,function*({extraData:t}){try{let o=Object.values(t?.annotationData?.subscribedUsers||{}).map(a=>a.user.userId)??[],s=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&o.length){let a=t?.metadata?.clientDocumentId,c=t?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?t?.annotationData?.context?.access:null,l=[],u=t?.metadata?.folderId;o.forEach(g=>{if(l.push({userId:g,resource:M({id:a,type:ki.DOCUMENT,source:Qn.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:c?{access:c}:void 0},u&&{parentFolderId:u})}),c){let p=JSON.stringify(c);l.push({userId:g,resource:{id:p,type:ki.CONTEXT,source:Qn.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:{access:c}}})}});let d=Z();this.coreActionsService.triggerAction(H.PERMISSION_PROVIDER,{event:P.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:Qn.SET_NOTIFICATIONS,uniqueId:d,timestamp:new Date().getTime(),source:"internal",payload:{requests:l}});let f=yield this.userPermissionService?.onResourceAccessRequired({requests:l,uniqueId:d,methodName:Qn.SET_NOTIFICATIONS});f?.success&&f?.data?.length&&f.data.forEach(g=>{g.hasAccess||s.push(g.userId)})}return s}catch(o){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",o),[]}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let l=iI(this.authService.getFirebaseConfig()?.firebaseOptions),u=Rr(this.functions,Ir({url:this.endpointsService.getSetEncryptedDataUrl(l),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),d={from:t?.from,visibilityConfig:t?.visibilityConfig,context:{accessFields:t?.context?.accessFields}};if(o){o=this.notificationService?.processNotificationData(o),o.annotationData=t;let T=o?.targetAnnotationData?.commentId;if(T){let D=t?.comments?.find(L=>L?.commentId===T);D&&(o.targetAnnotationData=D)}try{let D=yield this.stripCommentAnnotationData({data:o.annotationData,actionType:o?.actionType??ye.NEWLY_ADDED});D?.originalData&&(o.annotationData=this.formatCommentData(D.originalData)),o?.targetAnnotationData&&(o.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:o.targetAnnotationData})))}catch(D){this.loggingService.warn("Error in CommentUtilsService handleCommentEncryption:",D)}}let f=uc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=yield this.getDeniedForYouUsers({extraData:o});g=this.applyNotificationVisibility({annotation:d,extraData:o,deniedForYouUsers:g});let p={path:i??"",data:t??{},dbId:f??"",notificationData:o||void 0,notificationURL:this.endpointsService.getNotificationsDbUrl(),feature:"comment",eventType:s??"PATCH",sdkVersion:Gr(),deniedForYouUsers:g,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),isCrossOrganizationEnabled:this.notificationService?.getCrossOrganizationConfig()?.enabled,metadata:a},_=yield hl(p,this.authService.getUser()?.userId??"");yield u({veltData:_})}catch(l){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",l)}})}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(Dr),C(ur),C(Xn),C(qo),C(Zh),C(vt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var lS=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new Y(null),this.activityById$=new Y({}),this.fieldsToRemove=[],this.getActivityById=s=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in ActivityResolverService getActivityById:",a);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.saveRetryConfig&&(this.retrySaveConfig=s.config.saveRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig),s.config?.fieldsToRemove&&(this.fieldsToRemove=s.config.fieldsToRemove))})}catch(s){this.loggingService.catch("Error in ActivityResolverService constructor:",s)}}getProvider(){try{let t=this.activityDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ActivityResolverService getProvider:",t);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(t){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",t)}}resolveActivities(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let L=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:t}}),f(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=[...new Set(t.activityIds||[])],T=le(M({},t),{activityIds:_});I(this,null,function*(){try{if(_.length>0||t.documentIds?.length){let L=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{request:T}});let B=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,T,!0,g.config.getConfig.credentials):g?.get?.(T)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(w=>c?{}:(u(),w&&w.statusCode!==200?(this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:w,request:T}}),this.loggingService.catch(w?.message??"Error in ActivityResolverService resolveActivities:"),{}):w?.data)).catch(w=>{throw u(),w});try{p=(yield B)||{},this.analyticsService.trackEvent(P.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:_});let w={};Object.entries(p).forEach(([F,U])=>{let A=this.activityById$.value?.[F];A?A&&JSON.stringify(A)!==JSON.stringify(U)&&(w[F]=U):w[F]=U}),Object.keys(w).length>0&&this.activityById$.next(M(M({},this.activityById$.getValue()),w)),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{result:w,request:T}}),d(w)}catch(w){let F=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:F,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:w,request:T}}),c||f(w),d(p)}}else u(),d({})}catch(L){u();let B=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:B,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:L,request:T}}),f(L)}})})}catch(a){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:cr.RESOLVE_ACTIVITIES,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}saveActivity(t,i){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let o=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let s=i||Z();this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{request:t}});let a=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=M(M({},a),t.activity);let c=yield xt(()=>{if(o?.config?.saveConfig?.url){let l={activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata};return $t(o.config.saveConfig.url,o.config.saveConfig.headers,l,!1,o.config.saveConfig.credentials)}return o?.save?.({activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return c&&c.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=a),this.loggingService.catch(c?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{error:c,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(t.activity),event:t.event}),this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in ActivityResolverService saveActivity:",o);let s=i||Z();return this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:cr.SAVE_ACTIVITY,source:"internal",payload:{error:o,request:t}}),{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()):de(void 0)}catch(t){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",t),de(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",t),this.fieldsToRemove}}setActivityDataProvider(t){try{if(t){this.loggingService.log("Setting activity data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.activityDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",i)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var uS=(()=>{let e=class e{constructor(t,i,o,s,a,c){this.loggingService=t,this.usersService=i,this.authService=o,this.functions=s,this.configService=a,this.reactionAnnotationsResolverService=c,this.endpointsService=J(xo)}getUserIdsToResolveFromReactions(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o?.from?.userId),o?.reactions?.length)for(let s of o?.reactions)s?.from?.userId&&i.add(s?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{let a=iI(this.authService.getFirebaseConfig()?.firebaseOptions),c=Rr(this.functions,Ir({url:this.endpointsService.getSetEncryptedDataUrl(a),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),l=uc.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),u=this.authService.getUser()?.userId??"",d={path:i??"",data:t??{},dbId:l??"",feature:"reaction",eventType:o??"PATCH",sdkVersion:Gr()},f=yield hl(d,u);yield c({veltData:f})}catch(a){this.loggingService.catch("Error in handleReactionEncryption:",a)}})}mergeReactionWithUser(t){try{if(this.usersService.userDataProviderAvailable()){if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}if(t?.reactions?.length){for(let i of t?.reactions)if(i?.from?.userId){let o=this.usersService.getUserById(i?.from?.userId);o&&(i.from=o)}}}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",i),t}}formatReactionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t.reactions=t?.reactions?.map(i=>(this.usersService.userDataProviderAvailable()&&i?.from?.userId&&(i.from={userId:i.from.userId}),i)),t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",i),t}}isReactionDataChanged(t,i){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let o=this.reactionAnnotationsResolverService.getReactionAnnotationById(i);return o?!Ui(t,o):!0}catch(o){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",o),!0}}stripReactionAnnotationData(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let i={},o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(t&&t.annotationId){let s=t.annotationId;if(i[s]=M({annotationId:s,metadata:yn(t.metadata??{}),icon:t.icon},t?.from&&{from:t?.from}),o?.length>0)for(let c of o)t?.[c]!==void 0&&(i[s][c]=t[c],delete t[c]);if(!this.isReactionDataChanged(i[s],s))return{strippedData:null,originalData:t};delete t?.icon,t.isReactionResolverUsed=!0}return{strippedData:i,originalData:t}}catch(i){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",i),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return t;let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(t?.annotationId);if(i){i.icon&&(t.icon=i.icon);let o=this.reactionAnnotationsResolverService.getFieldsToRemove();if(o?.length>0)for(let s of o)i?.[s]!==void 0&&(t[s]=i[s])}return t}catch(i){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(Dr),C(ur),C(Xn),C(Ko))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var dS=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d){this.loggingService=t,this.usersService=i,this.commentUtilsService=o,this.reactionUtilsService=s,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=c,this.recorderAnnotationsResolverService=l,this.activityResolverService=u,this.serviceBook=d}getActivityDisplayMessage(t){try{switch(t.featureType){case"comment":return this.getCommentDisplayMessage(t);case"recorder":return this.getRecorderDisplayMessage(t);case"reaction":return this.getReactionDisplayMessage(t);case"crdt":return this.getCrdtDisplayMessage(t);case"custom":return t.displayMessageTemplate&&t.displayMessageTemplateData?this.resolveTemplate(t.displayMessageTemplate,t.displayMessageTemplateData):"";default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",i),""}}resolveTemplate(t,i){try{return t.replace(/\{\{([\w.]+)\}\}/g,(o,s)=>{let a=s.split(".").reduce((c,l)=>{if(c!=null&&typeof c=="object")return c[l]},i);return a!=null?String(a):""})}catch(o){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",o),t}}buildActivityDataFromExtraData(t){try{let{feature:i,extraData:o}=t;if(!o?.actionType)return null;switch(i){case"comment":return this.buildCommentActivityData({commentAnnotation:o.annotationData,targetComment:o.targetAnnotationData,actionType:o.actionType,otherFields:o});case"recorder":return this.buildRecorderActivityData(o);case"reaction":return this.buildReactionActivityData(o);default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",i),null}}stripActivityPII(t){return I(this,null,function*(){try{let i=JSON.parse(JSON.stringify(t));if(delete i.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:i};i.actionUser?.userId&&(i.actionUser={userId:i.actionUser.userId}),i.changes&&this.stripUsersFromChanges(i.changes),i.displayMessageTemplateData&&this.stripUsersFromTemplateData(i.displayMessageTemplateData);let o=this.extractCommentChangesForResolver(i),s=this.extractFeatureEntityDataForResolver(i);yield this.stripFeatureSpecificPII(i);let a=this.extractActivityResolverData(i);return o&&(a?a.changes=M(M({},a.changes),o.changes):a=o),s&&(a?(s.entityData!==void 0&&(a.entityData=s.entityData),s.entityTargetData!==void 0&&(a.entityTargetData=s.entityTargetData)):a=s),a&&(i.isActivityResolverUsed=!0),{strippedActivity:i,activityResolverData:a}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",i),{strippedActivity:t}}})}mergeActivityWithUser(t){try{if(!this.usersService.userDataProviderAvailable())return t;if(t=JSON.parse(JSON.stringify(t)),t.actionUser?.userId){let i=this.usersService.getUserById(t.actionUser.userId);i&&(t.actionUser=i)}return t.changes&&this.rehydrateUsersInChanges(t.changes),t.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(t.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(t),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",i),t}}mergeActivityWithFeatureData(t){try{switch(t.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(t);case"reaction":return this.mergeActivityWithReactionData(t);case"recorder":return this.mergeActivityWithRecorderData(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",i),t}}getUserIdsToResolveFromActivities(t){try{let i=new Set;for(let o of t){if(o.actionUser?.userId&&i.add(o.actionUser.userId),o.changes)for(let s of Object.values(o.changes))s&&(this.extractUserIdFromValue(s.from,i),this.extractUserIdFromValue(s.to,i));if(o.displayMessageTemplateData)for(let s of Object.values(o.displayMessageTemplateData))this.extractUserIdFromValue(s,i);this.extractFeatureSpecificUserIds(o,i)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",i),[]}}getEntityIdsToResolveFromActivities(t,i){try{let o=new Set;for(let s of t)if(!(i&&s.featureType!==i))switch(s.featureType){case"comment":case"reaction":case"recorder":s.targetEntityId&&o.add(s.targetEntityId);break}return Array.from(o)}catch(o){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",o),[]}}stripFeatureSpecificPII(t){return I(this,null,function*(){try{switch(t.featureType){case"comment":yield this.stripCommentPII(t);break;case"reaction":this.stripReactionPII(t);break;case"recorder":this.stripRecorderPII(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",i)}})}extractActivityResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let i={id:t.id},o=!1,s=this.activityResolverService.getFieldsToRemove();for(let a of s)a in t&&t[a]!==void 0&&(i[a]=t[a],delete t[a],o=!0);return t.metadata&&(i.metadata=yn(t.metadata)),o?i:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",i);return}}extractCommentChangesForResolver(t){try{return!this.activityResolverService.activityDataProviderAvailable()||t.featureType!=="comment"||!t.changes?.commentText?void 0:{id:t.id,changes:{commentText:t.changes.commentText},metadata:t.metadata?yn(t.metadata):void 0}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",i);return}}extractFeatureEntityDataForResolver(t){try{if(!this.activityResolverService.activityDataProviderAvailable()||!t.entityData)return;let i=t.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),o=t.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!i&&!o)return;let s={id:t.id,metadata:t.metadata?yn(t.metadata):void 0},a=JSON.parse(JSON.stringify(t.entityData));if(i){let c=this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:a});if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}if(o){let c=this.reactionUtilsService.stripReactionAnnotationData(a);if(c?.strippedData){let l=Object.keys(c.strippedData)[0];l&&(s.entityData=c.strippedData[l])}}return s.entityData?s:void 0}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",i);return}}mergeActivityWithResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return t;let i=this.activityResolverService.getActivityById(t.id);if(!i)return t;i.changes&&(t.changes||(t.changes={}),Object.assign(t.changes,i.changes)),i.entityData!==void 0&&(t.entityData=i.entityData),i.entityTargetData!==void 0&&(t.entityTargetData=i.entityTargetData),i.displayMessageTemplateData&&(t.displayMessageTemplateData||(t.displayMessageTemplateData={}),Object.assign(t.displayMessageTemplateData,i.displayMessageTemplateData));let o=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[s,a]of Object.entries(i))!o.has(s)&&a!==void 0&&(t[s]=a);return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",i),t}}rehydrateFeatureSpecificUserData(t){try{switch(t.featureType){case"comment":this.rehydrateCommentUserData(t);break;case"reaction":this.rehydrateReactionUserData(t);break;case"recorder":this.rehydrateRecorderUserData(t);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",i)}}getCommentDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Me.ANNOTATION_ADD:return`${i} added a comment`;case Me.COMMENT_ADD:return`${i} replied to a comment`;case Me.COMMENT_UPDATE:return`${i} edited a comment`;case Me.COMMENT_DELETE:return`${i} deleted a comment`;case Me.ANNOTATION_DELETE:return`${i} deleted a comment thread`;case Me.STATUS_CHANGE:{let o=t.changes?.status,s=o?.from?.name,a=o?.to?.name;return s&&a?`${i} changed status from ${s} to ${a}`:`${i} changed the status`}case Me.PRIORITY_CHANGE:{let o=t.changes?.priority,s=o?.to;if(!s)return`${i} removed the priority`;let a=typeof s=="object"?s?.name:String(s),c=o?.from,l=c&&typeof c=="object"?c?.name:c?String(c):null;return l&&a?`${i} changed priority from ${l} to ${a}`:`${i} changed priority to ${a}`}case Me.ASSIGN:{let s=t.changes?.assignedTo?.to;return s&&typeof s=="object"&&s.name?`${i} assigned to ${s.name}`:`${i} assigned the comment`}case Me.ACCESS_MODE_CHANGE:{let s=t.changes?.accessMode?.to;return s?`${i} changed access to ${s}`:`${i} changed the access mode`}case Me.CUSTOM_LIST_CHANGE:return`${i} changed the custom list`;case Me.APPROVE:return`${i} approved the comment`;case Me.ACCEPT:case Me.SUGGESTION_ACCEPT:return`${i} accepted a suggestion`;case Me.REJECT:case Me.SUGGESTION_REJECT:return`${i} rejected a suggestion`;case Me.REACTION_ADD:return`${i} reacted to a comment`;case Me.REACTION_DELETE:return`${i} removed a reaction`;case Me.SUBSCRIBE:return`${i} subscribed to the thread`;case Me.UNSUBSCRIBE:return`${i} unsubscribed from the thread`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",i),""}}getRecorderDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Cg.RECORDING_ADD:return`${i} added a recording`;case Cg.RECORDING_DELETE:return`${i} deleted a recording`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",i),""}}getReactionDisplayMessage(t){try{let i=t.actionUser?.name??"Someone";switch(t.actionType){case Ng.REACTION_ADD:return`${i} added a reaction`;case Ng.REACTION_DELETE:return`${i} removed a reaction`;default:return""}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",i),""}}getCrdtDisplayMessage(t){try{let i=t.actionUser?.name??"Someone",s=t.entityData?.editCount??0,a=t.targetEntityId??"unknown";return`${i} made ${s} edit${s!==1?"s":""} to editor ${a}`}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",i),""}}stripCommentPII(t){return I(this,null,function*(){try{let i=yield this.commentUtilsService.stripCommentAnnotationData({data:t.entityData,actionType:t.eventType??ye.NEWLY_ADDED});i?.originalData&&(t.entityData=this.commentUtilsService.formatCommentData(i.originalData)),t.entityTargetData&&(t.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:t.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()&&t.changes?.commentText&&delete t.changes.commentText}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",i)}})}rehydrateCommentUserData(t){try{t.entityData&&this.commentUtilsService.mergeCommentWithUser(t.entityData),t.entityTargetData&&(this.rehydrateUserInObject(t.entityTargetData,"from"),this.rehydrateUsersInArray(t.entityTargetData,"to"),this.rehydrateUsersInArray(t.entityTargetData,"taggedUserContacts"))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",i)}}stripReactionPII(t){try{if(!t.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(t.entityData),t.entityData=this.reactionUtilsService.formatReactionData(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",i)}}rehydrateReactionUserData(t){try{if(!t.entityData)return;this.reactionUtilsService.mergeReactionWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",i)}}stripRecorderPII(t){try{if(!t.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:t.entityData});return}let i=t.entityData;if(this.usersService.userDataProviderAvailable()){i.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId});let o=i.transcription;o?.from&&typeof o.from=="object"&&"userId"in o.from&&(o.from={userId:o.from.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",i)}}rehydrateRecorderUserData(t){try{if(!t.entityData)return;this.serviceBook.get(ui)?.mergeRecorderWithUser(t.entityData)}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",i)}}mergeActivityWithCommentAnnotationData(t){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t.targetEntityId);if(!i)return t;let o=t.entityData?.comments;if(Array.isArray(o))for(let s of o){let a=s?.commentId;if(a==null)continue;let c=i.comments?.[String(a)];c&&(c.commentText&&(s.commentText=c.commentText),c.commentHtml&&(s.commentHtml=c.commentHtml))}if(t.targetSubEntityId&&t.entityTargetData){let s=i.comments?.[t.targetSubEntityId];if(s){let a=t.entityTargetData;s.commentText&&(a.commentText=s.commentText),s.commentHtml&&(a.commentHtml=s.commentHtml)}}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",i),t}}mergeActivityWithReactionData(t){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",i),t}}mergeActivityWithRecorderData(t){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.serviceBook.get(ui)?.mergeStrippedDataWithRecorderAnnotation(t.entityData),t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",i),t}}buildCommentActivityData(t){try{let{commentAnnotation:i,targetComment:o,actionType:s,otherFields:a}=t,c=i,l=o,u=s===ye.DELETED&&a?.isAnnotationDelete?Me.ANNOTATION_DELETE:this.mapCommentStatusToActionType(s);if(!u)return null;let d=c?.annotationId;if(!d)return null;let f=l?.commentId,g=this.buildCommentChanges(s,l,a);return{featureType:"comment",actionType:u,targetEntityId:d,eventType:s,targetSubEntityId:f??null,changes:Object.keys(g).length>0?g:void 0,entityData:i,entityTargetData:o??void 0}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",i),null}}mapCommentStatusToActionType(t){try{switch(t){case ye.NEWLY_ADDED:return Me.ANNOTATION_ADD;case ye.ADDED:return Me.COMMENT_ADD;case ye.UPDATED:return Me.COMMENT_UPDATE;case ye.DELETED:return Me.COMMENT_DELETE;case ye.STATUS_CHANGED:return Me.STATUS_CHANGE;case ye.PRIORITY_CHANGED:return Me.PRIORITY_CHANGE;case ye.ASSIGNED:return Me.ASSIGN;case ye.ACCESS_MODE_CHANGED:return Me.ACCESS_MODE_CHANGE;case ye.CUSTOM_LIST_CHANGED:return Me.CUSTOM_LIST_CHANGE;case ye.APPROVED:return Me.APPROVE;case ye.ACCEPTED:return Me.ACCEPT;case ye.REJECTED:return Me.REJECT;case ye.SUGGESTION_ACCEPTED:return Me.SUGGESTION_ACCEPT;case ye.SUGGESTION_REJECTED:return Me.SUGGESTION_REJECT;case ye.REACTION_ADDED:return Me.REACTION_ADD;case ye.REACTION_DELETED:return Me.REACTION_DELETE;case ye.SUBSCRIBED:return Me.SUBSCRIBE;case ye.UNSUBSCRIBED:return Me.UNSUBSCRIBE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",i),null}}buildRecorderActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapRecorderStatusToActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"recorder",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",i),null}}mapRecorderStatusToActionType(t){try{switch(t){case MT.ADDED:return Cg.RECORDING_ADD;case MT.DELETED:return Cg.RECORDING_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",i),null}}buildReactionActivityData(t){try{let i=t.annotationData,o=t.actionType,s=this.mapReactionActionType(o);if(!s)return null;let a=i?.annotationId;return a?{featureType:"reaction",actionType:s,targetEntityId:a,entityData:i}:null}catch(i){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",i),null}}mapReactionActionType(t){try{switch(t){case"add":return Ng.REACTION_ADD;case"delete":return Ng.REACTION_DELETE;default:return null}}catch(i){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",i),null}}buildCommentChanges(t,i,o){try{let s={};switch(t){case ye.NEWLY_ADDED:case ye.ADDED:s.commentText={from:null,to:i?.commentText??null};break;case ye.UPDATED:s.commentText={from:o?.oldCommentText??null,to:i?.commentText??null};break;case ye.DELETED:s.commentText={from:i?.commentText??null,to:null};break;case ye.STATUS_CHANGED:s.status={from:o?.oldStatus??null,to:o?.newStatus??null};break;case ye.PRIORITY_CHANGED:s.priority={from:o?.oldPriority??null,to:o?.newPriority??null};break;case ye.ASSIGNED:{s.assignedTo={from:o?.oldAssignedTo??null,to:o?.newAssignedTo??null};break}case ye.ACCESS_MODE_CHANGED:s.accessMode={from:o?.oldAccessMode??null,to:o?.newAccessMode??null};break;case ye.CUSTOM_LIST_CHANGED:s.customList={from:o?.oldCustomList??null,to:o?.newCustomList??null};break}return s}catch(s){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",s),{}}}extractFeatureSpecificUserIds(t,i){try{switch(t.featureType){case"comment":this.extractCommentActivityUserIds(t,i);break;case"reaction":this.extractReactionActivityUserIds(t,i);break;case"recorder":this.extractRecorderActivityUserIds(t,i);break}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",o)}}extractCommentActivityUserIds(t,i){try{if(t.entityData){let o=this.commentUtilsService.getUserIdsToResolveFromComments([t.entityData]);for(let s of o)i.add(s)}if(t.entityTargetData){let o=t.entityTargetData;if(this.extractUserIdFromValue(o.from,i),Array.isArray(o.to))for(let s of o.to)this.extractUserIdFromValue(s,i);if(Array.isArray(o.taggedUserContacts))for(let s of o.taggedUserContacts)this.extractUserIdFromValue(s,i)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",o)}}extractReactionActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.reactionUtilsService.getUserIdsToResolveFromReactions([t.entityData]);for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",o)}}extractRecorderActivityUserIds(t,i){try{if(!t.entityData)return;let o=this.serviceBook.get(ui)?.getUserIdsToResolveFromRecorders([t.entityData])??[];for(let s of o)i.add(s)}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",o)}}stripUsersFromChanges(t){try{for(let i of Object.keys(t)){let o=t[i];o&&(o.from=this.stripUserIfPresent(o.from),o.to=this.stripUserIfPresent(o.to))}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",i)}}stripUserIfPresent(t){try{return t&&typeof t=="object"&&"userId"in t?{userId:t.userId}:t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",i),t}}stripUsersFromTemplateData(t){try{for(let i of Object.keys(t)){let o=t[i];o&&typeof o=="object"&&"userId"in o&&(t[i]={userId:o.userId})}}catch(i){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",i)}}rehydrateUsersInChanges(t){try{for(let i of Object.values(t))i&&(i.from=this.rehydrateIfUser(i.from),i.to=this.rehydrateIfUser(i.to))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",i)}}rehydrateIfUser(t){try{if(t&&typeof t=="object"&&"userId"in t){let i=t.userId;return this.usersService.getUserById(i)??t}return t}catch(i){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",i),t}}rehydrateUsersInTemplateData(t){try{for(let i of Object.keys(t))t[i]=this.rehydrateIfUser(t[i])}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",i)}}rehydrateUserInObject(t,i){try{let o=t[i];if(o&&typeof o=="object"&&"userId"in o){let s=o.userId,a=this.usersService.getUserById(s);a&&(t[i]=a)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",o)}}rehydrateUsersInArray(t,i){try{let o=t[i];Array.isArray(o)&&(t[i]=o.map(s=>this.rehydrateIfUser(s)))}catch(o){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",o)}}extractUserIdFromValue(t,i){try{if(t&&typeof t=="object"&&"userId"in t){let o=t.userId;typeof o=="string"&&i.add(o)}}catch(o){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",o)}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt),C(cS),C(uS),C(qo),C(Ko),C(lc),C(lS),C(di))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var hS=class{constructor({apiKey:e,documentId:n,organizationId:t,folderId:i,veltFolderId:o,clientDocumentId:s,clientOrganizationId:a}){this.paths={},this.apiKey=e,this.documentId=n,this.organizationId=t,this.folderId=i,this.veltFolderId=o,this.clientDocumentId=s,this.clientOrganizationId=a,s&&(this.documentId=_a(s)),a&&(this.organizationId=Ds(a)),i&&(this.folderId=i,this.veltFolderId=bo(i)),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 e=`${this.apiKey}`;this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${e}/${v.FIREBASE_PARTIAL_PATH_CONTACTS}/${v.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${v.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${e}/${v.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${v.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${v.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${e}/${v.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${v.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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var vz=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.usersService=o}getUserIdsToResolveFromLiveStateCustom(t){try{let i=new Set;return t?.updatedBy&&i.add(t?.updatedBy?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",i),[]}}mergeLiveStateCustomWithUser(t){try{if(t?.updatedBy?.userId){let i=this.usersService.getUserById(t?.updatedBy?.userId);i&&(t.updatedBy=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",i),t}}formatLiveStateCustomData(t){try{return this.usersService.userDataProviderAvailable()&&t?.updatedBy&&(t.updatedBy={userId:t.updatedBy.userId}),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",i),t}}getUserIdsToResolveFromLiveStateCustoms(t){try{let i=new Set;for(let o of t)o?.updatedBy?.userId&&i.add(o?.updatedBy?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",i),[]}}getUserIdsToResolveFromLiveStates(t){try{let i=new Set;return t?.default?.singleEditorMode?.editor?.userId&&i.add(t?.default?.singleEditorMode?.editor?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",i),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(t){try{let i=new Set;return t?.editor?.userId&&i.add(t?.editor?.userId),t?.requestEditorAccess?.user?.userId&&i.add(t?.requestEditorAccess?.user?.userId),Array.from(i)}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",i),[]}}mergeLiveStateWithUser(t){try{if(t?.default?.singleEditorMode?.editor?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.editor?.userId);i&&(t.default.singleEditorMode.editor=i)}if(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);i&&(t.default.singleEditorMode.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",i),t}}mergeSingleEditorLiveStateDataWithUser(t){try{if(t?.editor?.userId){let i=this.usersService.getUserById(t?.editor?.userId);i&&(t.editor=i)}if(t?.requestEditorAccess?.user?.userId){let i=this.usersService.getUserById(t?.requestEditorAccess?.user?.userId);i&&(t.requestEditorAccess.user=i)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",i),t}}resolveAndMergeSingleEditorLiveStateDataWithUser(t){return I(this,null,function*(){try{let i=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:t}});if(i.length){let o=Z(),s=Ea.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:Ln.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:s,source:"internal",payload:{userIds:i}}),yield this.usersService.resolveUsers({userIds:i,uniqueId:o,moduleName:s}),this.mergeSingleEditorLiveStateDataWithUser(t)}return t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",i),t}})}formatLiveStateSingleEditorModeData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.editor?.userId&&(t.editor={userId:t.editor.userId}),t?.requestEditorAccess?.user?.userId&&(t.requestEditorAccess.user={userId:t.requestEditorAccess.user.userId})),t}catch(i){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",i),t}}mergeLiveStateCustomsWithUsers(t){try{for(let i of t)if(i?.updatedBy?.userId){let o=this.usersService.getUserById(i?.updatedBy?.userId);o&&(i.updatedBy=o)}return t}catch(i){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var fS=(()=>{let e=class e{constructor(t,i,o){this.coreActionsService=t,this.loggingService=i,this.analyticsService=o,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new Y(null),this.notificationById$=new Y({}),this.inFlightRequests=new Map,this.getNotificationById=s=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[s]:void 0}catch(a){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",a);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(s=>{s&&(s.config?.resolveTimeout&&(this.resolveTimeout=s.config.resolveTimeout),s.config?.deleteRetryConfig&&(this.retryDeleteConfig=s.config.deleteRetryConfig),s.config?.getRetryConfig&&(this.retryGetConfig=s.config.getRetryConfig))})}catch(s){this.loggingService.catch("Error in NotificationResolverService constructor:",s)}}getProvider(){try{let t=this.notificationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in NotificationResolverService getProvider:",t);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(t){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",t)}}resolveNotifications(s){return I(this,arguments,function*({request:t,uniqueId:i,moduleName:o}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let a,c=!1,l=!1,u=()=>{a&&(clearTimeout(a),a=void 0,l=!0)};return new Promise((d,f)=>{a=setTimeout(()=>{if(!l){c=!0,u();let U=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:t}}),f(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return u(),d({});let p={},_=this.notificationById$.getValue()||{},T=[...new Set(t.notificationIds||[])],D=[],L=[],B=[];for(let U of T)_[U]||(this.inFlightRequests.has(U)?(D.push(this.inFlightRequests.get(U)),L.push(U)):B.push(U));let w=le(M({},t),{notificationIds:B});I(this,null,function*(){try{if(D.length>0&&(yield Promise.allSettled(D)),B.length>0){let U=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{request:w}});let A,R=new Promise(b=>{A=b});for(let b of B)this.inFlightRequests.set(b,R.then(x=>x?.[b]));let N=xt(()=>g?.config?.getConfig?.url?$t(g.config.getConfig.url,g.config.getConfig.headers,w,!0,g.config.getConfig.credentials):g?.get?.(w)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(b=>c?{}:(u(),b&&b.statusCode!==200?(this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:b,request:w}}),this.loggingService.catch(b?.message??"Error in NotificationResolverService resolveNotifications:"),{}):b?.data)).catch(b=>{throw u(),b});try{p=(yield N)||{},A(p);for(let x of B)this.inFlightRequests.delete(x);this.analyticsService.trackEvent(P.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:B});let b={};Object.entries(p).forEach(([x,k])=>{let O=this.notificationById$.value?.[x];O?O&&JSON.stringify(O)!==JSON.stringify(k)&&(b[x]=k):b[x]=k}),Object.keys(b).length>0&&this.notificationById$.next(M(M({},this.notificationById$.getValue()),b)),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:U,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{result:b,request:w}}),d(b)}catch(b){A({});for(let k of B)this.inFlightRequests.delete(k);let x=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:x,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:b,request:w}}),c||f(b),d(p)}}else u(),d({})}catch(U){u();let A=i||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:A,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:U,request:w}}),f(U)}})})}catch(a){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",a);let c=i||Z();return this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:c,methodName:Mn.RESOLVE_NOTIFICATIONS,moduleName:o,source:"internal",payload:{error:a,request:t}}),{}}})}deleteNotification(t,i,o){return I(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let s=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let a=o||Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:t,organizationId:i}});let c=this.notificationById$.getValue(),l=M({},c);delete l?.[t],this.notificationById$._value=l;let u={notificationId:t,organizationId:i},d=yield xt(()=>s?.config?.deleteConfig?.url?$t(s.config.deleteConfig.url,s.config.deleteConfig.headers,u,!1,s.config.deleteConfig.credentials):s?.delete?.(u)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return d&&d.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=c),this.loggingService.catch(d?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{error:d,notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(P.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:t}),this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:t,organizationId:i}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(s){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",s);let a=o||Z();return this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:a,methodName:Mn.DELETE_NOTIFICATION,source:"internal",payload:{error:s,notificationId:t,organizationId:i}}),{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()):de(void 0)}catch(t){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",t),de(void 0)}}setNotificationDataProvider(t){try{if(t){this.loggingService.log("Setting notification data provider");let i=t.config,o=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],s=[];if(o.forEach(({method:a,configKey:c})=>{let l=i?.[c]?.url,u=a in t&&typeof t[a]=="function";!l&&!u&&s.push(a)}),s.length>0){let a=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${s.join(", ")}.`;this.loggingService.catch(a);return}else this.notificationDataProvider$.next(t)}}catch(i){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",i)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",t),!1}}};e.\u0275fac=function(i){return new(i||e)(C(vt),C(me),C(Ot))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Up=class{constructor({apiKey:e,documentId:n,organizationId:t,clientDocumentId:i,clientOrganizationId:o,folderId:s,veltFolderId:a}){this.paths={},this.apiKey=e,this.documentId=n,this.organizationId=t,this.veltFolderId=a,i&&(this.documentId=_a(i)),o&&(this.organizationId=Ds(o)),s&&(this.folderId=s,this.veltFolderId=bo(s)),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 e=`apiKey/${this.apiKey}`;this.paths.activities=`${e}/${v.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.userNotificationIndex=`${e}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION_INDEX}`,this.organizationId&&(e=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=e,this.paths.folder=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${e}/${v.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${e}/${v.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${e}/${v.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${e}/${v.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${v.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${e}/${v.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${v.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userNotificationIndex(){return this.paths.userNotificationIndex}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(e){throw{type:"DocumentPaths",message:e,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var Sz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromAreaAnnotations(t){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",i),[]}}mergeAreaWithUser(t){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",i),t}}formatAreaData(t){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t}catch(i){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Az=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromUserIamData(t){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let i=new Set;if(t?.length)for(let o of t)o?.user?.userId&&i.add(o?.user?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",i),[]}}mergeUserIamWithUser(t){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);if(i){let o=i;t?.user&&typeof t.user=="object"&&(o=M(M({},o),t.user));let s=this.usersService.getContactListUser(t.user.userId);s&&(o=M(M({},o),s)),t=le(M({},t),{user:o})}}return t}catch(i){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Rz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromMultiThreads(t){try{let i=new Set;for(let o of t)o?.from?.userId&&i.add(o?.from?.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",i),[]}}mergeMultiThreadWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",i),t}}formatMultiThreadData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.commentAnnotationsMap&&(t.commentAnnotationsMap=null)),t}catch(i){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Dz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromSelections(t){try{let i=new Set;for(let o of t)o?.user?.userId&&i.add(o.user.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",i),[]}}mergeSelectionWithUser(t){try{if(t?.user?.userId){let i=this.usersService.getUserById(t?.user?.userId);i&&(t.user=i)}return t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",i),t}}formatSelectionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.user?.userId&&(t.user={userId:t.user.userId}),t}catch(i){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Cz=(()=>{let e=class e{constructor(t,i){this.loggingService=t,this.usersService=i}getUserIdsToResolveFromTags(t){try{let i=new Set;for(let o of t)if(o?.from?.userId&&i.add(o.from.userId),o?.to?.length)for(let s of o.to)s?.userId&&i.add(s.userId);return Array.from(i)}catch(i){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",i),[]}}mergeTagWithUser(t){try{if(t?.from?.userId){let i=this.usersService.getUserById(t?.from?.userId);i&&(t.from=i)}return t?.to?.length&&(t.to=t.to.map(i=>{if(i?.userId){let o=this.usersService.getUserById(i?.userId);o&&(i=o)}return i})),t}catch(i){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",i),t}}formatTagData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to?.length&&(t.to=t.to.map(i=>(i?.userId&&(i={userId:i.userId}),i)))),t}catch(i){return this.loggingService.catch("Error in TagUtilsService formatTagData:",i),t}}};e.\u0275fac=function(i){return new(i||e)(C(me),C(jt))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Nz=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,L,B,w,F,U){this.activityUtilsService=t,this.areaUtilsService=i,this.commentUtilsService=o,this.contactUtilsService=s,this.coreActionsService=a,this.liveStateUtilsService=c,this.loggingService=l,this.multiThreadUtilsService=u,this.reactionUtilsService=d,this.selectionUtilsService=f,this.tagUtilsService=g,this.usersService=p,this.docService=_,this.commentAnnotationsResolverService=T,this.reactionAnnotationsResolverService=D,this.recorderAnnotationsResolverService=L,this.notificationResolverService=B,this.activityResolverService=w,this.serviceBook=F,this.attachmentResolverService=U}getErrorForGetRequests({feature:t,error:i}){try{switch(t){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(i?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",o),null}}getFirestorePath({feature:t,properties:i,documentPaths:o,apiKey:s}){try{if(!s)return;if(t==="userNotificationIndex"){if(!i?.id)return;let d=new Up({apiKey:s});return d?.userNotificationIndex?`${d.userNotificationIndex}/${i.id}`:void 0}let{documentId:a,organizationId:c,folderId:l}=i;if(!c&&(c=o?.organizationId,!c))return;let u=new Up({apiKey:s,documentId:a?`${a}`:"",organizationId:c?`${c}`:"",veltFolderId:l?`${l}`:void 0});switch(t){case"userConfig":return i?.userId&&u?.userConfig?`${u?.userConfig}/${i?.userId}${i?.documentId?`/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:""}`:void 0;case"allPermissionsUsers":return u?.permissionsUsers?`${u?.permissionsUsers}`:void 0;case"comment":return i?.documentId&&i?.id&&u?.comment?`${u?.comment}/${i?.id}`:void 0;case"allComments":return i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"multiThread":return i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}/${i?.id}`:void 0;case"allMultiThreads":return i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}`:void 0;case"allLastNotificationTimestamp":return u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return i?.id&&u?.lastNotificationTimestamp?`${u?.lastNotificationTimestamp}/${i?.id}`:void 0;case"activity":return i?.id&&u?.activities?`${u?.activities}/${i?.id}`:void 0;case"allActivities":return u?.activities?`${u?.activities}`:void 0;case"allLastActivityTimestamp":return u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return i?.id&&u?.lastActivityTimestamp?`${u?.lastActivityTimestamp}/${i?.id}`:void 0;case"area":return i?.documentId&&i?.id&&u?.area?`${u?.area}/${i?.id}`:void 0;case"allAreas":return i?.documentId&&u?.area?`${u?.area}`:void 0;case"allDocuments":return u?.document?`${u?.document}`:void 0;case"allLocations":return u?.location?`${u?.location}`:void 0;case"allFolders":return u?.folder?`${u?.folder}`:void 0;case"folder":return u?.folder&&i.folderId?`${u?.folder}/${i.folderId}`:void 0;case"documentUserAccess":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"reaction":return i?.documentId&&i?.id&&u?.reaction?`${u?.reaction}/${i?.id}`:void 0;case"allReactions":return i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}`:void 0;case"allRecorders":return i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"recorderTrackEvent":return i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}/${i?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"apiKeyMetadata":return s?`apiKey/${s}`:void 0;case"organizationMetadata":return u?.organization?`${u?.organization}`:void 0;case"documentIam":case"documentMetadata":return i?.documentId&&u?.document?`${u?.document}/${i?.documentId}`:void 0;case"folderMetadata":return i?.folderId&&u?.folder?`${u?.folder}/${i?.folderId}`:void 0;case"locationMetadata":return i?.documentId&&u?.location&&i?.id?`${u?.location}/${i?.id}`:void 0;case"documentUser":return i?.documentId&&i?.id&&u?.documentUsers?`${u?.documentUsers}/${i?.id}`:void 0;case"allDocumentUsers":return u?.users?`${u?.users}`:void 0;case"allFolderUsers":return u?.users?`${u?.users}`:void 0;case"allOrganizationGroups":return u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return u?.users?`${u?.users}`:void 0;case"notificationViewsTimestamp":return i?.documentId&&i?.id&&u?.notificationViews?`${u?.notificationViews}/${i?.id}`:void 0;case"allDocumentViews":return i?.documentId&&u?.documentViews?`${u?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return i?.documentId&&i?.id&&u?.documentViews?`${u?.documentViews}/${i?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return i?.documentId&&i?.id&&u?.locationViews?`${u?.locationViews}/${i?.id}`:void 0;case"allLocationViews":return i?.documentId&&u?.locationViews?`${u?.locationViews}`:void 0;case"allDocNotifications":return i?.documentId&&u?.docNotification?`${u?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.docNotification?`${u?.docNotification}/${i?.id}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${i?.id}`:void 0;case"allUserNotifications":return i?.userId&&u?.notificationUsers?`${u?.notificationUsers}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${t}`)}}catch(a){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",a);return}}getFirestoreCollectionGroupPath(t){try{switch(t){case"allComments":return v.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return v.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return v.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return v.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return v.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return v.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return v.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return v.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return v.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return v.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${t}`)}}catch(i){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",i);return}}getDocumentPath({feature:t,properties:i,defaultDocumentPaths:o,apiKey:s,useFirestore:a}){try{if(!s)return;let{documentId:c,organizationId:l}=i;l||(l=o?.organizationId);let u=new hS({apiKey:s,documentId:c?`${c}`:"",organizationId:l?`${l}`:""});switch(t){case"userConfig":return i?.userId&&i?.documentId&&u?.userConfig?`${u?.userConfig}/${i?.userId}/${v.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${i?.documentId}`:void 0;case"allComments":return!a&&i?.documentId&&u?.comment?`${u?.comment}`:void 0;case"allGlobalContacts":return i?.documentId&&u?.globalContacts?`${u?.globalContacts}`:void 0;case"globalContacts":return i?.documentId&&i?.userId&&u?.globalContacts?`${u?.globalContacts}${i?.userId}`:void 0;case"groupContacts":return i?.documentId&&i?.groupId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}`:void 0;case"groupContactsUser":return i?.documentId&&i?.groupId&&i?.userId&&u?.groupContacts?`${u?.groupContacts}${i?.groupId}/${i?.userId}`:void 0;case"allLoginContacts":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}/contacts`:void 0;case"allLogins":return i?.documentId&&u?.logins?`${u?.logins}`:void 0;case"logins":return i?.documentId&&i?.userId&&u?.logins?`${u?.logins}${i?.userId}`:void 0;case"customerMetadata":return u?.customerMetadata?`${u?.customerMetadata}`:void 0;case"allArrows":return i?.documentId&&u?.arrow?`${u?.arrow}`:void 0;case"arrow":return i?.documentId&&u?.arrow&&i.id?`${u?.arrow}${i.id}`:void 0;case"allCursors":return i?.documentId&&u?.cursor?`${u?.cursor}`:void 0;case"cursor":return i?.documentId&&u?.cursor&&i.id?`${u?.cursor}${i.id}`:void 0;case"flockUser":return i?.documentId&&u?.flock&&i.id?`${u?.flock}users/${i.id}`:void 0;case"flockSession":return i?.documentId&&u?.flock&&i.id?`${u?.flock}sessions/${i.id}`:void 0;case"allHuddleAttendees":return i?.documentId&&u?.huddle?`${u?.huddle}attendees`:void 0;case"huddleAttendee":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}`:void 0;case"huddleAttendeeState":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}attendees/${i.id}/state`:void 0;case"allHuddleInvitees":return i?.documentId&&u?.huddle?`${u?.huddle}invitees`:void 0;case"huddleConnection":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}connections/${i.id}`:void 0;case"huddleIceCandidate":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}iceCandidates/${i.id}`:void 0;case"allHuddleIceCandidates":return i?.documentId&&u?.huddle?`${u?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return i?.documentId&&u?.huddle?`${u?.huddle}messages`:void 0;case"huddleMessage":return i?.documentId&&u?.huddle&&i.id?`${u?.huddle}messages/${i.id}`:void 0;case"allLiveStates":return i?.documentId&&u?.liveState?`${u?.liveState}`:void 0;case"allLiveStateCustoms":return i?.documentId&&u?.liveState?`${u?.liveState}custom`:void 0;case"liveStateCustom":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}custom/${i.id}`:void 0;case"liveStateSingleEditorMode":return i?.documentId&&u?.liveStateSingleEditorMode?`${u?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return i?.documentId&&u?.liveState?`${u?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return i?.documentId&&u?.liveState&&i?.id?`${u?.liveState}default/autoSyncState/history/${i.id}`:void 0;case"presence":return i?.documentId&&u?.presence&&i?.userId?`${u?.presence}${i?.userId}`:void 0;case"allPresence":return i?.documentId&&u?.presence?`${u?.presence}`:void 0;case"workspaceIam":return u?.workspaceIam?`${u?.workspaceIam}`:void 0;case"selection":return i?.documentId&&u?.selection&&i?.userId?`${u?.selection}${i?.userId}`:void 0;case"allSelections":return i?.documentId&&u?.selection?`${u?.selection}`:void 0;case"syncVideoPlayer":return i?.documentId&&u?.syncVideoPlayer?`${u?.syncVideoPlayer}`:void 0;case"allTags":return i?.documentId&&u?.tag?`${u?.tag}`:void 0;case"tag":return i?.documentId&&u?.tag&&i?.id?`${u?.tag}${i?.id}`:void 0;case"userContactUs":return i?.documentId&&u?.userContactUs?`${u?.userContactUs}`:void 0;case"userFeedback":return i?.documentId&&u?.userFeedback?`${u?.userFeedback}`:void 0;case"userReportBug":return i?.documentId&&u?.userReportBugs?`${u?.userReportBugs}`:void 0;case"comment":return!a&&i?.documentId&&i?.id&&u?.comment?`${u?.comment}${i?.id}`:void 0;case"allMultiThreads":return!a&&i?.documentId&&u?.multiThread?`${u?.multiThread}`:void 0;case"crdt":return!a&&i?.documentId&&u?.crdt?`${u?.crdt}`:void 0;case"crdtData":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/data`:void 0;case"crdtSyncState":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/state`:void 0;case"crdtSyncPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence/${i.userId}`:void 0;case"allCrdtSyncPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/sync/presence`:void 0;case"crdtPresence":return i?.documentId&&i.userId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence/${i.userId}`:void 0;case"allCrdtPresence":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/presence`:void 0;case"crdtVersion":return i?.documentId&&u?.crdt&&i?.id&&i?.versionId?`${u?.crdt}/${i?.id}/versions/${i?.versionId}`:void 0;case"crdtVersions":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/versions`:void 0;case"crdtMessages":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/messages`:void 0;case"crdtMessage":return i?.documentId&&u?.crdt&&i?.id&&i?.messageId?`${u?.crdt}/${i?.id}/messages/${i?.messageId}`:void 0;case"crdtSnapshot":return i?.documentId&&u?.crdt&&i?.id?`${u?.crdt}/${i?.id}/snapshot`:void 0;case"multiThread":return!a&&i?.documentId&&i?.id&&u?.multiThread?`${u?.multiThread}${i?.id}`:void 0;case"allLastNotificationTimestamp":return!a&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!a&&i?.id&&u?.organizationNotificationsLastNotificationTimestamp?`${u?.organizationNotificationsLastNotificationTimestamp}${i?.id}`:void 0;case"documentIam":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}`:void 0;case"allDocuments":return!a&&u?.docs&&i?.documentId?`${u?.docs}/${i?.documentId}/${v.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!a&&i?.documentId&&u?.area?`${u?.area}`:void 0;case"area":return!a&&i?.id&&u?.area?`${u?.area}${i?.id}`:void 0;case"folder":return!a&&i?.folderId&&u?.folder?`${u?.folder}${i?.folderId}`:void 0;case"documentUserAccess":return!a&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"documentUser":return!a&&i?.documentId&&i?.id&&u?.documentIam?`${u?.documentIam}users/${i?.id}`:void 0;case"allDocumentUsers":return!a&&i?.documentId&&u?.documentIam?`${u?.documentIam}users/`:void 0;case"allOrganizationGroups":return!a&&u?.organizationGroups?`${u?.organizationGroups}`:void 0;case"allOrganizationUsers":return!a&&u?.organizationIam?`${u?.organizationIam}users/`:void 0;case"reaction":return!a&&i?.id&&u?.reaction?`${u?.reaction}${i?.id}`:void 0;case"allReactions":return!a&&i?.documentId&&u?.reaction?`${u?.reaction}`:void 0;case"recorder":return!a&&i?.documentId&&i?.id&&u?.recorder?`${u?.recorder}${i?.id}`:void 0;case"allRecorders":return!a&&i?.documentId&&u?.recorder?`${u?.recorder}`:void 0;case"organizationMetadata":return!a&&u?.organizationMetadata?`${u?.organizationMetadata}`:void 0;case"heartbeat":return i?.id&&u?.heartbeat?`${u?.heartbeat}${i?.id}`:void 0;case"allHeartbeats":return u?.heartbeat?`${u?.heartbeat}`:void 0;case"heartbeatByDocument":return i?.id&&u?.heartbeatByDocument?`${u?.heartbeatByDocument}${i?.id}`:void 0;case"allHeartbeatsByDocument":return u?.heartbeatByDocument?`${u?.heartbeatByDocument}`:void 0;case"documentAccessType":return!a&&u?.documentIam?`${u?.documentIam}`:void 0;case"documentMetadata":return!a&&i?.documentId&&u?.metadata?`${u?.metadata}`:void 0;case"allDocumentViews":return!a&&i?.documentId&&u?.views?`${u?.views}documentViews/`:void 0;case"documentViews":return!a&&i?.documentId&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}`:void 0;case"allLocationViews":return!a&&i?.documentId&&u?.views?`${u?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!a&&i?.id&&i?.user&&u?.views?`${u?.views}notification/${i?.id}/views/${i?.user}`:void 0;case"documentUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}documentViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"documentMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}documentViews/${i?.id}/metadata`:void 0;case"documentDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}documentViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"locationViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/location`:void 0;case"location":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}`:void 0;case"locationUsersViews":return!a&&i?.id&&i?.user&&i?.date&&u?.views?`${u?.views}locationViews/${i?.id}/users/${i?.user}/${i?.date}`:void 0;case"locationMetadataViews":return!a&&i?.id&&u?.views?`${u?.views}locationViews/${i?.id}/metadata`:void 0;case"locationDayViews":return!a&&i?.id&&i?.date&&i?.user&&u?.views?`${u?.views}locationViews/${i?.id}/day/${i?.date}/${i?.user}`:void 0;case"docNotificationViews":case"docNotification":return i?.documentId&&i?.id&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}${i?.id}`:void 0;case"allDocNotifications":return i?.documentId&&u?.organizationNotificationsWithDocumentId?`${u?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return i?.userId&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}`:void 0;case"userNotificationViews":case"userNotification":return i?.userId&&i?.id&&u?.organizationNotificationsUsers?`${u?.organizationNotificationsUsers}${i?.userId}/${i?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${t}`)}}catch(c){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",c);return}}resolveAnnotations(o){return I(this,arguments,function*({data:t,feature:i}){try{if(t&&t?.length>0)switch(i){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let s=Z(),a=Nd.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:_t.RESOLVE_COMMENT_ANNOTATIONS,moduleName:a,source:"internal",payload:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let s=Z(),a=Od.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:a,source:"internal",payload:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let s=Z(),a=bd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:s,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:a,source:"internal",payload:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:s,moduleName:a})}break}default:break}}catch(s){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${i}`,s)}})}formatResponse(g){return I(this,arguments,function*({feature:t,data:i,organizationId:o,shouldAwait:s=!1,forceResolve:a=!1,shouldCommentAnnotationsResolverAwait:c=!1,shouldNotificationResolverAwait:l=!1,shouldActivityResolverAwait:u=!1,shouldReactionResolverAwait:d=!1,shouldRecorderResolverAwait:f=!1}){try{let p=o??this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId??"";if(this.usersService.userDataProviderAvailable()){let _=[];switch(t){case"allAreas":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(i)));break}case"allArrows":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(FT)?.getUserIdsToResolveFromArrowAnnotations(Object.values(i))??[]);break}case"allCursors":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(kT)?.getUserIdsToResolveFromCursorUsers(Object.values(i))??[]);break}case"allComments":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(i)));break}case"allDocumentUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allFolderUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allOrganizationUsers":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(i)));break}case"allMultiThreads":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(i)));break}case"allDocNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(Fi)?.getUserIdsToResolveFromNotifications(Array.isArray(i)?i:Object.values(i))??[]);break}case"allUserNotifications":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(Fi)?.getUserIdsToResolveFromNotifications(Object.values(i))??[]);break}case"allPresence":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(UT)?.getUserIdsToResolveFromPresenceUsers(Object.values(i))??[]);break}case"allRecorders":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(ui)?.getUserIdsToResolveFromRecorders(Object.values(i))??[]);break}case"allReactions":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(i)));break}case"allTags":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(i)));break}case"allHuddleAttendees":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.serviceBook.get(VT)?.getUserIdsToResolveFromHuddleAttendees(Object.values(i))??[]);break}case"liveStateCustom":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(i));break}case"allLiveStateCustoms":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(i)));break}case"allLiveStates":{i&&typeof i=="object"&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(i));break}case"liveStateSingleEditorMode":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(i));break}case"allSelections":{i&&typeof i=="object"&&!Array.isArray(i)&&(_=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(i)));break}case"allActivities":{i&&typeof i=="object"&&(_=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(i)?i:Object.values(i)));break}default:_=[]}if(_?.length){let T=Z(),D=Ea.GET_USERS;this.coreActionsService.triggerAction(H.USER_RESOLVER,{event:P.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Ln.FORMAT_RESPONSE,source:"internal",moduleName:D,payload:{userIds:_,feature:t,forceResolve:a}}),s?yield this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D}):this.usersService.resolveUsers({userIds:_,forceResolve:a,feature:t,organizationId:o,uniqueId:T,moduleName:D})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":case"allUserNotifications":{i&&typeof i=="object"&&(_=this.serviceBook.get(Fi)?.getCustomNotificationIdsToResolve(i)??[],_=_.filter(D=>!this.notificationResolverService.getNotificationById(D)));break}default:_=[]}if(_?.length){let T=Z(),D=kC.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Mn.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{notificationIds:_,organizationId:p,shouldNotificationResolverAwait:l}}),l?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.notificationResolverService.resolveNotifications({request:{notificationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let _=[];switch(t){case"allDocNotifications":{if(i&&typeof i=="object"){let D=this.serviceBook.get(Fi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}case"allUserNotifications":{if(i&&typeof i=="object"&&!Array.isArray(i)){let D=this.serviceBook.get(Fi)?.getTargetAnnotationIdsFromNotifications(i)??[];_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}case"allActivities":{if(i&&typeof i=="object"){let T=Array.isArray(i)?i:Object.values(i),D=this.activityUtilsService.getEntityIdsToResolveFromActivities(T,"comment");_=[..._,...D],_=_.filter(L=>!this.commentAnnotationsResolverService.getCommentAnnotationById(L))}break}default:_=[]}if(_?.length){let T=Z(),D=Nd.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.FORMAT_RESPONSE,moduleName:D,source:"internal",payload:{commentAnnotationIds:_,organizationId:p,shouldCommentAnnotationsResolverAwait:c}}),c?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:_,organizationId:p},uniqueId:T,moduleName:D})}}if(t==="allActivities"&&i&&typeof i=="object"){let _=Array.isArray(i)?i:Object.values(i),T=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let D=[];for(let L of _)L?.id&&!this.activityResolverService.getActivityById(L.id)&&D.push(L.id);if(D.length){let L=Z(),B=UC.GET_ACTIVITIES;this.coreActionsService.triggerAction(H.ACTIVITY_RESOLVER,{event:P.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:cr.FORMAT_RESPONSE,moduleName:B,source:"internal",payload:{activityIds:D,organizationId:T,shouldActivityResolverAwait:u}}),u?yield this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.activityResolverService.resolveActivities({request:{activityIds:D,organizationId:T},uniqueId:L,moduleName:B})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"reaction");if(D=D.filter(L=>!this.reactionAnnotationsResolverService.getAnnotationById(L)),D.length){let L=Z(),B=Od.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:Tt.RESOLVE_REACTION_ANNOTATIONS,moduleName:B,source:"internal",payload:{reactionAnnotationIds:D,organizationId:T,shouldReactionResolverAwait:d}}),d?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let D=this.activityUtilsService.getEntityIdsToResolveFromActivities(_,"recorder");if(D=D.filter(L=>!this.recorderAnnotationsResolverService.getAnnotationById(L)),D.length){let L=Z(),B=bd.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:L,methodName:It.RESOLVE_RECORDER_ANNOTATIONS,moduleName:B,source:"internal",payload:{recorderAnnotationIds:D,organizationId:T,shouldRecorderResolverAwait:f}}),f?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:D,organizationId:T},uniqueId:L,moduleName:B})}}}return i}catch(p){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",p),i}})}mergeCommentAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(a),o),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(Fi);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithNotification(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",o),t}}mergeActivityResolverWithData({data:t,feature:i}){try{return this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable()&&i==="allActivities"&&Array.isArray(t)?t.map(o=>this.activityUtilsService.mergeActivityWithResolverData(o)):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",o),t}}mergeNotificationsWithResolvedData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(i){case"allDocNotifications":case"allUserNotifications":{let o=this.serviceBook.get(Fi);return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeResolvedNotificationData(c):c,s),{}):Array.isArray(t)?t.map(s=>o?o.mergeResolvedNotificationData(s):s):t}default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",o),t}}mergeNotificationsWithResolvedData$({data:t,feature:i}){try{return this.notificationResolverService.getNotificationsById$().pipe(ge(()=>{let o=this.mergeNotificationsWithResolvedData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",o),de(t)}}mergeReactionAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(i){case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(a),o),{}):t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",o),t}}mergeRecorderAnnotationsWithData({data:t,feature:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(i){case"allRecorders":if(t&&typeof t=="object"&&!Array.isArray(t)){let o=this.serviceBook.get(ui);return Object.entries(t).reduce((s,[a,c])=>(s[a]=o?o.mergeStrippedDataWithRecorderAnnotation(c):c,s),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",o),t}}mergeActivitiesWithFeatureData(t){return Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithFeatureData(i)):t}mergeLocationMetadataWithData({data:t,feature:i,locationMetadata:o}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),o&&typeof o=="object"&&!Array.isArray(o))switch(i){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((s,[a,c])=>(s[a]=this.commentUtilsService.mergeLocationWithCommentAnnotations(c,o),s),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let s=this.serviceBook.get(Fi);return Object.entries(t).reduce((a,[c,l])=>(a[c]=s?s.mergeLocationWithNotification(l,o):l,a),{})}else return t;default:return t}return t}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",s),t}}mergeUsersWithData({feature:t,data:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(t){case"allAreas":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.areaUtilsService.mergeAreaWithUser(a),o),{}):i;case"allArrows":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(FT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeArrowWithUser(c):c,s),{})}else return i;case"allCursors":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(kT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeCursorUserWithUser(c):c,s),{})}else return i;case"allComments":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.commentUtilsService.mergeCommentWithUser(a),o),{}):i;case"allDocumentUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allFolderUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allOrganizationUsers":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.contactUtilsService.mergeUserIamWithUser(a),o),{}):i;case"allMultiThreads":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.multiThreadUtilsService.mergeMultiThreadWithUser(a),o),{}):i;case"allDocNotifications":if(i&&typeof i=="object"){let o=this.serviceBook.get(Fi);return i?.map(s=>o?o.mergeNotificationWithUser(s):s)}else return i;case"allUserNotifications":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(Fi);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeNotificationWithUser(c):c,s),{})}else return i;case"allPresence":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(UT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergePresenceUserWithUser(c):c,s),{})}else return i;case"allRecorders":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(ui);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?o.mergeRecorderWithUser(c):c,s),{})}else return i;case"allReactions":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.reactionUtilsService.mergeReactionWithUser(a),o),{}):i;case"allTags":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.tagUtilsService.mergeTagWithUser(a),o),{}):i;case"allHuddleAttendees":if(i&&typeof i=="object"&&!Array.isArray(i)){let o=this.serviceBook.get(VT);return Object.entries(i).reduce((s,[a,c])=>(s[a]=o?.mergeHuddleAttendeeWithUser(c)??c,s),{})}else return i;case"liveStateCustom":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(i):i;case"allLiveStateCustoms":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(a),o),{}):i;case"allLiveStates":return i&&typeof i=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(i):i;case"liveStateSingleEditorMode":return i&&typeof i=="object"&&!Array.isArray(i)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(i):i;case"allSelections":return i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).reduce((o,[s,a])=>(o[s]=this.selectionUtilsService.mergeSelectionWithUser(a),o),{}):i;case"allActivities":return Array.isArray(i)?i.map(o=>this.activityUtilsService.mergeActivityWithUser(o)):i;default:return i}return i}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",o),i}}mergeCommentAnnotationsWithData$({data:t,feature:i}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(ge(()=>{let o=this.mergeCommentAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",o),de(t)}}mergeReactionAnnotationsWithData$({data:t,feature:i}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(ge(()=>{let o=this.mergeReactionAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",o),de(t)}}mergeRecorderAnnotationsWithData$({data:t,feature:i}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(ge(()=>{let o=this.mergeRecorderAnnotationsWithData({data:t?.data??{},feature:i}),s=this.mergeUsersWithData({feature:i,data:o??{}});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",o),de(t)}}mergeUsersWithData$({feature:t,data:i}){try{return this.usersService.getUserById$().pipe(ge(()=>{let o=this.mergeUsersWithData({feature:t,data:i?.data??{}});return typeof o=="object"?{data:JSON.parse(JSON.stringify(o)),operation:i?.operation??null}:{data:o,operation:i?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch(`Error in mergeUsersWithData for ${t}:`,o),de(i)}}mergeLocationMetadataWithData$({data:t,feature:i}){try{return this.docService.getLocationMetadata$().pipe(ge(o=>{let s=this.mergeLocationMetadataWithData({data:t?.data??{},feature:i,locationMetadata:o});return typeof s=="object"?{data:JSON.parse(JSON.stringify(s)),operation:t?.operation??null}:{data:s,operation:t?.operation??null}}),rt(Pt))}catch(o){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${i}:`,o),de(t)}}handleDataStripping(a){return I(this,arguments,function*({feature:t,data:i,actionType:o,commentId:s}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),t){case"comment":{let c=yield this.commentUtilsService.stripCommentAnnotationData({data:i,actionType:o,commentId:s});return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()})}case"reaction":{let c=this.reactionUtilsService.stripReactionAnnotationData(i);return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()})}case"recorder":{let c=this.serviceBook.get(ui)?.stripRecorderAnnotationData({data:i,actionType:o})??{originalData:i,strippedData:null};return this.filterOriginalDataForVeltDb({feature:t,result:c,providerAvailable:this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()})}default:return{originalData:i,strippedData:null}}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",c),{originalData:i,strippedData:null}}})}filterOriginalDataForVeltDb({feature:t,result:i,providerAvailable:o}){try{return!o||!i||i.originalData===null||i.originalData===void 0?i:le(M({},i),{originalData:this.applyVeltDbFieldFilter(t,i.originalData)})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService filterOriginalDataForVeltDb:",s),i}}applyVeltDbFieldFilter(t,i){switch(t){case"comment":return nB(i,{stripAttachmentFiles:this.attachmentResolverService.attachmentDataProviderAvailable()});case"reaction":return rB(i);case"recorder":return iB(i);default:return i}}formatData({feature:t,data:i,properties:o,offset:s,isRealtimeDb:a}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof i=="object"&&(i=JSON.parse(JSON.stringify(i)));let c=new Date().getTime()+s;switch(t){case"documentAccessType":return delete i?.users,{docIamConfig:i};case"organizationMetadata":case"documentMetadata":return a?i:{metadata:i};case"documentCommentMetadata":return i;case"cursor":{let l=this.serviceBook.get(kT);return l?l.formatCursorUserData(i):i}case"comment":return this.commentUtilsService.formatCommentData(i);case"area":return this.areaUtilsService.formatAreaData(i);case"arrow":{let l=this.serviceBook.get(FT);return l?l.formatArrowData(i):i}case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(i);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(i);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(i);case"reaction":return this.reactionUtilsService.formatReactionData(i);case"recorder":return this.serviceBook.get(ui)?.formatRecorderData(i,c)??i;case"notificationViewsTimestamp":return{views:{[o.user??""]:i}};case"documentUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"documentDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"documentMetadataViews":return a?i:{metadata:i};case"huddleMessage":return this.serviceBook.get(VT)?.formatHuddleMessageData(i)??i;case"locationMetadataViews":return a?i:{metadata:i};case"locationUsersViews":return a?i:{users:{[o.user??""]:{[o.date??""]:i}}};case"locationDayViews":return a?i:{day:{[o.date??""]:{[o.user??""]:i}}};case"locationViews":return a?i:{location:i};case"docNotificationViews":return a?i:{views:i.views};case"userNotificationViews":return a?i:{views:i.views};case"presence":{let l=this.serviceBook.get(UT);return l?l.formatPresenceUserData(i):i}case"selection":return this.selectionUtilsService.formatSelectionData(i);case"tag":return this.tagUtilsService.formatTagData(i);default:return i}}catch(c){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",c),i}}modifyAndSetData(a){return I(this,arguments,function*({feature:t,data:i,subscriber:o,operation:s=null}){try{let c=yield this.modifyData({feature:t,data:i});o.next({data:c,operation:s})}catch(c){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",c)}})}isDataAlreadyProcessedInLocalCache({feature:t,change:i,cache:o}){try{if(t==="allReactions"||t==="allComments"){if(i.type==="removed")return!Object.keys(o??{}).includes(i.doc.id);if(o?.[i.doc.id]){let s=i.doc.data(),a=o?.[i.doc.id];return s?.lastUpdated===a?.lastUpdated}}return!1}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",s),!1}}modifyData(o){return I(this,arguments,function*({feature:t,data:i}){try{return yield this.formatResponse({feature:t,data:i})}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",s),i}})}addMetadata(t,i){try{return t&&typeof t=="object"&&!Array.isArray(t)?le(M({},t),{metadata:t?.metadata??{documentId:i?.documentId,organizationId:i?.organizationId,apiKey:i?.apiKey}}):t}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",o),t}}setDataInLocal(l){return I(this,arguments,function*({feature:t,data:i,observablesCache:o,eventType:s,id:a,operation:c=null}){try{let d={comment:"allComments",reaction:"allReactions"}[t];if(!d)return null;let f=i?.metadata?.documentId,g=i?.metadata?.veltFolderId;return Object.keys(o).filter(p=>p.includes(d)&&(!f||p.includes(f)||g&&p.includes(g))).forEach(p=>{let _=o[p]?.subject?.getValue()??{};s==="DELETE"?a&&_?.data?.[a]&&(delete _?.data?.[a],o[p]?.subject&&o[p].subject.next({data:_?.data,operation:c})):o[p]?.subject?.next({data:le(M({},_?.data),{[i?.annotationId]:i}),operation:c})}),null}catch(u){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",u),null}})}handleCommentEncryption(c){return I(this,arguments,function*({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a}){try{return yield this.commentUtilsService.handleCommentEncryption({data:t,firestorePath:i,extraData:o,eventType:s,metadata:a})}catch(l){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",l),t}})}handleReactionEncryption(s){return I(this,arguments,function*({data:t,firestorePath:i,eventType:o}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:t,firestorePath:i,eventType:o})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",a),t}})}rtdbDefaultTransactionCallback(t,i){try{let o=M({},t||{});return Object.entries(i).forEach(([s,a])=>{a==null?delete o[s]:o[s]=a}),o}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",o),t}}};e.\u0275fac=function(i){return new(i||e)(C(dS),C(Sz),C(cS),C(Az),C(vt),C(vz),C(me),C(Rz),C(uS),C(Dz),C(Cz),C(jt),C(ef),C(qo),C(Ko),C(lc),C(fS),C(lS),C(di),C(Zh))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var rae={comment:{mode:"persistent",scope:"doc"},notification:{mode:"persistent",scope:"user"},notificationIndex:{mode:"persistent",scope:"user"},presence:{mode:"ephemeral",scope:"doc"},liveState:{mode:"ephemeral",scope:"doc"},cursor:{mode:"ephemeral",scope:"doc"},huddle:{mode:"ephemeral",scope:"doc"},syncVideoPlayer:{mode:"ephemeral",scope:"doc"},heartbeat:{mode:"ephemeral",scope:"org"},flockSession:{mode:"ephemeral",scope:"doc"},selection:{mode:"ephemeral",scope:"doc"}};function Oz(r){return rae[r]}var nt={getDatabase:rh,ref:ih,query:tj,get:Lm,set:ij,update:oj,remove:nj,push:ej,runTransaction:rj,onValue:Mb,onChildAdded:Q2,onChildChanged:X2,onChildRemoved:J2,off:Y2,objectVal:q2,listVal:z2,stateChanges:K2,onDisconnect:Z2},bz=(()=>{let e=class e{constructor(t,i){this.databaseService=t,this.loggingService=i}getServerTimeOffset(){return I(this,null,function*(){try{let t=this.databaseService.getDbValue();if(!t)return 0;let o=(yield Lm(ih(t,e.SERVER_TIME_OFFSET_PATH)))?.val();return typeof o=="number"?o:0}catch(t){return this.loggingService.catch("Error in FirebaseRealtimeAdapter getServerTimeOffset: ",t),0}})}onServerTimeOffset(t){let i=null,o=null;try{o=this.databaseService.getDb().subscribe(s=>{if(s){let a=ih(s,e.SERVER_TIME_OFFSET_PATH);i=Mb(a,c=>{try{t(c?.val())}catch(l){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset callback: ",l)}})}})}catch(s){this.loggingService.catch("Error in FirebaseRealtimeAdapter onServerTimeOffset: ",s)}return()=>{try{i&&(i(),i=null),o?.unsubscribe(),o=null}catch(s){this.loggingService.catch("Error tearing down FirebaseRealtimeAdapter onServerTimeOffset: ",s)}}}getChannelTag(t){return Oz(t)}getDatabaseInstance(t){return t?nt.getDatabase(void 0,t):nt.getDatabase()}rtdbRef(t,i){return nt.ref(t,i)}rtdbQueryRef(t,...i){return nt.query(t,...i)}rtdbGet(t){return nt.get(t)}rtdbSet(t,i,o){return this.getChannelTag(t),nt.set(i,o)}rtdbUpdate(t,i,o){return this.getChannelTag(t),nt.update(i,o)}rtdbRemove(t,i){return this.getChannelTag(t),nt.remove(i)}rtdbPush(t,i,o){return this.getChannelTag(t),o===void 0?nt.push(i):nt.push(i,o)}rtdbRunTransaction(t,i,o){return this.getChannelTag(t),nt.runTransaction(i,o)}rtdbOnValue(t,i,o,s,a){return this.getChannelTag(t),typeof s=="function"?a?nt.onValue(i,o,s,a):nt.onValue(i,o,s):s?nt.onValue(i,o,s):nt.onValue(i,o)}rtdbOnChildAdded(t,i,o,s){return this.getChannelTag(t),s?nt.onChildAdded(i,o,s):nt.onChildAdded(i,o)}rtdbOnChildChanged(t,i,o,s){return this.getChannelTag(t),s?nt.onChildChanged(i,o,s):nt.onChildChanged(i,o)}rtdbOnChildRemoved(t,i,o,s){return this.getChannelTag(t),s?nt.onChildRemoved(i,o,s):nt.onChildRemoved(i,o)}rtdbOff(t,i,o){nt.off(t,i,o)}rtdbObjectVal$(t,i){return this.getChannelTag(t),nt.objectVal(i)}rtdbListVal$(t,i){return this.getChannelTag(t),nt.listVal(i)}rtdbStateChanges$(t,i){return this.getChannelTag(t),nt.stateChanges(i)}rtdbOnDisconnectSet(t,i,o){return this.getChannelTag(t),nt.onDisconnect(i).set(o)}rtdbOnDisconnectUpdate(t,i,o){return this.getChannelTag(t),nt.onDisconnect(i).update(o)}rtdbOnDisconnectRemove(t,i){return this.getChannelTag(t),nt.onDisconnect(i).remove()}rtdbOnDisconnectCancel(t,i){return this.getChannelTag(t),nt.onDisconnect(i).cancel()}subscribe(t,i,o,s){return{unsubscribe:()=>{}}}publish(t,i,o){return I(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.publish wiring deferred to Phase A"}})}presence(t,i){return I(this,null,function*(){return{ok:!1,code:"unimplemented",message:"RealtimeAdapter.presence wiring deferred to Phase A"}})}onDisconnect(t,i){return I(this,null,function*(){return()=>{}})}};e.SERVER_TIME_OFFSET_PATH=".info/serverTimeOffset",e.\u0275fac=function(i){return new(i||e)(C(cc),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var gS=(()=>{let e=class e{constructor(t,i,o){this.configService=t,this.authService=i,this.loggingService=o,this.firestore$=new Y(null);try{ti([this.authService.getFirebaseConfig$(),this.configService.getApiKey$(),this.configService.getFirestorePersistentCacheEnabled$()]).pipe(Rt(([s,a])=>!!s&&!!a),Dt(1)).subscribe(([s,a,c])=>{if(s&&a&&s?.firebaseOptions?.storeDbId){try{let d=sessionStorage?.getItem("veltFirestoreLogLevel")||dn?.firebaseLogLevel||"silent";aM(d)}catch(d){this.loggingService.catch("Error in FirestoreService setLogLevel: ",d)}let l=uc.getFirestoreProdDbName(a,s.firebaseOptions),u=this.configService.getProxyConfig();if(u?.v2DbHost){let d={host:u.v2DbHost,ssl:!0};u.forceLongPolling?d.experimentalForceLongPolling=!0:d.experimentalAutoDetectLongPolling=!0,c&&(d.localCache=jM({tabManager:HM()}));try{this.firestore$.next(eS(Sr(),d,l))}catch(f){this.loggingService.catch("Firestore proxy: initializeFirestore failed, falling back to existing instance. Proxy settings may not be applied: ",f),this.firestore$.next(Xh(l))}}else if(c)try{let d=Sr(),f=eS(d,{localCache:jM({tabManager:HM()})},l);this.firestore$.next(f)}catch{this.firestore$.next(Xh(l))}else this.firestore$.next(Xh(l))}},s=>{})}catch{}}getFirestore(){return this.firestore$.asObservable()}getFirestoreValue(){return this.firestore$.value}generateFirestoreDocumentId(){try{let t=this.getFirestoreValue()||Xh("DocumentIdDb");if(t){let i=iS(t,"generateDocumentId");return xp(i).id}return}catch(t){this.loggingService.catch("Error in FirestoreService generateFirestoreDocumentId: ",t);return}}};e.\u0275fac=function(i){return new(i||e)(C(Xn),C(Dr),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Qr={doc:xp,collection:iS,collectionGroup:lz,query:gz,getDoc:WM,getDocs:hz,getCountFromServer:dz,setDoc:pz,deleteDoc:uz,onSnapshot:fz,runTransaction:mz},Lz=(()=>{let e=class e{constructor(t,i,o){this.firestoreService=t,this.databaseService=i,this.loggingService=o}read(t){return I(this,null,function*(){if((t.store??"firestore")==="rtdb"){let a=this.databaseService.getDbValue();return a?{data:(yield Lm(ih(a,t.location)))?.val()}:{data:void 0}}let o=this.firestoreService.getFirestoreValue();return o?{data:(yield WM(xp(o,t.location)))?.data()}:{data:void 0}})}runTransaction(t){return I(this,null,function*(){return t()})}firestoreDoc(t,i){return Qr.doc(t,i)}firestoreCollection(t,i){return Qr.collection(t,i)}firestoreCollectionGroup(t,i){return Qr.collectionGroup(t,i)}firestoreQuery(t,...i){return Qr.query(t,...i)}firestoreGetDoc(t){return Qr.getDoc(t)}firestoreGetDocs(t){return Qr.getDocs(t)}firestoreGetCountFromServer(t){return Qr.getCountFromServer(t)}firestoreSetDoc(t,i,o){return o?Qr.setDoc(t,i,o):Qr.setDoc(t,i)}firestoreDeleteDoc(t){return Qr.deleteDoc(t)}firestoreOnSnapshot(t,i,o){return o?Qr.onSnapshot(t,i,o):Qr.onSnapshot(t,i)}firestoreRunTransaction(t,i){return Qr.runTransaction(t,i)}addComment(t){return this.deferred("addComment")}editComment(t){return this.deferred("editComment")}deleteComment(t){return this.deferred("deleteComment")}setCommentResolved(t){return this.deferred("setCommentResolved")}setCommentMetadata(t){return this.deferred("setCommentMetadata")}bumpCommentViews(t){return this.deferred("bumpCommentViews")}markCommentThreadRead(t){return this.deferred("markCommentThreadRead")}markNotificationRead(t){return this.deferred("markNotificationRead")}addNotification(t){return this.deferred("addNotification")}deleteNotification(t){return this.deferred("deleteNotification")}updateNotification(t){return this.deferred("updateNotification")}updatePresence(t){return this.deferred("updatePresence")}grantAccess(t){return this.deferred("grantAccess")}revokeAccess(t){return this.deferred("revokeAccess")}getAccess(t){return this.deferred("getAccess")}upsertOrgUserProfile(t){return this.deferred("upsertOrgUserProfile")}upsertDocMetadata(t){return this.deferred("upsertDocMetadata")}upsertOrgMetadata(t){return this.deferred("upsertOrgMetadata")}createActivity(t){return this.deferred("createActivity")}deferred(t){return this.loggingService.warn(`[WB] FirebaseDbAdapter.${t} called but write-op wiring is deferred to Phase A (self-hosting Step 0). The SDK uses its existing direct write path in Step 0.`),Promise.resolve({ok:!1,code:"unimplemented",message:`FirebaseDbAdapter.${t} wiring deferred to Phase A`})}};e.\u0275fac=function(i){return new(i||e)(C(gS),C(cc),C(me))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var Mz=(()=>{let e=class e{allow(){return Promise.resolve({allow:!0})}canRead(t){return I(this,null,function*(){return this.allow()})}canWrite(t){return I(this,null,function*(){return this.allow()})}};e.\u0275fac=function(i){return new(i||e)},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();var p1e=(()=>{let e=class e{constructor(t,i,o,s,a,c,l,u,d,f,g,p,_,T,D,L,B,w){this.activityUtilsService=t,this.authService=i,this.commonDbUtilsService=o,this.coreActionsService=s,this.loggingService=a,this.firestoreService=c,this.databaseService=l,this.configService=u,this.docService=d,this.usersService=f,this.commentAnnotationsResolverService=g,this.reactionAnnotationsResolverService=p,this.recorderAnnotationsResolverService=_,this.notificationResolverService=T,this.serviceBook=D,this.realtimeAdapter=L,this.dbAdapter=B,this.authzAdapter=w,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.serverTimeOffsetUnsub=null,this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.serviceBook.observe(jT).subscribe(F=>{this.activityService=F??void 0}),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(F=>{F&&(this.db=F)})),this.serverTimeOffsetUnsub=this.realtimeAdapter.onServerTimeOffset(F=>{this.offset=F}),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(F=>{F&&(this.firestore=F)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([t,i])=>{i?.subject?.complete(),i?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(t){this.loggingService.catch("Error in unsubscribeFromObservables:",t)}}ngOnDestroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.offsetListener&&this.offsetListener(),this.serverTimeOffsetUnsub&&(this.serverTimeOffsetUnsub(),this.serverTimeOffsetUnsub=null),this.unsubscribeFromObservables()}setupOnDisconnect(t,i,o){return I(this,null,function*(){try{if(this.db){let s=this.realtimeAdapter.rtdbRef(this.db,t);return this.realtimeAdapter.rtdbOnDisconnectUpdate(o??"commondb",s,i)}return Promise.resolve()}catch(s){return this.loggingService.catch("Error in setupOnDisconnect:",s),Promise.resolve()}})}getOffset(){return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(t){ti([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Rt(([i,o])=>!!i),Dt(1),ea(([i,o])=>{t({db:i,firestore:o})})).subscribe({error:i=>{this.loggingService.catch("Error in CommonDbService subscription: ",i)}})}performDatabaseOperation(t,i,o,s,a,c){return I(this,null,function*(){try{if(!i){this.loggingService.warn(`%c[WB] No properties found for ${t}`,"color: red;");return}return this.subscribeToServices(d=>I(this,[d],function*({db:l,firestore:u}){let f;i?.skipFirestore||(f=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}));let g=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!l){this.loggingService.warn(`%c[WB] No database or firestore found for ${t}`,"color: red;");return}try{let p,_;try{g&&(p=this.realtimeAdapter.rtdbRef(l,`${g}`))}catch{this.loggingService.catch("Error in dbRef")}try{f?.includes("/organizations")&&u&&f&&(_=this.dbAdapter.firestoreDoc(u,`${f}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield o({dbRef:p,firestoreRef:_,data:s,firestorePath:f}),c&&c({firestoreAvailable:!!u})}catch(p){this.loggingService.catch(`Error in ${t} operation: `,p),a&&a(p)}}))}catch(l){this.loggingService.catch("Error in performDatabaseOperation:",l)}})}setData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,u.dbRef,()=>JSON.parse(JSON.stringify(d))):yield this.realtimeAdapter.rtdbSet(t,u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId??o?.targetCommentId});if(t==="comment"){let _=null,T=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:It.SET_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(u.firestoreRef,d)}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in setData for ${t}`,u)}})}updateData(l){return I(this,arguments,function*({feature:t,data:i,properties:o,callback:s,errorCallback:a,extraData:c}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${t}`,"color: green;"),this.shouldUseFirestore()&&i?.metadata&&!i?.metadata?.apiKey?void 0:(this.commonDbUtilsService.setDataInLocal({feature:t,data:i,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,c),this.performDatabaseOperation(t,o,u=>I(this,null,function*(){if(u.dbRef&&!o?.skipRtdb){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset(),isRealtimeDb:!0});o?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,u.dbRef,f=>{let g;return o?.rtdbTransactionCallback?g=o.rtdbTransactionCallback(f,d):g=this.commonDbUtilsService.rtdbDefaultTransactionCallback(f,d),JSON.parse(JSON.stringify(g))}):yield this.realtimeAdapter.rtdbUpdate(t,u.dbRef,JSON.parse(JSON.stringify(d)))}try{if(u.firestoreRef&&u.data&&!o?.skipFirestore){let d=this.commonDbUtilsService.formatData({feature:t,data:u.data,properties:o,offset:this.getOffset()});typeof d=="object"&&(d=JSON.parse(JSON.stringify(d)));let{strippedData:f,originalData:g,eventType:p}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:d,actionType:c?.actionType,commentId:c?.targetAnnotationData?.commentId});if(t==="comment"){let _=null,T=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:_t.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g,eventType:p,commentId:c?.targetAnnotationData?.commentId}}),f&&(_=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:f,eventType:p,commentId:c?.targetAnnotationData?.commentId},T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:u.firestorePath??"",extraData:c,metadata:o?.metadata}))}else if(t==="reaction"){let _=null,T=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:Tt.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(f,T)),g&&(_?.isSuccess||_===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:u.firestorePath??""}))}else if(t==="recorder"){let _=null,T=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:T,methodName:It.UPDATE_DATA,source:"internal",payload:{strippedData:f,originalData:g}}),f&&(_=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:f,eventType:p},T)),g&&(_?.isSuccess||_===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,D=>I(this,null,function*(){D.set(u.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(u.firestoreRef,d,{merge:!0})}}catch(d){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${t}`,d)}}),i,a,s))}catch(u){this.loggingService.catch(`Error in updateData for ${t}`,u)}})}createActivityFromExtraData(t,i){try{if(!i?.actionType||!this.activityService)return;let o=this.activityUtilsService.buildActivityDataFromExtraData({feature:t,extraData:i});o&&this.activityService.createActivity(o)}catch(o){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",o)}}deleteData(c){return I(this,arguments,function*({feature:t,properties:i,callback:o,errorCallback:s,extraData:a}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${t}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:t,observablesCache:this.observablesCache,eventType:"DELETE",id:i?.id,operation:{type:"removed",ids:[i?.id]}}),this.createActivityFromExtraData(t,a),this.performDatabaseOperation(t,i,l=>I(this,null,function*(){l.dbRef&&(yield this.realtimeAdapter.rtdbRemove(t,l.dbRef));try{if(l.firestoreRef&&!i?.skipFirestore)if(t==="comment"){let u=null,d=Z();this.coreActionsService.triggerAction(H.COMMENT_RESOLVER,{event:P.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:_t.DELETE_DATA,source:"internal",payload:{commentAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE",metadata:i?.metadata}))}else if(t==="reaction"){let u=null,d=Z();this.coreActionsService.triggerAction(H.REACTION_RESOLVER,{event:P.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Tt.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:l.firestorePath??"",eventType:"DELETE"}))}else if(t==="recorder"){let u=null,d=Z();this.coreActionsService.triggerAction(H.RECORDER_RESOLVER,{event:P.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:It.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:i?.id??"",metadata:i?.metadata}}),u=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(i?.id??"",i?.metadata,d),(u?.isSuccess||u===null)&&(yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef))}else if(t==="userNotification"){let u=null,d=Z();this.coreActionsService.triggerAction(H.NOTIFICATION_RESOLVER,{event:P.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:Mn.DELETE_DATA,source:"internal",payload:{notificationId:i?.id??"",organizationId:i?.organizationId??""}}),u=yield this.notificationResolverService.deleteNotification(String(i?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",d),(u?.isSuccess||u===null)&&(yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef))}else yield this.dbAdapter.firestoreDeleteDoc(l.firestoreRef)}catch(u){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${t}`,u)}}),void 0,s,o)}catch(l){this.loggingService.catch(`Error in deleteData for ${t}`,l)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled()}catch(t){return this.loggingService.catch("Error in shouldUseFirestore:",t),!1}}generateDocumentId(){try{let t=this.firestoreService.generateFirestoreDocumentId();return t||(t=Z()),t||"noDocumentId"}catch(t){return this.loggingService.catch("Error in generateFirestoreDocumentId:",t),Z()||"noDocumentId"}}queryData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();return!t||!i?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):s?yield this.handleFirestoreQuery(t,i):yield this.handleRtdbQuery(t,i)}catch(s){return this.loggingService.catch(`Error in queryData for ${t}`,s),[]}})}handleFirestoreQuery(t,i){return I(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let o=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),[];try{let s=this.dbAdapter.firestoreCollection(this.firestore,o);i?.useCollectionGroup&&(s=this.dbAdapter.firestoreCollectionGroup(this.firestore,o));let a=i?.firestoreQuery??[],c=this.dbAdapter.firestoreQuery(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];if(i?.getCount)try{let l=yield this.dbAdapter.firestoreGetCountFromServer(c).catch(u=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,u),null));return l?l.data().count:0}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,l),0}else try{let l=yield this.dbAdapter.firestoreGetDocs(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,d),null));if(!l)return[];let u=l.docs.map(d=>d.data());try{return yield this.commonDbUtilsService.modifyData({feature:t,data:u})}catch(d){return this.loggingService.catch(`Error in modifyData for ${t}`,d),u}}catch(l){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,l),[]}}catch(s){return this.loggingService.catch(`Error in Firestore query for ${t}:`,s),[]}}catch(o){return this.loggingService.catch(`Error in Firestore query for ${t}:`,o),[]}})}handleRtdbQuery(t,i){return I(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let o=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!o)return this.loggingService.warn(`[WB] No database path found for ${t}`),[];try{let s=this.realtimeAdapter.rtdbRef(this.db,o),a=i?.rtdbQuery??[],c=this.realtimeAdapter.rtdbQueryRef(s,...a);if(!this.authService.getUser()&&!i?.skipUserCheck)return[];let l=yield this.realtimeAdapter.rtdbGet(c).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),null));if(!l)return[];let u=l.val();return u?i?.skipObjectValues?u:Object.values(u??{}):[]}catch(s){return this.loggingService.catch(`Error in RTDB query for ${t}:`,s),[]}})}buildAuthzRequest(t,i){return{feature:t,scope:"doc",resourceId:i?.id!=null?String(i.id):void 0,apiKey:i?.apiKey??this.configService.getApiKey()??void 0,organizationId:i?.organizationId!=null?String(i.organizationId):void 0,documentId:i?.documentId!=null?String(i.documentId):void 0}}getData(o){return I(this,arguments,function*({feature:t,properties:i}){try{let s=this.shouldUseFirestore();if(i?.skipFirestore&&(s=!1),!t||!i)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};if(s&&this.firestore){let a=this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,i))).allow)return{};let l=yield this.dbAdapter.read({feature:t,scope:"doc",location:a,store:"firestore",field:i?.field,suppressError:i?.suppressError}).catch(d=>(this.authService.getUser()&&!i?.suppressError&&this.loggingService.catch(`Error in getDoc for ${t}`,d),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:d})));if(l){if(l?.errorCode)return l}else return this.loggingService.warn(`[WB] No document found at ${a}`),{};let u=l.data;return i?.field?u?.[i.field]??{}:u??{}}catch(c){return this.loggingService.catch(`Error fetching Firestore data for ${t}:`,c),{}}}if(this.db){let a=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!a)return this.loggingService.warn(`[WB] No database path found for ${t}`),{};try{if(!this.authService.getUser())return{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,i))).allow)return{};let l=yield this.dbAdapter.read({feature:t,scope:"doc",location:a,store:"rtdb",field:i?.field,suppressError:i?.suppressError}).catch(d=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,d),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:d})));if(l){if(l?.errorCode)return l}else return this.loggingService.warn(`[WB] No data found at ${a}`),{};let u=l.data;return i?.field?u?.[i.field]??{}:u??{}}catch(c){return this.loggingService.catch(`Error fetching RTDB data for ${t}:`,c),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(s){return this.loggingService.catch("Unexpected error in getData:",s),{}}})}dbListener({feature:t,properties:i}){let o=this.shouldUseFirestore();i?.skipFirestore&&(o=!1);let s=`${t}-${JSON.stringify(i)}`;return ti([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Rt(a=>!!a))]).pipe(Rt(([a,c])=>a?o&&!c?(this.loggingService.warn(`[WB] Firestore requested but not available for ${t}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${t}`),!1)),pt(([a,c])=>{try{if(o&&c){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleFirestoreListener(t,i,c).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.firestoreSubscriptions[s]=d}return new pe(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.firestoreSubscriptions[s]?.unsubscribe(),delete this.firestoreSubscriptions[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache[s]))}})}else if(a){if(!!!this.observablesCache[s]){this.observablesCache[s]={subject:new Y({}),count:0};let d=this.handleRealtimeDbListener(t,i,a).subscribe(f=>{this.observablesCache[s]?.subject?.next(f)},f=>this.observablesCache[s]?.subject?.error(f));this.rtdbSubscriptions[s]=d}return new pe(u=>{let d=this.observablesCache[s]?.subject?.subscribe(f=>u.next(f),f=>u.error(f),()=>u.complete());return this.observablesCache[s].count+=1,()=>{d?.unsubscribe(),this.observablesCache[s]&&(this.observablesCache[s].count-=1,this.observablesCache[s].count<=0&&(this.rtdbSubscriptions[s]?.unsubscribe(),delete this.rtdbSubscriptions?.[s],this.observablesCache[s]?.subject?.complete(),delete this.observablesCache?.[s]))}})}return de({})}catch(l){return this.loggingService.catch(`Error setting up listener for ${t}:`,l),de({})}}),Lc(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${t} and key ${s}`)}))}handleFirestoreListener(t,i,o){let s=i?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:i,documentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()}),a=`${t}-${JSON.stringify(i)}`;return s?new pe(c=>{let l=i.isCollection?this.setupCollectionListener(o,s,t,c,i):this.setupDocumentListener(o,s,t,c,i);return()=>{c.complete(),c.unsubscribe(),l(),this.observablesCache[a]?.subject?.complete(),this.observablesCache[a]?.subject?.unsubscribe(),delete this.observablesCache[a]}}).pipe(pt(c=>this.commonDbUtilsService.mergeUsersWithData$({feature:t,data:c})),pt(c=>["allComments","allUserNotifications"].includes(t)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:c,feature:t}):de(c)),pt(c=>["allReactions"].includes(t)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:c,feature:t}):de(c)),pt(c=>["allRecorders"].includes(t)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:c,feature:t}):de(c)),rt(Pt)):(this.loggingService.warn(`[WB] No firestore path found for ${t} and key ${a}`),de({}))}setupCollectionListener(t,i,o,s,a){let c=`${o}-${JSON.stringify(a)}`,l=this.dbAdapter.firestoreCollection(t,i);if(a?.useCollectionGroup&&(l=this.dbAdapter.firestoreCollectionGroup(t,i)),a?.useQuery&&a?.firestoreQuery){let f=a?.firestoreQuery??[];l=this.dbAdapter.firestoreQuery(l,...f)}let u=!0,d=[];return o==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",i,"feature:",o,"properties:",JSON.stringify(a??"nil")),this.dbAdapter.firestoreOnSnapshot(l,f=>{try{let g=JSON.parse(JSON.stringify(this.observablesCache[c]?.subject?.getValue()?.data??{})),p=null,_=!1;f?.docChanges()?.length?f.docChanges().forEach(T=>{["allComments","allReactions","allRecorders"].includes(o)&&!u&&T.type!=="removed"&&d.push(T.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:o,change:T,cache:this.observablesCache[c]?.subject?.getValue()?.data??{}})||(_=!0,Object.assign(g,this.handleCollectionChange(T,g)),T.type==="removed"&&(p||(p={type:T.type,ids:[]}),p.ids.push(T.doc.id)))}):_=!0,_&&(["allComments","allReactions","allRecorders"].includes(o)&&d?.length&&(this.commonDbUtilsService.resolveAnnotations({data:d,feature:o}),d=[]),this.commonDbUtilsService.modifyAndSetData({feature:o,data:g,subscriber:s,operation:p})),u=!1}catch(g){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,g),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(g,o,s)}},f=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${o}:`,f),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(a??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(f,o,s)})}handleCollectionChange(t,i){switch(t.type){case"added":case"modified":i[t.doc.id]=t.doc.data();break;case"removed":delete i?.[t.doc.id];break}return i}setupDocumentListener(t,i,o,s,a){let c=this.dbAdapter.firestoreDoc(t,i);return this.dbAdapter.firestoreOnSnapshot(c,l=>{try{let u=l.data()||{};a?.field&&(u=u?.[a?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:o,data:u,subscriber:s,operation:null})}catch(u){this.handleListenerError(u,o,s)}},l=>this.handleListenerError(l,o,s))}handleListenerError(t,i,o){this.loggingService.catch(`Firestore listener error for ${i}:`,t)}handleRealtimeDbListener(t,i,o){let s=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey()});if(!s)return this.loggingService.warn(`[WB] No database path found for ${t}`),de({});let a=this.realtimeAdapter.rtdbRef(o,s);if(i?.useQuery&&i?.rtdbQuery){let c=i?.rtdbQuery??[];a=this.realtimeAdapter.rtdbQueryRef(a,...c)}return this.objectValFromChildEvents(a,t).pipe(as(c=>(this.loggingService.catch(`RTDB listener error for ${t}:`,c),de({}))),ge(c=>(c===null&&(c={}),c&&typeof c=="object"?Object.entries(c??{}).reduce((u,[d,f])=>(u[d]=this.commonDbUtilsService.addMetadata(f,i),u),{}):this.commonDbUtilsService.addMetadata(c,i))),pt(c=>this.commonDbUtilsService.modifyData({feature:t,data:c})),pt(c=>this.usersService.getUserById$().pipe(ge(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:t,data:c}),operation:null})))))}pushData(s){return I(this,arguments,function*({feature:t,properties:i,data:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${t}`,"color: green;"),this.performDatabaseOperation(t,i,a=>I(this,null,function*(){if(a.dbRef){let c=this.realtimeAdapter.rtdbPush(t,a.dbRef);yield this.realtimeAdapter.rtdbSet(t,c,JSON.parse(JSON.stringify(a.data)))}}),o)}catch(a){this.loggingService.catch(`Error in pushData for ${t}`,a)}})}streamChildAdded({feature:t,properties:i,afterTs:o}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${t}`,"color: green;"),new pe(s=>{let a=null,c=!1,l=({db:u})=>{if(!u||c||!this.authService.getUser())return;let d=this.commonDbUtilsService.getDocumentPath({feature:t,properties:i,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:i.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!d)return;let g=this.realtimeAdapter.rtdbRef(u,d),p=!1,_=L=>{try{let B=L.val();if(p){if(o!=null&&B?.timestamp!=null&&B.timestamp<=o)return;s.next(B)}}catch(B){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${t}:`,B)}},T=L=>{try{this.loggingService.catch(`streamChildAdded error for ${t}:`,L),s.error(L)}catch(B){this.loggingService.catch(`streamChildAdded onError handler error for ${t}:`,B)}};this.realtimeAdapter.rtdbOnChildAdded(t,g,_,T);let D=this.realtimeAdapter.rtdbOnValue(t,g,()=>{p=!0},T,{onlyOnce:!0});a=()=>{try{D&&typeof D=="function"&&D(),this.realtimeAdapter.rtdbOff(g,"child_added",_)}catch(L){this.loggingService.catch(`streamChildAdded cleanup error for ${t}:`,L)}}};return this.subscribeToServices(l),()=>{c=!0,a&&a()}})}catch(s){return this.loggingService.catch(`Error in streamChildAdded for ${t}`,s),de(null)}}objectValFromChildEvents(t,i){return new pe(o=>{let s={},a=!1,c=null,l=T=>{try{this.loggingService.catch(`Realtime DB listener error for ${i}:`,T),o.error(T)}catch{}},u=T=>{try{if(!Ui(T,c)){let D=JSON.parse(JSON.stringify(T));c=D,o.next(D)}}catch{}},d=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(M({},s)))}catch{}},f=T=>{try{T.key&&(s[T.key]=T.val(),a&&u(M({},s)))}catch{}},g=T=>{try{T.key&&(delete s[T.key],a&&u(M({},s)))}catch{}},p=T=>{try{if(!a){let D=s&&typeof s=="object"?JSON.parse(JSON.stringify(s)):{};c=D,o.next(D),a=!0}}catch{}};this.realtimeAdapter.rtdbOnChildAdded(i,t,d,l),this.realtimeAdapter.rtdbOnChildChanged(i,t,f,l),this.realtimeAdapter.rtdbOnChildRemoved(i,t,g,l);let _=this.realtimeAdapter.rtdbOnValue(i,t,p,l,{onlyOnce:!0});return()=>{try{_&&typeof _=="function"&&_(),this.realtimeAdapter.rtdbOff(t,"child_added",d),this.realtimeAdapter.rtdbOff(t,"child_changed",f),this.realtimeAdapter.rtdbOff(t,"child_removed",g)}catch{}}})}};e.\u0275fac=function(i){return new(i||e)(C(dS),C(Dr),C(Nz),C(vt),C(me),C(gS),C(cc),C(Xn),C(ef),C(jt),C(qo),C(Ko),C(lc),C(fS),C(di),C(bz),C(Lz),C(Mz))},e.\u0275prov=K({token:e,factory:e.\u0275fac,providedIn:"root"});let r=e;return r})();export{M as a,le as b,NS as c,aae as d,cae as e,lae as f,I as g,mt as h,pe as i,jS as j,Ct as k,Y as l,Mc as m,k6 as n,U6 as o,Oc as p,Mr as q,de as r,V6 as s,B6 as t,A6 as u,ge as v,ti as w,iA as x,G6 as y,fo as z,K6 as A,Ni as B,_6 as C,ju as D,Rt as E,c6 as F,as as G,VS as H,Mu as I,Dt as J,$S as K,rt as L,Pu as M,AE as N,WS as O,T6 as P,zS as Q,I6 as R,xu as S,pt as T,Zs as U,v6 as V,ea as W,y6 as X,D6 as Y,oe as Z,zE as _,K as $,us as aa,ee as ba,C as ca,J as da,pr as ea,zn as fa,go as ga,F0 as ha,k0 as ia,K0 as ja,Y0 as ka,lt as la,In as ma,sr as na,Pr as oa,Io as pa,Jc as qa,ni as ra,D4 as sa,un as ta,rD as ua,W4 as va,ha as wa,C_ as xa,j_ as ya,Z4 as za,Lq as Aa,Mq as Ba,Pq as Ca,xq as Da,Fq as Ea,Zq as Fa,gs as Ga,we as Ha,a8 as Ia,Q8 as Ja,X8 as Ka,So as La,tg as Ma,Es as Na,nT as Oa,dt as Pa,a5 as Qa,Do as Ra,rl as Sa,Ak as Ta,K5 as Ua,fa as Va,Co as Wa,rg as Xa,bk as Ya,i9 as Za,Mk as _a,Pk as $a,oT as ab,ga as bb,Bk as cb,Gk as db,d9 as eb,f9 as fb,g9 as gb,m9 as hb,p9 as ib,E9 as jb,_9 as kb,$k as lb,$D as mb,jD as nb,jk as ob,HD as pb,WD as qb,Hk as rb,zD as sb,qD as tb,zk as ub,A9 as vb,qk as wb,Yk as xb,Qk as yb,O9 as zb,w9 as Ab,L9 as Bb,P9 as Cb,x9 as Db,F9 as Eb,k9 as Fb,U9 as Gb,V9 as Hb,B9 as Ib,nU as Jb,rU as Kb,Z9 as Lb,tK as Mb,dK as Nb,hU as Ob,KD as Pb,fU as Qb,gU as Rb,mU as Sb,mK as Tb,pU as Ub,_U as Vb,pK as Wb,EK as Xb,_K as Yb,TK as Zb,AK as _b,RK as $b,DK as ac,CK as bc,NK as cc,OK as dc,bK as ec,wK as fc,LK as gc,MK as hc,PK as ic,xK as jc,kK as kc,VK as lc,BK as mc,GK as nc,$K as oc,jK as pc,zK as qc,lg as rc,ug as sc,ZD as tc,Uye as uc,Vye as vc,Bye as wc,yY as xc,dC as yc,Gye as zc,$ye as Ac,jye as Bc,No as Cc,YU as Dc,jY as Ec,h1 as Fc,HY as Gc,_C as Hc,WY as Ic,zY as Jc,qY as Kc,KY as Lc,QY as Mc,JY as Nc,e7 as Oc,TC as Pc,AT as Qc,RT as Rc,p7 as Sc,T7 as Tc,x1 as Uc,j7 as Vc,H7 as Wc,wC as Xc,q1 as Yc,xC as Zc,kd as _c,$r as $c,Ta as ad,uI as bd,gl as cd,vr as dd,Be as ed,fn as fd,lr as gd,Po as hd,yr as id,Sa as jd,Sr as kd,Ke as ld,$X as md,TLe as nd,ILe as od,vLe as pd,Gi as qd,Aa as rd,Ns as sd,$i as td,_e as ud,ji as vd,Os as wd,VLe as xd,BLe as yd,GLe as zd,Da as Ad,dZ as Bd,fZ as Cd,DZ as Dd,Il as Ed,vl as Fd,SPe as Gd,APe as Hd,lxe as Id,Kre as Jd,uxe as Kd,Yre as Ld,Qre as Md,Xre as Nd,ur as Od,$Pe as Pd,jPe as Qd,HPe as Rd,Q1 as Sd,lQ as Td,Og as Ud,dn as Vd,j as Wd,ye as Xd,Qt as Yd,cRe as Zd,lRe as _d,uRe as $d,dRe as ae,H as be,hRe as ce,fRe as de,gRe as ee,mRe as fe,q7 as ge,K7 as he,Y7 as ie,Q7 as je,MT as ke,X7 as le,pRe as me,J7 as ne,LC as oe,Z7 as pe,Br as qe,PT as re,eQ as se,Ad as te,Mt as ue,tQ as ve,xT as we,nQ as xe,rQ as ye,iQ as ze,ERe as Ae,_Re as Be,TRe as Ce,oQ as De,v as Ee,H1 as Fe,XRe as Ge,Cd as He,tDe as Ie,nDe as Je,hi as Ke,Nt as Le,X1 as Me,J1 as Ne,wDe as Oe,LDe as Pe,qT as Qe,FC as Re,KT as Se,Ln as Te,Ea as Ue,Oo as Ve,nV as We,rV as Xe,iV as Ye,As as Ze,rCe as _e,Qn as $e,ki as af,oV as bf,sV as cf,aV as df,cV as ef,lV as ff,uV as gf,dV as hf,hV as if,fV as jf,gV as kf,mV as lf,VCe as mf,BCe as nf,pV as of,VC as pf,EV as qf,_V as rf,IV as sf,TNe as tf,Rs as uf,uQ as vf,dQ as wf,vbe as xf,FV as yf,kV as zf,Lbe as Af,Tr as Bf,fi as Cf,_a as Df,Ds as Ef,bo as Ff,Mbe as Gf,Pbe as Hf,xbe as If,Fbe as Jf,kbe as Kf,Ube as Lf,VV as Mf,BV as Nf,Vbe as Of,Bbe as Pf,jC as Qf,GV as Rf,Gbe as Sf,$be as Tf,$V as Uf,Z as Vf,jbe as Wf,jV as Xf,Ld as Yf,bV as Zf,wV as _f,fQ as $f,gQ as ag,hl as bg,HC as cg,Hbe as dg,wo as eg,Wbe as fg,Mg as gg,Ui as hg,zbe as ig,WC as jg,dl as kg,EQ as lg,tI as mg,qbe as ng,Kbe as og,WV as pg,Pg as qg,_Q as rg,TQ as sg,IQ as tg,vQ as ug,yQ as vg,Gr as wg,Ybe as xg,GC as yg,Qbe as zg,AQ as Ag,Xbe as Bg,Jbe as Cg,qV as Dg,Zbe as Eg,ewe as Fg,twe as Gg,nwe as Hg,rwe as Ig,iwe as Jg,owe as Kg,eI as Lg,swe as Mg,awe as Ng,cwe as Og,lwe as Pg,uwe as Qg,dwe as Rg,hwe as Sg,fwe as Tg,gwe as Ug,mwe as Vg,pwe as Wg,Ewe as Xg,_we as Yg,Twe as Zg,Iwe as _g,vwe as $g,ywe as ah,Swe as bh,Awe as ch,Rwe as dh,Dwe as eh,Cwe as fh,Nwe as gh,Owe as hh,bwe as ih,NQ as jh,wwe as kh,Lwe as lh,Mwe as mh,MV as nh,Pwe as oh,xwe as ph,Pt as qh,yn as rh,Fwe as sh,xt as th,$t as uh,OQ as vh,ZV as wh,Md as xh,qC as yh,Ir as zh,kwe as Ah,PV as Bh,P as Ch,Rr as Dh,FT as Eh,ARe as Fh,RRe as Gh,Fi as Hh,DRe as Ih,kT as Jh,CRe as Kh,NRe as Lh,UT as Mh,ORe as Nh,VT as Oh,bRe as Ph,BT as Qh,wRe as Rh,ui as Sh,LRe as Th,Rd as Uh,MRe as Vh,PRe as Wh,xRe as Xh,FRe as Yh,kRe as Zh,URe as _h,VRe as $h,GT as ai,BRe as bi,GRe as ci,$T as di,jT as ei,B1 as fi,G1 as gi,$1 as hi,di as ii,Ot as ji,me as ki,Xn as li,Jee as mi,i0e as ni,xo as oi,aj as pi,vt as qi,Ov as ri,bv as si,Dr as ti,rS as ui,zse as vi,qse as wi,Kse as xi,Yse as yi,Ii as zi,cc as Ai,qo as Bi,Ko as Ci,Zh as Di,lc as Ei,ef as Fi,jt as Gi,cS as Hi,lS as Ii,dS as Ji,hS as Ki,vz as Li,fS as Mi,Nz as Ni,bz as Oi,p1e as Pi};