@veltdev/sdk 6.0.28 → 6.0.29

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 (60) hide show
  1. package/{chunk-3BCXNETY.js → chunk-2DMVX6Z3.js} +1 -1
  2. package/{chunk-JWSICAW6.js → chunk-2YDGTFZM.js} +1 -1
  3. package/{chunk-KNYRVMQK.js → chunk-333ZBMSE.js} +1 -1
  4. package/{chunk-4HAFXUDN.js → chunk-35XJQZ27.js} +1 -1
  5. package/chunk-4H2TOH52.js +1 -0
  6. package/{chunk-VESMHAEV.js → chunk-4QGCX4EY.js} +4 -4
  7. package/{chunk-VJPZ6E4S.js → chunk-5TCVSBJS.js} +1 -1
  8. package/{chunk-URKI6WZP.js → chunk-7DF5ZYSM.js} +1 -1
  9. package/{chunk-XEXFF5FD.js → chunk-7DTEJ3JT.js} +1 -1
  10. package/{chunk-JZCDUWAA.js → chunk-7K4EA6Y5.js} +1 -1
  11. package/{chunk-YBLQ2JHR.js → chunk-7WHI6IHH.js} +1 -1
  12. package/{chunk-MP2SDO2E.js → chunk-7ZSEYX3G.js} +1 -1
  13. package/{chunk-3Q5TRC4E.js → chunk-AOKM7YOQ.js} +1 -1
  14. package/{chunk-R7EWRVMV.js → chunk-ASGMGCYI.js} +1 -1
  15. package/{chunk-CR275X25.js → chunk-BG6LRF5O.js} +1 -1
  16. package/{chunk-SYLJZSJP.js → chunk-BRCK225M.js} +1 -1
  17. package/{chunk-J3IQ7DYW.js → chunk-CRKE5XUX.js} +1 -1
  18. package/{chunk-EB7SHB2S.js → chunk-DHVECNH4.js} +1 -1
  19. package/{chunk-RPLZXBLF.js → chunk-DJPCTT4F.js} +1 -1
  20. package/{chunk-J35LMO3C.js → chunk-EQWU2DL7.js} +1 -1
  21. package/{chunk-ZRITZXNF.js → chunk-ESMJKCYM.js} +1 -1
  22. package/{chunk-R7PIAWZF.js → chunk-FQILN45X.js} +1 -1
  23. package/{chunk-67RGQF3Z.js → chunk-M6J3KGG7.js} +1 -1
  24. package/{chunk-SN6HOFPK.js → chunk-MFXS56C3.js} +1 -1
  25. package/{chunk-IS7ZDK65.js → chunk-MW45OPL7.js} +1 -1
  26. package/chunk-OITZJHUL.js +1 -0
  27. package/{chunk-JQZKADOA.js → chunk-PRURFNVL.js} +1 -1
  28. package/{chunk-TSC5TWPQ.js → chunk-Q3RXGMSF.js} +1 -1
  29. package/{chunk-TLEK2ADO.js → chunk-QXHO6I75.js} +1 -1
  30. package/{chunk-HIEV42PB.js → chunk-RIQYRZB7.js} +1 -1
  31. package/{chunk-HCM2TAE7.js → chunk-STGE6CFR.js} +1 -1
  32. package/{chunk-5ACPKO6C.js → chunk-T6YEK2X2.js} +1 -1
  33. package/{chunk-GHN6NWBT.js → chunk-TU6L6SDC.js} +1 -1
  34. package/{chunk-4P3GYHGY.js → chunk-XZCIYLEI.js} +1 -1
  35. package/{chunk-GAWI762G.js → chunk-ZADJEDZT.js} +1 -1
  36. package/{chunk-N3IQEYGG.js → chunk-ZAORQEEC.js} +1 -1
  37. package/package.json +1 -1
  38. package/velt-activity-log.js +1 -1
  39. package/velt-area.js +1 -1
  40. package/velt-arrow.js +1 -1
  41. package/velt-comment.js +6 -6
  42. package/velt-crdt.js +1 -1
  43. package/velt-cursor.js +1 -1
  44. package/velt-huddle.js +1 -1
  45. package/velt-live-state-sync.js +1 -1
  46. package/velt-notification.js +1 -1
  47. package/velt-portable.js +1 -1
  48. package/velt-presence.js +1 -1
  49. package/velt-reaction.js +1 -1
  50. package/velt-recorder.js +1 -1
  51. package/velt-rewriter.js +1 -1
  52. package/velt-selection.js +1 -1
  53. package/velt-tag.js +1 -1
  54. package/velt-user-invite.js +1 -1
  55. package/velt-user-request.js +1 -1
  56. package/velt-video-player.js +1 -1
  57. package/velt-views.js +1 -1
  58. package/velt.js +2 -2
  59. package/chunk-FWIDRPYU.js +0 -1
  60. package/chunk-NTFMMZRZ.js +0 -1
package/velt-views.js CHANGED
@@ -1,3 +1,3 @@
1
- import{t as dt}from"./chunk-4HAFXUDN.js";import"./chunk-CR275X25.js";import"./chunk-SN6HOFPK.js";import{a as We,c as Je,d as Ke}from"./chunk-J3IQ7DYW.js";import{a as gt}from"./chunk-FWIDRPYU.js";import"./chunk-J35LMO3C.js";import{a as ct}from"./chunk-JWSICAW6.js";import{a as pt}from"./chunk-TLEK2ADO.js";import"./chunk-KNYRVMQK.js";import"./chunk-5ACPKO6C.js";import{b as st,d as lt}from"./chunk-3BCXNETY.js";import{a as mt}from"./chunk-ZRITZXNF.js";import{a as je}from"./chunk-SYLJZSJP.js";import{A as Pe,Fa as rt,G as Ne,H as Le,Ha as at,I as Me}from"./chunk-GHN6NWBT.js";import{a as ut}from"./chunk-67RGQF3Z.js";import{D as ot,E as pe,j as ge}from"./chunk-NTFMMZRZ.js";import{Aj as Se,Bb as x,E as B,Fj as z,G as De,Gd as Re,Ha as w,Hc as ze,He as E,Hi as ye,Ia as re,Ic as le,Ij as tt,K as te,Kb as ae,Ki as Ze,M as q,Mb as se,O as xe,Pb as _,Pj as it,Qb as K,Ra as I,Rb as j,Rc as Fe,Tb as Te,U as _e,V as S,Va as Ue,Vd as qe,Wa as Q,Wd as Ge,Xa as ke,Y as Ee,Zf as we,Zi as fe,_ as ie,a as m,ab as T,b as h,ba as Oe,ca as Be,cc as $e,ci as Qe,ea as k,ei as de,g as R,ja as P,ka as N,kj as Xe,l as $,la as H,ma as Y,mc as A,nb as D,nc as U,nj as me,ob as v,pb as y,pj as C,qb as L,qe as He,qj as et,r as b,rc as ce,rk as ue,sa as ne,sk as nt,t as Ce,ub as G,v as f,vb as W,w as Z,wa as Ae,xb as J,ya as oe,yg as Ye,zb as M}from"./chunk-VESMHAEV.js";function vt(c){return c?{field:"metadata.veltFolderId",value:c}:null}function ht(c,l){if(!l||!c||typeof c!="object")return c;let r={};for(let e of Object.keys(c)){let t=c[e]?.metadata;(!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"veltFolderId"))||t.veltFolderId===l.value)&&(r[e]=c[e])}return r}var F=(()=>{let l=class l{constructor(e,t,n,i,o,s,d,a,g,p){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=s,this.iamService=d,this.loggingService=a,this.userPermissionService=g,this.serviceBook=p,this.documentPaths=null,this.views$=new $({}),this.commentViews$=new $({}),this.documentViews$=new $({}),this.locationViews$=new $({}),this.commentViewsByOrganizationIdAndDocumentId$=new $({}),this.documentViewsByOrganizationIdAndDocumentId$=new $({}),this.locationViewsByOrganizationIdAndLocationId$=new $({}),this.documentViewsEnabled$=new $(!1),this.documentViewsSetByDocumentId={},this.notificationService=null,this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.serviceBook.observe(fe).subscribe(u=>{this.commentService=u??void 0}),this.serviceBook.observe(Ze).subscribe(u=>{this.notificationService=u??null}),this.viewsDbReadyGate$().pipe(te(1)).subscribe(()=>{this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(u=>{this.notificationService?.setNotificationViews(u)}),this.authService.getUser$().pipe(B(u=>!!u),S(u=>this.documentViewsEnabled$.pipe(B(V=>V),f(()=>u))),S(u=>this.docService.getDocumentPaths$().pipe(_e(null),xe(),f(([V,O])=>(V?.documentId!==O?.documentId&&this.views$.next({}),O)),f(V=>(this.documentPaths=V,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:u,_documentPaths:V})),S(V=>this.docService.getDocumentIds$().pipe(S(O=>(O?.length&&(O.find(ee=>ee.documentId===this.documentPaths?.documentId)||O.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),O.forEach(ee=>{this.setDocumentAsRead({documentId:ee.documentId,clientDocumentId:ee.clientDocumentId})})),b(V))))))),S(u=>this.docService.getDocumentMetadata$().pipe(B(V=>!!V),f(V=>h(m({},u),{_documentMetadata:V}))))).subscribe(),this.authService.getUser$().pipe(B(u=>!!u),S(u=>this.documentViewsEnabled$.pipe(B(V=>V),f(()=>u))),S(u=>this.docService.getLocation$().pipe(B(V=>!!V))),S(u=>this.docService.getDocumentIds$().pipe(S(V=>(V.find(O=>O.documentId===this.documentPaths?.documentId)||V.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),V.forEach(O=>{this.setLocationAsRead({documentId:O.documentId,clientDocumentId:O.clientDocumentId})}),b(u)))))).subscribe()},u=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",u)})}catch(u){this.loggingService.catch("Error in ViewsService constructor: ",u)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let n,i;try{if(e&&(i=we(e)),t&&typeof t=="object"){let o=Ye(t);n=we(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(B(o=>!!o),S(o=>this.isFeatureAllowed({firebaseUser:o})),S(o=>o.featureAllowed?this.iamService.isUserAllowed$().pipe(f(s=>(o.featureAllowed=s,o))):b(o)),S(o=>o.featureAllowed?b(o).pipe(S(s=>this.docService.getDocumentPaths$().pipe(f(d=>(this.documentPaths=d,s.documentPaths=d,s)))),S(s=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(d=>{let a=d?.length>0?d.map(g=>g.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(a)})))):b([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(B(t=>!!t),f(t=>h(m({},e),{config:t})),S(t=>this.authService.getUser$().pipe(f(n=>h(m({},t),{user:n})))),S(t=>t.user?b(h(m({},t),{featureAllowed:!0})):b(h(m({},t),{featureAllowed:!1}))),q((t,n)=>t?.featureAllowed===n?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:n}=e;return t?.some(i=>!i)||!this.documentPaths?b([]):this.documentViewsEnabled$.pipe(S(i=>i?Z([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Z([this.getCommentViewsDataFromDocuments()])))}else return b(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([n,i])=>{let o=i.metadata?.documentId,s=i.views;!o||!s||(t[o]||(t[o]={}),t[o][i.annotationId]=s)}),Object.entries(t??{}).forEach(([n,i])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:n,commentViews:i})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.serviceBook.observe(fe).pipe(q(),S(e=>{if(!e)return b([]);try{return e.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,fromCommentSidebar:!0,skipPositionCalculation:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(B(t=>!!t),Ee(t=>{this.getCommentViews(t)}),De(t=>(this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",t),b([]))))}catch(t){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",t),b([])}}))}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),b([])}}viewsDbReadyGate$(){return it({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(ge),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in ViewsService viewsDbReadyGate$ ${e}: `,t)})}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=vt(t),i=b([]),o={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(o.documentId=e?.length?e[0]:void 0,o.organizationId=this.documentPaths?.organizationId),this.commonDbService.usesPortableChannelFeed(ge))i=this.commonDbService.dbListener({feature:"allDocumentViews",properties:h(m({},o),{organizationId:this.documentPaths?.organizationId,documentIds:e})}).pipe(ie(),f(s=>de(JSON.parse(JSON.stringify([s])))),f(s=>n&&s?.data?h(m({},s),{data:ht(s.data,n)}):s));else{let s=[];for(let d=0;d<(e?.length??0);d+=E.LISTENER_BATCH_SIZE)s.push(e?.slice(d,d+E.LISTENER_BATCH_SIZE)??[]);i=Z(s.map(d=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:h(m({},o),{firestoreQuery:[Se(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",d),z("metadata.organizationId","==",this.documentPaths?.organizationId),...n?[z(n.field,"==",n.value)]:[])]})}).pipe(ie()))).pipe(f(d=>de(d)))}return i.pipe(f(s=>({data:s?.data,operation:s?.operation})),f(({data:s,operation:d})=>{let a={};return e?(Object.entries(s??{}).forEach(([g,p])=>{let u=p.metadata?.documentId;u&&(a[u]||(a[u]={}),a[u][g]=p)}),{data:s,documentMap:a,operation:d}):{data:s,documentMap:a,operation:d}}),f(({data:s,documentMap:d,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let g=this.documentViews$.value;a?.ids?.forEach(p=>{delete g?.[p]}),this.documentViews$.next(g)}}else Object.entries(d??{}).forEach(([g,p])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:g,documentViews:p})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=b([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId);let o=[];for(let s=0;s<(e?.length??0);s+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(s,s+E.LISTENER_BATCH_SIZE)??[]);return n=Z(o.map(s=>this.commonDbService.dbListener({feature:"allLocationViews",properties:h(m({},i),{firestoreQuery:[Se(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",s),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(s=>de(s))),n.pipe(f(s=>({data:s?.data,operation:s?.operation})),f(({data:s,operation:d})=>{let a={};return e?(Object.entries(s??{}).forEach(([g,p])=>{let u=p.metadata?.documentId;u&&(a[u]||(a[u]={}),a[u][g]=p)}),{data:s,documentMap:a,operation:d}):{data:s,documentMap:a,operation:d}}),f(({data:s,documentMap:d,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let g=this.locationViews$.value;a?.ids?.forEach(p=>{delete g?.[p]}),this.locationViews$.next(g)}}else Object.entries(d??{}).forEach(([g,p])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:g,locationViews:p})})}))}setViewsData(e){try{this.views$.next(m(m({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.commentViews$.value),n);this.commentViews$.next(o),this.commentViewsByOrganizationIdAndDocumentId$.next(h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.documentViews$.value),n);this.documentViews$.next(o),this.documentViewsByOrganizationIdAndDocumentId$.next(h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.locationViews$.value),n);this.locationViews$.next(o),this.locationViewsByOrganizationIdAndLocationId$.next(h(m({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:h(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[t]:h(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}getCommentFeatureViews$(){return this.commentViews$.pipe(q((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return R(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.updateCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}setCommentAnnotationAsUnread(e){return R(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.removeCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{},s=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(a=>{o[a.commentId]||(o[a.commentId]={views:{}}),o[a.commentId].views||(o[a.commentId].views={}),o[a.commentId].views[t.userSnippylyId]||(o[a.commentId].views[t.userSnippylyId]={timestamp:s})});let d=new Set(e.comments?.map(a=>a.commentId+""));if(Object.keys(o??{}).forEach(a=>{d.has(a)||delete o[a]}),e.comments?.length){let a=o[e.comments[0].commentId]?.views||{},g=Object.keys(a??{}).filter(p=>e.comments?.every(u=>o[u.commentId]?.views?.[p]));g.forEach(p=>{i[p]={timestamp:a[p].timestamp}}),e.viewedByUserIds=g}n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}removeCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{};e.comments?.forEach(d=>{o[d.commentId]?.views?.[t.userSnippylyId]&&delete o[d.commentId].views[t.userSnippylyId]});let s=new Set(e.comments?.map(d=>d.commentId+""));if(Object.keys(o??{}).forEach(d=>{s.has(d)||delete o[d]}),e.comments?.length){let d=o[e.comments[0].commentId]?.views||{},a=Object.keys(d??{}).filter(g=>e.comments?.every(p=>o[p.commentId]?.views?.[g]));a.forEach(g=>{i[g]={timestamp:d[g].timestamp}}),e.viewedByUserIds=a}else e.viewedByUserIds=[];n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService removeCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(q((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let n=new Date().getTime()+this.commonDbService.getOffset();e.forEach(i=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:i,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:n}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(q((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.users||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.users||{}:{}})))),q(Qe))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),b({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.day||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.day||{}:{}})))))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),b({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(n){return R(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser();if(i&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let o=new Date().getTime()+this.commonDbService.getOffset(),s=new Date().toISOString().split("T")[0];if(this.commonDbService.usesPortableChannelFeed(ge)){let a=yield Ce(this.docService.getDocumentPaths$().pipe(f(g=>g?.organizationId),B(g=>!!g)));yield this.commonDbService.whenPortableRealtimeReady(),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:a},data:{}}),this.checkAndTriggerNotification(i);return}let d=this.getDocumentViewsById(e);if(d){let a=new Date().toISOString().split("T")[0];d?.users[i.userSnippylyId]||(d.users[i.userSnippylyId]={}),d.users[i.userSnippylyId][a]={timestamp:this.timestamp},d?.day[a]||(d.day[a]={}),d.day[a][i.userSnippylyId]={timestamp:this.timestamp},d.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:d})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:i.userSnippylyId,date:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})}),this.docService.getDocumentMetadata$(e).pipe(B(a=>a!==null),te(1)).subscribe(()=>{let a={day:{[s]:{[i.userSnippylyId]:{timestamp:o}}},users:{[i.userSnippylyId]:{[s]:{timestamp:o}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:a})});this.checkAndTriggerNotification(i)}}catch(i){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",i)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(te(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let n=this.docService.getDocumentMetadata();if(n?.creator?.email&&n?.creator?.email!==e.email){let i=[n.creator.email];this.updateNotificationsDatabase(He.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return R(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),s=o?.locationId,d=o?.location;if(i&&s&&d){let a=new Date().getTime()+this.commonDbService.getOffset(),g=new Date().toISOString().split("T")[0],p=this.getLocationViewsById(s);if(p){let u=new Date().toISOString().split("T")[0];p?.users[i.userSnippylyId]||(p.users[i.userSnippylyId]={}),p.users[i.userSnippylyId][u]={timestamp:this.timestamp},p?.day[u]||(p.day[u]={}),p.day[u][i.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:p,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:d,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:s,user:i.userSnippylyId,date:g,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:a}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:s,date:g,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:a}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let u={day:{[g]:{[i.userSnippylyId]:{timestamp:a}}},users:{[i.userSnippylyId]:{[g]:{timestamp:a}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:d};this.commonDbService.updateData({feature:"location",data:u,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(i){this.loggingService.catch("Error in ViewsService setLocationAsRead:",i)}})}updateNotificationsDatabase(e,t={}){try{let n=m({actionType:e,notificationSource:"documentViews"},t);this.notificationService?.updateNotificationDatabase(n)}catch(n){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",n)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};l.\u0275fac=function(t){return new(t||l)(k(Re),k(nt),k(et),k(tt),k(pe),k(ot),k(mt),k(C),k(gt),k(me))},l.\u0275prov=Oe({token:l,factory:l.\u0275fac,providedIn:"root"});let c=l;return c})();function Vt(c,l){if(c&1&&(G(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),y(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),y()(),v(8,"div",26),_(9),A(10,"timeAgo"),y()(),W()),c&2){let r=l.$implicit;w(3),D("user",r==null?null:r.user)("size",32),w(3),j(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),w(3),j(" ",U(10,6,r==null?null:r.timestamp)," ")}}function It(c,l){if(c&1&&(v(0,"div",19),T(1,Vt,11,8,"ng-container",20),y()),c&2){let r=x(2).ngIf;w(),D("ngForOf",r.userViews)}}function Ct(c,l){if(c&1){let r=J();G(0),v(1,"div",4)(2,"button",5),M("click",function(){P(r);let t=x(2);return N(t.closeTrendDialog())}),H(),v(3,"svg",6),L(4,"path",7),y(),Y(),v(5,"span"),_(6),A(7,"translate"),y()()(),v(8,"div",8)(9,"div",9)(10,"div",10),_(11),y(),v(12,"div",11),H(),v(13,"svg",12),L(14,"path",13)(15,"path",14),y(),Y(),v(16,"span"),_(17),A(18,"translate"),y()()(),v(19,"div",15)(20,"div",16),_(21),y(),v(22,"div",17)(23,"span"),_(24),A(25,"translate"),y()()()(),T(26,It,2,1,"div",18),W()}if(c&2){let r=x().ngIf;w(6),K(U(7,6,"Go Back")),w(5),j(" ",r.totalUniqueViewsCount," "),w(6),K(U(18,8,"Total Views")),w(4),j(" ",r.todayViewsCount," "),w(3),K(U(25,10,"Views Today")),w(2),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Dt(c,l){if(c&1&&(G(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),y(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),y(),v(8,"div",26),_(9),A(10,"timeAgo"),y()()(),W()),c&2){let r=l.$implicit;w(3),D("user",r==null?null:r.user)("size",32),w(3),j(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),w(3),j(" ",U(10,6,r==null?null:r.timestamp)," ")}}function xt(c,l){if(c&1&&(v(0,"div",29)(1,"div",19),T(2,Dt,11,8,"ng-container",20),y()()),c&2){let r=x(2).ngIf;w(2),D("ngForOf",r.userViews)}}function _t(c,l){if(c&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),_(3),y(),v(4,"div",11),H(),v(5,"svg",12),L(6,"path",13)(7,"path",14),y(),Y(),v(8,"span"),_(9),A(10,"translate"),y()()(),v(11,"div",15),_(12),A(13,"translate"),A(14,"translate"),A(15,"translate"),y()(),T(16,xt,3,1,"div",28)),c&2){let r=x().ngIf;w(3),j(" ",r.totalUniqueViewsCount," "),w(6),K(U(10,6,"Total Views")),w(3),Te(" ",r.todayViewsCount," ",r.todayViewsCount===1?U(13,8,"View"):U(14,10,"Views")," ",U(15,12,"Today")," "),w(4),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Et(c,l){if(c&1){let r=J();G(0),v(1,"div",2),M("clickOutside",function(){P(r);let t=x();return N(t.closeTrendDialog())}),T(2,Ct,27,12,"ng-container",3)(3,_t,17,14,"ng-template",null,0,ce),y(),W()}if(c&2){let r=l.ngIf,e=ae(4);w(),se("bottom-sheet",r.bottomSheetMode),w(),D("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var X=(()=>{let l=class l{constructor(e,t,n,i,o,s,d){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=s,this.bottomSheetData=d,this.close=new re,this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,views:{},usersMap:{},userViews:[],bottomSheetMode:!1}),this.subscriptions=[];try{d&&(this.componentConfigSignal.update(a=>(a=h(m({},a),{bottomSheetMode:!0}),a)),this.clientLocationId=d.clientLocationId,this.closeBottomSheetFn=d.closeBottomSheetFn),this.subscriptions.push(this.contactService.getUsersMap$().subscribe(a=>{this.componentConfigSignal.update(g=>(g=h(m({},g),{usersMap:a||{}}),g)),this.setLatestViewsByUsers()},a=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUsersMap$ subscription: ",a)})),this.subscriptions.push(this.themeService.getDarkMode$().subscribe(a=>{a?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark")}))}catch(a){this.loggingService.catch("Error in ViewAnalyticsDialogComponent constructor: ",a)}}ngOnInit(){this.getDocumentViews()}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngAfterViewInit: ",e)}}trackByUserIdAndTimestamp(e,t){return`${t?.user?.userSnippylyId}-${t.timestamp}`}getDocumentViews(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(e=>(e=h(m({},e),{totalUniqueViews:{},totalUniqueViewsCount:0}),e)),this.uniqueViewsByUserSubscription.unsubscribe()),this.uniqueViewsByDateSubscription&&(this.componentConfigSignal.update(e=>(e=h(m({},e),{todayViews:{},todayViewsCount:0}),e)),this.uniqueViewsByDateSubscription.unsubscribe()),this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=h(m({},t),{totalUniqueViews:e||{},totalUniqueViewsCount:Object.keys(e||{})?.length||0}),t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByUser subscription: ",e)}),this.uniqueViewsByDateSubscription=this.viewsService.getUniqueViewsByDate(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.todayViews=e&&e[t.today]?e[t.today]:{},t.todayViewsCount=Object.keys(t.todayViews||{})?.length||0,t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByDate subscription: ",e)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent getDocumentViews: ",e)}}setLatestViewsByUsers(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLatestViewsByUsers","color: green;"),Object.keys(this.componentConfigSignal().todayViews||{}).forEach(e=>{let t=this.componentConfigSignal().usersMap[e],n=this.componentConfigSignal().todayViews[e]?.timestamp;t&&n&&(this.componentConfigSignal().userViews.find(o=>o.user.userSnippylyId===e)||this.componentConfigSignal.update(o=>(o=h(m({},o),{userViews:[...o.userViews,{user:t,timestamp:n}]}),o)))}),this.componentConfigSignal.update(e=>(e=m({},e),e.userViews.sort((t,n)=>n.timestamp-t.timestamp),e.userViews=e.userViews.slice(0,3),e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent setLatestViewsByUsers: ",e)}}closeTrendDialog(){try{this.close.emit(),this.closeBottomSheetFn&&this.closeBottomSheetFn?.()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()}),this.uniqueViewsByDateSubscription?.unsubscribe(),this.uniqueViewsByUserSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngOnDestroy: ",e)}}};l.\u0275fac=function(t){return new(t||l)(I(rt),I(C),I(F),I(at),I(oe),I(ue),I(We,8))},l.\u0275cmp=Q({type:l,selectors:[["velt-view-analytics-dialog"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:1,vars:1,consts:[["defaultDialogRef",""],[4,"ngIf"],["snippylyClickOutside","",1,"v-view-analytics-dialog-container",3,"clickOutside"],[4,"ngIf","ngIfElse"],[1,"v-back-btn-container"],[1,"v-back-btn",3,"click"],["width","16","height","16","viewBox","0 0 16 16","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M9.99988 4L5.99988 8L9.99988 12","stroke","currentColor","stroke-width","1.33333","stroke-linecap","round","stroke-linejoin","round"],[1,"v-view-analytics-count-container"],[1,"v-total-views-container"],[1,"v-total-views-count"],[1,"v-total-views-text"],["width","18","height","18","viewBox","0 0 18 18","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M7.5 9C7.5 9.39782 7.65804 9.77936 7.93934 10.0607C8.22064 10.342 8.60218 10.5 9 10.5C9.39782 10.5 9.77936 10.342 10.0607 10.0607C10.342 9.77936 10.5 9.39782 10.5 9C10.5 8.60218 10.342 8.22064 10.0607 7.93934C9.77936 7.65804 9.39782 7.5 9 7.5C8.60218 7.5 8.22064 7.65804 7.93934 7.93934C7.65804 8.22064 7.5 8.60218 7.5 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],["d","M15.75 9C13.95 12 11.7 13.5 9 13.5C6.3 13.5 4.05 12 2.25 9C4.05 6 6.3 4.5 9 4.5C11.7 4.5 13.95 6 15.75 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],[1,"v-today-views-container"],[1,"v-today-views-count"],[1,"v-today-views-text"],["class","v-users-container",4,"ngIf"],[1,"v-users-container"],[4,"ngFor","ngForOf"],[1,"v-user"],[1,"v-user-image"],[3,"user","size"],[1,"v-user-view-details"],[1,"v-user-name"],[1,"v-user-view-time"],[1,"v-document-viewer-tread-left"],["class","v-document-viewer-tread-right",4,"ngIf"],[1,"v-document-viewer-tread-right"]],template:function(t,n){t&1&&T(0,Et,5,4,"ng-container",1),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[ze,le,ct,lt,st,pt],styles:[`.v-view-analytics-dialog-container{border-radius:var(--legacy-velt-view-analytics-dialog-border-radius);border:var(--legacy-velt-view-analytics-dialog-border);background:var(--legacy-velt-view-analytics-dialog-bg-color);box-shadow:var(--legacy-velt-view-analytics-dialog-box-shadow);padding:var(--legacy-velt-view-analytics-dialog-padding);display:flex;gap:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-left{display:flex;flex-direction:column;gap:4px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container{width:140px;height:110px;flex-shrink:0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:10px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-today-views-container{display:flex;width:140px;padding:8px 4px;justify-content:center;align-items:center;gap:4px;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container .v-document-viewer-tread-right{padding:8px 0}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user{display:flex;align-items:center;gap:12px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container.bottom-sheet{display:flex;flex-direction:column;border-bottom-left-radius:0;border-bottom-right-radius:0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container{display:flex;padding:8px 8px 0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container .v-back-btn{background:transparent;border:0;outline:0;display:flex;align-items:center;gap:8px;color:var(--legacy-velt-view-analytics-dialog-back-btn-color);cursor:pointer;font-size:16px;font-style:normal;font-weight:400;line-height:normal}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container{display:flex;flex:1;gap:10px}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-count{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-text{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user{display:flex;align-items:center;gap:12px;width:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px;flex:1}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}
1
+ import{t as dt}from"./chunk-35XJQZ27.js";import"./chunk-BG6LRF5O.js";import"./chunk-MFXS56C3.js";import{a as We,c as Je,d as Ke}from"./chunk-CRKE5XUX.js";import{a as gt}from"./chunk-OITZJHUL.js";import"./chunk-EQWU2DL7.js";import{a as ct}from"./chunk-2YDGTFZM.js";import{a as pt}from"./chunk-QXHO6I75.js";import"./chunk-333ZBMSE.js";import"./chunk-T6YEK2X2.js";import{b as st,d as lt}from"./chunk-2DMVX6Z3.js";import{a as mt}from"./chunk-ESMJKCYM.js";import{a as je}from"./chunk-BRCK225M.js";import{A as Pe,Fa as rt,G as Ne,H as Le,Ha as at,I as Me}from"./chunk-TU6L6SDC.js";import{a as ut}from"./chunk-M6J3KGG7.js";import{D as ot,E as pe,j as ge}from"./chunk-4H2TOH52.js";import{Aj as Se,Bb as x,E as B,Fj as z,G as De,Gd as Re,Ha as w,Hc as ze,He as E,Hi as ye,Ia as re,Ic as le,Ij as tt,K as te,Kb as ae,Ki as Ze,M as q,Mb as se,O as xe,Pb as _,Pj as it,Qb as K,Ra as I,Rb as j,Rc as Fe,Tb as Te,U as _e,V as S,Va as Ue,Vd as qe,Wa as Q,Wd as Ge,Xa as ke,Y as Ee,Zf as we,Zi as fe,_ as ie,a as m,ab as T,b as h,ba as Oe,ca as Be,cc as $e,ci as Qe,ea as k,ei as de,g as R,ja as P,ka as N,kj as Xe,l as $,la as H,ma as Y,mc as A,nb as D,nc as U,nj as me,ob as v,pb as y,pj as C,qb as L,qe as He,qj as et,r as b,rc as ce,sa as ne,sk as ue,t as Ce,tk as nt,ub as G,v as f,vb as W,w as Z,wa as Ae,xb as J,ya as oe,yg as Ye,zb as M}from"./chunk-4QGCX4EY.js";function vt(c){return c?{field:"metadata.veltFolderId",value:c}:null}function ht(c,l){if(!l||!c||typeof c!="object")return c;let r={};for(let e of Object.keys(c)){let t=c[e]?.metadata;(!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"veltFolderId"))||t.veltFolderId===l.value)&&(r[e]=c[e])}return r}var F=(()=>{let l=class l{constructor(e,t,n,i,o,s,d,a,g,p){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=s,this.iamService=d,this.loggingService=a,this.userPermissionService=g,this.serviceBook=p,this.documentPaths=null,this.views$=new $({}),this.commentViews$=new $({}),this.documentViews$=new $({}),this.locationViews$=new $({}),this.commentViewsByOrganizationIdAndDocumentId$=new $({}),this.documentViewsByOrganizationIdAndDocumentId$=new $({}),this.locationViewsByOrganizationIdAndLocationId$=new $({}),this.documentViewsEnabled$=new $(!1),this.documentViewsSetByDocumentId={},this.notificationService=null,this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.serviceBook.observe(fe).subscribe(u=>{this.commentService=u??void 0}),this.serviceBook.observe(Ze).subscribe(u=>{this.notificationService=u??null}),this.viewsDbReadyGate$().pipe(te(1)).subscribe(()=>{this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(u=>{this.notificationService?.setNotificationViews(u)}),this.authService.getUser$().pipe(B(u=>!!u),S(u=>this.documentViewsEnabled$.pipe(B(V=>V),f(()=>u))),S(u=>this.docService.getDocumentPaths$().pipe(_e(null),xe(),f(([V,O])=>(V?.documentId!==O?.documentId&&this.views$.next({}),O)),f(V=>(this.documentPaths=V,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:u,_documentPaths:V})),S(V=>this.docService.getDocumentIds$().pipe(S(O=>(O?.length&&(O.find(ee=>ee.documentId===this.documentPaths?.documentId)||O.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),O.forEach(ee=>{this.setDocumentAsRead({documentId:ee.documentId,clientDocumentId:ee.clientDocumentId})})),b(V))))))),S(u=>this.docService.getDocumentMetadata$().pipe(B(V=>!!V),f(V=>h(m({},u),{_documentMetadata:V}))))).subscribe(),this.authService.getUser$().pipe(B(u=>!!u),S(u=>this.documentViewsEnabled$.pipe(B(V=>V),f(()=>u))),S(u=>this.docService.getLocation$().pipe(B(V=>!!V))),S(u=>this.docService.getDocumentIds$().pipe(S(V=>(V.find(O=>O.documentId===this.documentPaths?.documentId)||V.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),V.forEach(O=>{this.setLocationAsRead({documentId:O.documentId,clientDocumentId:O.clientDocumentId})}),b(u)))))).subscribe()},u=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",u)})}catch(u){this.loggingService.catch("Error in ViewsService constructor: ",u)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let n,i;try{if(e&&(i=we(e)),t&&typeof t=="object"){let o=Ye(t);n=we(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(B(o=>!!o),S(o=>this.isFeatureAllowed({firebaseUser:o})),S(o=>o.featureAllowed?this.iamService.isUserAllowed$().pipe(f(s=>(o.featureAllowed=s,o))):b(o)),S(o=>o.featureAllowed?b(o).pipe(S(s=>this.docService.getDocumentPaths$().pipe(f(d=>(this.documentPaths=d,s.documentPaths=d,s)))),S(s=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(d=>{let a=d?.length>0?d.map(g=>g.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(a)})))):b([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(B(t=>!!t),f(t=>h(m({},e),{config:t})),S(t=>this.authService.getUser$().pipe(f(n=>h(m({},t),{user:n})))),S(t=>t.user?b(h(m({},t),{featureAllowed:!0})):b(h(m({},t),{featureAllowed:!1}))),q((t,n)=>t?.featureAllowed===n?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:n}=e;return t?.some(i=>!i)||!this.documentPaths?b([]):this.documentViewsEnabled$.pipe(S(i=>i?Z([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Z([this.getCommentViewsDataFromDocuments()])))}else return b(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([n,i])=>{let o=i.metadata?.documentId,s=i.views;!o||!s||(t[o]||(t[o]={}),t[o][i.annotationId]=s)}),Object.entries(t??{}).forEach(([n,i])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:n,commentViews:i})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.serviceBook.observe(fe).pipe(q(),S(e=>{if(!e)return b([]);try{return e.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,fromCommentSidebar:!0,skipPositionCalculation:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(B(t=>!!t),Ee(t=>{this.getCommentViews(t)}),De(t=>(this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",t),b([]))))}catch(t){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",t),b([])}}))}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),b([])}}viewsDbReadyGate$(){return it({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(ge),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in ViewsService viewsDbReadyGate$ ${e}: `,t)})}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=vt(t),i=b([]),o={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(o.documentId=e?.length?e[0]:void 0,o.organizationId=this.documentPaths?.organizationId),this.commonDbService.usesPortableChannelFeed(ge))i=this.commonDbService.dbListener({feature:"allDocumentViews",properties:h(m({},o),{organizationId:this.documentPaths?.organizationId,documentIds:e})}).pipe(ie(),f(s=>de(JSON.parse(JSON.stringify([s])))),f(s=>n&&s?.data?h(m({},s),{data:ht(s.data,n)}):s));else{let s=[];for(let d=0;d<(e?.length??0);d+=E.LISTENER_BATCH_SIZE)s.push(e?.slice(d,d+E.LISTENER_BATCH_SIZE)??[]);i=Z(s.map(d=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:h(m({},o),{firestoreQuery:[Se(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",d),z("metadata.organizationId","==",this.documentPaths?.organizationId),...n?[z(n.field,"==",n.value)]:[])]})}).pipe(ie()))).pipe(f(d=>de(d)))}return i.pipe(f(s=>({data:s?.data,operation:s?.operation})),f(({data:s,operation:d})=>{let a={};return e?(Object.entries(s??{}).forEach(([g,p])=>{let u=p.metadata?.documentId;u&&(a[u]||(a[u]={}),a[u][g]=p)}),{data:s,documentMap:a,operation:d}):{data:s,documentMap:a,operation:d}}),f(({data:s,documentMap:d,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let g=this.documentViews$.value;a?.ids?.forEach(p=>{delete g?.[p]}),this.documentViews$.next(g)}}else Object.entries(d??{}).forEach(([g,p])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:g,documentViews:p})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=b([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId);let o=[];for(let s=0;s<(e?.length??0);s+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(s,s+E.LISTENER_BATCH_SIZE)??[]);return n=Z(o.map(s=>this.commonDbService.dbListener({feature:"allLocationViews",properties:h(m({},i),{firestoreQuery:[Se(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",s),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(s=>de(s))),n.pipe(f(s=>({data:s?.data,operation:s?.operation})),f(({data:s,operation:d})=>{let a={};return e?(Object.entries(s??{}).forEach(([g,p])=>{let u=p.metadata?.documentId;u&&(a[u]||(a[u]={}),a[u][g]=p)}),{data:s,documentMap:a,operation:d}):{data:s,documentMap:a,operation:d}}),f(({data:s,documentMap:d,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let g=this.locationViews$.value;a?.ids?.forEach(p=>{delete g?.[p]}),this.locationViews$.next(g)}}else Object.entries(d??{}).forEach(([g,p])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:g,locationViews:p})})}))}setViewsData(e){try{this.views$.next(m(m({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.commentViews$.value),n);this.commentViews$.next(o),this.commentViewsByOrganizationIdAndDocumentId$.next(h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:h(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.documentViews$.value),n);this.documentViews$.next(o),this.documentViewsByOrganizationIdAndDocumentId$.next(h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:h(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.locationViews$.value),n);this.locationViews$.next(o),this.locationViewsByOrganizationIdAndLocationId$.next(h(m({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:h(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[t]:h(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}getCommentFeatureViews$(){return this.commentViews$.pipe(q((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return R(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.updateCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}setCommentAnnotationAsUnread(e){return R(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.removeCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{},s=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(a=>{o[a.commentId]||(o[a.commentId]={views:{}}),o[a.commentId].views||(o[a.commentId].views={}),o[a.commentId].views[t.userSnippylyId]||(o[a.commentId].views[t.userSnippylyId]={timestamp:s})});let d=new Set(e.comments?.map(a=>a.commentId+""));if(Object.keys(o??{}).forEach(a=>{d.has(a)||delete o[a]}),e.comments?.length){let a=o[e.comments[0].commentId]?.views||{},g=Object.keys(a??{}).filter(p=>e.comments?.every(u=>o[u.commentId]?.views?.[p]));g.forEach(p=>{i[p]={timestamp:a[p].timestamp}}),e.viewedByUserIds=g}n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}removeCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{};e.comments?.forEach(d=>{o[d.commentId]?.views?.[t.userSnippylyId]&&delete o[d.commentId].views[t.userSnippylyId]});let s=new Set(e.comments?.map(d=>d.commentId+""));if(Object.keys(o??{}).forEach(d=>{s.has(d)||delete o[d]}),e.comments?.length){let d=o[e.comments[0].commentId]?.views||{},a=Object.keys(d??{}).filter(g=>e.comments?.every(p=>o[p.commentId]?.views?.[g]));a.forEach(g=>{i[g]={timestamp:d[g].timestamp}}),e.viewedByUserIds=a}else e.viewedByUserIds=[];n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService removeCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(q((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let n=new Date().getTime()+this.commonDbService.getOffset();e.forEach(i=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:i,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:n}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(q((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.users||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.users||{}:{}})))),q(Qe))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),b({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.day||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.day||{}:{}})))))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),b({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(n){return R(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser();if(i&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let o=new Date().getTime()+this.commonDbService.getOffset(),s=new Date().toISOString().split("T")[0];if(this.commonDbService.usesPortableChannelFeed(ge)){let a=yield Ce(this.docService.getDocumentPaths$().pipe(f(g=>g?.organizationId),B(g=>!!g)));yield this.commonDbService.whenPortableRealtimeReady(),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:a},data:{}}),this.checkAndTriggerNotification(i);return}let d=this.getDocumentViewsById(e);if(d){let a=new Date().toISOString().split("T")[0];d?.users[i.userSnippylyId]||(d.users[i.userSnippylyId]={}),d.users[i.userSnippylyId][a]={timestamp:this.timestamp},d?.day[a]||(d.day[a]={}),d.day[a][i.userSnippylyId]={timestamp:this.timestamp},d.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:d})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:i.userSnippylyId,date:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})}),this.docService.getDocumentMetadata$(e).pipe(B(a=>a!==null),te(1)).subscribe(()=>{let a={day:{[s]:{[i.userSnippylyId]:{timestamp:o}}},users:{[i.userSnippylyId]:{[s]:{timestamp:o}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:a})});this.checkAndTriggerNotification(i)}}catch(i){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",i)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(te(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let n=this.docService.getDocumentMetadata();if(n?.creator?.email&&n?.creator?.email!==e.email){let i=[n.creator.email];this.updateNotificationsDatabase(He.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return R(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),s=o?.locationId,d=o?.location;if(i&&s&&d){let a=new Date().getTime()+this.commonDbService.getOffset(),g=new Date().toISOString().split("T")[0],p=this.getLocationViewsById(s);if(p){let u=new Date().toISOString().split("T")[0];p?.users[i.userSnippylyId]||(p.users[i.userSnippylyId]={}),p.users[i.userSnippylyId][u]={timestamp:this.timestamp},p?.day[u]||(p.day[u]={}),p.day[u][i.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:p,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:d,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:s,user:i.userSnippylyId,date:g,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:a}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:s,date:g,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:a}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let u={day:{[g]:{[i.userSnippylyId]:{timestamp:a}}},users:{[i.userSnippylyId]:{[g]:{timestamp:a}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:d};this.commonDbService.updateData({feature:"location",data:u,properties:{id:s,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(i){this.loggingService.catch("Error in ViewsService setLocationAsRead:",i)}})}updateNotificationsDatabase(e,t={}){try{let n=m({actionType:e,notificationSource:"documentViews"},t);this.notificationService?.updateNotificationDatabase(n)}catch(n){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",n)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};l.\u0275fac=function(t){return new(t||l)(k(Re),k(nt),k(et),k(tt),k(pe),k(ot),k(mt),k(C),k(gt),k(me))},l.\u0275prov=Oe({token:l,factory:l.\u0275fac,providedIn:"root"});let c=l;return c})();function Vt(c,l){if(c&1&&(G(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),y(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),y()(),v(8,"div",26),_(9),A(10,"timeAgo"),y()(),W()),c&2){let r=l.$implicit;w(3),D("user",r==null?null:r.user)("size",32),w(3),j(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),w(3),j(" ",U(10,6,r==null?null:r.timestamp)," ")}}function It(c,l){if(c&1&&(v(0,"div",19),T(1,Vt,11,8,"ng-container",20),y()),c&2){let r=x(2).ngIf;w(),D("ngForOf",r.userViews)}}function Ct(c,l){if(c&1){let r=J();G(0),v(1,"div",4)(2,"button",5),M("click",function(){P(r);let t=x(2);return N(t.closeTrendDialog())}),H(),v(3,"svg",6),L(4,"path",7),y(),Y(),v(5,"span"),_(6),A(7,"translate"),y()()(),v(8,"div",8)(9,"div",9)(10,"div",10),_(11),y(),v(12,"div",11),H(),v(13,"svg",12),L(14,"path",13)(15,"path",14),y(),Y(),v(16,"span"),_(17),A(18,"translate"),y()()(),v(19,"div",15)(20,"div",16),_(21),y(),v(22,"div",17)(23,"span"),_(24),A(25,"translate"),y()()()(),T(26,It,2,1,"div",18),W()}if(c&2){let r=x().ngIf;w(6),K(U(7,6,"Go Back")),w(5),j(" ",r.totalUniqueViewsCount," "),w(6),K(U(18,8,"Total Views")),w(4),j(" ",r.todayViewsCount," "),w(3),K(U(25,10,"Views Today")),w(2),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Dt(c,l){if(c&1&&(G(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),y(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),y(),v(8,"div",26),_(9),A(10,"timeAgo"),y()()(),W()),c&2){let r=l.$implicit;w(3),D("user",r==null?null:r.user)("size",32),w(3),j(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),w(3),j(" ",U(10,6,r==null?null:r.timestamp)," ")}}function xt(c,l){if(c&1&&(v(0,"div",29)(1,"div",19),T(2,Dt,11,8,"ng-container",20),y()()),c&2){let r=x(2).ngIf;w(2),D("ngForOf",r.userViews)}}function _t(c,l){if(c&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),_(3),y(),v(4,"div",11),H(),v(5,"svg",12),L(6,"path",13)(7,"path",14),y(),Y(),v(8,"span"),_(9),A(10,"translate"),y()()(),v(11,"div",15),_(12),A(13,"translate"),A(14,"translate"),A(15,"translate"),y()(),T(16,xt,3,1,"div",28)),c&2){let r=x().ngIf;w(3),j(" ",r.totalUniqueViewsCount," "),w(6),K(U(10,6,"Total Views")),w(3),Te(" ",r.todayViewsCount," ",r.todayViewsCount===1?U(13,8,"View"):U(14,10,"Views")," ",U(15,12,"Today")," "),w(4),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Et(c,l){if(c&1){let r=J();G(0),v(1,"div",2),M("clickOutside",function(){P(r);let t=x();return N(t.closeTrendDialog())}),T(2,Ct,27,12,"ng-container",3)(3,_t,17,14,"ng-template",null,0,ce),y(),W()}if(c&2){let r=l.ngIf,e=ae(4);w(),se("bottom-sheet",r.bottomSheetMode),w(),D("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var X=(()=>{let l=class l{constructor(e,t,n,i,o,s,d){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=s,this.bottomSheetData=d,this.close=new re,this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,views:{},usersMap:{},userViews:[],bottomSheetMode:!1}),this.subscriptions=[];try{d&&(this.componentConfigSignal.update(a=>(a=h(m({},a),{bottomSheetMode:!0}),a)),this.clientLocationId=d.clientLocationId,this.closeBottomSheetFn=d.closeBottomSheetFn),this.subscriptions.push(this.contactService.getUsersMap$().subscribe(a=>{this.componentConfigSignal.update(g=>(g=h(m({},g),{usersMap:a||{}}),g)),this.setLatestViewsByUsers()},a=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUsersMap$ subscription: ",a)})),this.subscriptions.push(this.themeService.getDarkMode$().subscribe(a=>{a?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark")}))}catch(a){this.loggingService.catch("Error in ViewAnalyticsDialogComponent constructor: ",a)}}ngOnInit(){this.getDocumentViews()}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngAfterViewInit: ",e)}}trackByUserIdAndTimestamp(e,t){return`${t?.user?.userSnippylyId}-${t.timestamp}`}getDocumentViews(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(e=>(e=h(m({},e),{totalUniqueViews:{},totalUniqueViewsCount:0}),e)),this.uniqueViewsByUserSubscription.unsubscribe()),this.uniqueViewsByDateSubscription&&(this.componentConfigSignal.update(e=>(e=h(m({},e),{todayViews:{},todayViewsCount:0}),e)),this.uniqueViewsByDateSubscription.unsubscribe()),this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=h(m({},t),{totalUniqueViews:e||{},totalUniqueViewsCount:Object.keys(e||{})?.length||0}),t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByUser subscription: ",e)}),this.uniqueViewsByDateSubscription=this.viewsService.getUniqueViewsByDate(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.todayViews=e&&e[t.today]?e[t.today]:{},t.todayViewsCount=Object.keys(t.todayViews||{})?.length||0,t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByDate subscription: ",e)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent getDocumentViews: ",e)}}setLatestViewsByUsers(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLatestViewsByUsers","color: green;"),Object.keys(this.componentConfigSignal().todayViews||{}).forEach(e=>{let t=this.componentConfigSignal().usersMap[e],n=this.componentConfigSignal().todayViews[e]?.timestamp;t&&n&&(this.componentConfigSignal().userViews.find(o=>o.user.userSnippylyId===e)||this.componentConfigSignal.update(o=>(o=h(m({},o),{userViews:[...o.userViews,{user:t,timestamp:n}]}),o)))}),this.componentConfigSignal.update(e=>(e=m({},e),e.userViews.sort((t,n)=>n.timestamp-t.timestamp),e.userViews=e.userViews.slice(0,3),e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent setLatestViewsByUsers: ",e)}}closeTrendDialog(){try{this.close.emit(),this.closeBottomSheetFn&&this.closeBottomSheetFn?.()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()}),this.uniqueViewsByDateSubscription?.unsubscribe(),this.uniqueViewsByUserSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngOnDestroy: ",e)}}};l.\u0275fac=function(t){return new(t||l)(I(rt),I(C),I(F),I(at),I(oe),I(ue),I(We,8))},l.\u0275cmp=Q({type:l,selectors:[["velt-view-analytics-dialog"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:1,vars:1,consts:[["defaultDialogRef",""],[4,"ngIf"],["snippylyClickOutside","",1,"v-view-analytics-dialog-container",3,"clickOutside"],[4,"ngIf","ngIfElse"],[1,"v-back-btn-container"],[1,"v-back-btn",3,"click"],["width","16","height","16","viewBox","0 0 16 16","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M9.99988 4L5.99988 8L9.99988 12","stroke","currentColor","stroke-width","1.33333","stroke-linecap","round","stroke-linejoin","round"],[1,"v-view-analytics-count-container"],[1,"v-total-views-container"],[1,"v-total-views-count"],[1,"v-total-views-text"],["width","18","height","18","viewBox","0 0 18 18","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M7.5 9C7.5 9.39782 7.65804 9.77936 7.93934 10.0607C8.22064 10.342 8.60218 10.5 9 10.5C9.39782 10.5 9.77936 10.342 10.0607 10.0607C10.342 9.77936 10.5 9.39782 10.5 9C10.5 8.60218 10.342 8.22064 10.0607 7.93934C9.77936 7.65804 9.39782 7.5 9 7.5C8.60218 7.5 8.22064 7.65804 7.93934 7.93934C7.65804 8.22064 7.5 8.60218 7.5 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],["d","M15.75 9C13.95 12 11.7 13.5 9 13.5C6.3 13.5 4.05 12 2.25 9C4.05 6 6.3 4.5 9 4.5C11.7 4.5 13.95 6 15.75 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],[1,"v-today-views-container"],[1,"v-today-views-count"],[1,"v-today-views-text"],["class","v-users-container",4,"ngIf"],[1,"v-users-container"],[4,"ngFor","ngForOf"],[1,"v-user"],[1,"v-user-image"],[3,"user","size"],[1,"v-user-view-details"],[1,"v-user-name"],[1,"v-user-view-time"],[1,"v-document-viewer-tread-left"],["class","v-document-viewer-tread-right",4,"ngIf"],[1,"v-document-viewer-tread-right"]],template:function(t,n){t&1&&T(0,Et,5,4,"ng-container",1),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[ze,le,ct,lt,st,pt],styles:[`.v-view-analytics-dialog-container{border-radius:var(--legacy-velt-view-analytics-dialog-border-radius);border:var(--legacy-velt-view-analytics-dialog-border);background:var(--legacy-velt-view-analytics-dialog-bg-color);box-shadow:var(--legacy-velt-view-analytics-dialog-box-shadow);padding:var(--legacy-velt-view-analytics-dialog-padding);display:flex;gap:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-left{display:flex;flex-direction:column;gap:4px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container{width:140px;height:110px;flex-shrink:0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:10px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-today-views-container{display:flex;width:140px;padding:8px 4px;justify-content:center;align-items:center;gap:4px;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container .v-document-viewer-tread-right{padding:8px 0}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user{display:flex;align-items:center;gap:12px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container.bottom-sheet{display:flex;flex-direction:column;border-bottom-left-radius:0;border-bottom-right-radius:0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container{display:flex;padding:8px 8px 0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container .v-back-btn{background:transparent;border:0;outline:0;display:flex;align-items:center;gap:8px;color:var(--legacy-velt-view-analytics-dialog-back-btn-color);cursor:pointer;font-size:16px;font-style:normal;font-weight:400;line-height:normal}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container{display:flex;flex:1;gap:10px}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-count{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-text{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user{display:flex;align-items:center;gap:12px;width:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px;flex:1}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}
2
2
  `],encapsulation:3,changeDetection:0});let c=l;return c})();var Ve=(()=>{let l=class l{constructor(e,t){this.bottomSheet=e,this.loggingService=t,this.close=new re,this.subscriptions=[]}ngOnInit(){}ngAfterViewInit(){this.openBottomSheet()}openBottomSheet(){return R(this,null,function*(){try{this.bottomSheetRef=this.bottomSheet.open(X,{data:{clientLocationId:this.clientLocationId,closeBottomSheetFn:()=>{this.onClose(),this.bottomSheetRef?.dismiss()}},panelClass:["v-view-analytics-bottom-sheet-container","velt-mat-bottom-sheet-container"]}),this.subscriptions.push(this.bottomSheetRef.backdropClick().subscribe(()=>{this.onClose()},e=>{this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent backdropClick subscription: ",e)}))}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent openBottomSheet: ",e)}})}onClose(){try{this.close.emit()}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()})}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent ngOnDestroy: ",e)}}};l.\u0275fac=function(t){return new(t||l)(I(Je),I(C))},l.\u0275cmp=Q({type:l,selectors:[["velt-view-analytics-bottom-sheet-internal"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:0,vars:0,template:function(t,n){},styles:[".velt-mat-bottom-sheet-container.v-view-analytics-bottom-sheet-container{padding:0!important} .velt-mat-bottom-sheet-container.v-view-analytics-bottom-sheet-container .mat-bottom-sheet-container{padding:0!important}"],changeDetection:0});let c=l;return c})();var At=()=>["snippyly-overlay-panel","v-view-analytics-overlay-panel","velt-overlay-panel"];function Ut(c,l){if(c&1){let r=J();v(0,"velt-view-analytics-dialog",11),M("close",function(){P(r);let t=x(2);return N(t.toggleTrends())}),y()}if(c&2){let r=x(2);D("clientLocationId",r.clientLocationId)}}function kt(c,l){if(c&1){let r=J();v(0,"velt-view-analytics-bottom-sheet-internal",11),M("close",function(){P(r);let t=x(2);return N(t.closeTrends())}),y()}if(c&2){let r=x(2);D("clientLocationId",r.clientLocationId)}}function Tt(c,l){if(c&1){let r=J();G(0),v(1,"div",3,0),M("click",function(t){return P(r),x().toggleTrends(),N(t.stopPropagation())}),v(3,"slot",4),M("slotchange",function(){P(r);let t=x();return N(t.onButtonSlotChange())}),v(4,"div",5),H(),v(5,"svg",6),L(6,"path",7),y(),Y(),v(7,"span",8),_(8),y()()()(),T(9,Ut,1,1,"ng-template",9,1,ce)(11,kt,1,1,"velt-view-analytics-bottom-sheet-internal",10),W()}if(c&2){let r=l.ngIf,e=ae(2),t=x();w(4),se("active",r.treadsVisible),w(4),K(r.totalUniqueViewsCount),w(),D("cdkConnectedOverlayOrigin",e)("cdkConnectedOverlayOpen",!r.isPhone&&r.treadsVisible)("cdkConnectedOverlayPanelClass",$e(11,At))("cdkConnectedOverlayBackdropClass","snippyly-overlay-backdrop")("cdkConnectedOverlayGrowAfterOpen",!0)("cdkConnectedOverlayPositions",t.positions)("cdkConnectedOverlayDisableClose",!0),w(2),D("ngIf",r.isPhone&&r.treadsVisible)}}var Ie=(()=>{let l=class l{constructor(e,t,n,i,o,s){this.breakpointObserver=e,this.docService=t,this.loggingService=n,this.viewsService=i,this.elementRef=o,this.domService=s,this.type="document",this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,treadsVisible:!1,customButtonAdded:!1,isPhone:!1,componentId:Math.random().toString(36).substring(2)}),this.positions=E.OVERLAY_POSITIONS.map(d=>new Pe({originX:d.originX,originY:d.originY},{overlayX:d.overlayX,overlayY:d.overlayY})),this.subscriptions=[]}ngOnInit(){try{this.getUniqueViewsByUser(),this.subscriptions.push(this.breakpointObserver.observe(Ge.XSmall).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.isPhone=!!e.matches,t))},e=>{this.loggingService.catch("Error in ViewAnalyticsComponent breakpointObserver subscription: ",e)})),this.subscriptions.push(this.docService.getLocation$().subscribe(e=>{e?.location?.id&&(this.clientLocationId=e?.location?.id,this.getUniqueViewsByUser())}))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnInit: ",e)}}ngOnChanges(e){try{(e.type||e.clientLocationId)&&this.getUniqueViewsByUser()}catch(t){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngAfterViewInit: ",e)}}getUniqueViewsByUser(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(t=>(t=m({},t),t.totalUniqueViews={},t.totalUniqueViewsCount=0,t)),this.uniqueViewsByUserSubscription.unsubscribe());let e=this.type==="location"&&this.clientLocationId?this.clientLocationId:void 0;this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(e).subscribe(t=>{this.componentConfigSignal.update(n=>(n=m({},n),n.totalUniqueViews=t||{},n.totalUniqueViewsCount=Object.keys(n.totalUniqueViews||{})?.length||0,n))},t=>{this.loggingService.catch("Error in ViewAnalyticsComponent getUniqueViewsByUser subscription: ",t)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent getDocumentViews: ",e)}}toggleTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: toggleTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!e.treadsVisible,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent toggleTrends: ",e)}}openTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: openTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!0,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent openTrends: ",e)}}closeTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: closeTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!1,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent closeTrends: ",e)}}onButtonSlotChange(){this.componentConfigSignal.update(e=>(e=m({},e),e.customButtonAdded=!0,e))}unsubscribe(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[],this.uniqueViewsByUserSubscription&&this.uniqueViewsByUserSubscription.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent unsubscribe: ",e)}}ngOnDestroy(){try{this.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnDestroy: ",e)}}};l.\u0275fac=function(t){return new(t||l)(I(qe),I(pe),I(C),I(F),I(oe),I(ue))},l.\u0275cmp=Q({type:l,selectors:[["velt-view-analytics-internal"]],inputs:{type:"type",clientLocationId:[0,"locationId","clientLocationId"]},standalone:!1,features:[Ae],decls:1,vars:1,consts:[["trigger","cdkOverlayOrigin"],["overlay","cdkConnectedOverlay"],[4,"ngIf"],["part","container","cdkOverlayOrigin","",1,"v-document-viewer-tread-container",3,"click"],["name","button",3,"slotchange"],["part","button-container",1,"action-btn"],["part","button-icon","width","24","height","24","viewBox","0 0 24 24","fill","none","xmlns","http://www.w3.org/2000/svg",1,"action-btn-icon"],["d","M4.5 16.1667L9.5 11.1667L12.8333 14.5L19.5 7.83334M19.5 7.83334H13.6667M19.5 7.83334V13.6667","stroke","currentColor","stroke-width","1.5","stroke-linecap","round","stroke-linejoin","round"],["part","button-label",1,"action-btn-label"],["cdkConnectedOverlay","",3,"cdkConnectedOverlayOrigin","cdkConnectedOverlayOpen","cdkConnectedOverlayPanelClass","cdkConnectedOverlayBackdropClass","cdkConnectedOverlayGrowAfterOpen","cdkConnectedOverlayPositions","cdkConnectedOverlayDisableClose"],[3,"clientLocationId","close",4,"ngIf"],[3,"close","clientLocationId"]],template:function(t,n){t&1&&T(0,Tt,12,12,"ng-container",2),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[le,Le,Ne,X,Ve],styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}*{box-sizing:border-box;-webkit-tap-highlight-color:rgba(255,255,255,0);outline:none;margin:0;padding:0;height:unset;width:unset;text-align:left;line-height:1.5;font-size:calc((1rem + 0px) * var(--velt-base-rem-unit))}*:empty{display:revert}.v-document-viewer-tread-container{display:inline-block}.action-btn{display:inline-flex;justify-content:center;align-items:center;padding:6px;border-radius:var(--legacy-velt-tool-border-radius);border:var(--legacy-velt-tool-border);background-color:var(--legacy-velt-tool-bg-color);color:var(--legacy-velt-tool-icon-color);cursor:pointer}.action-btn .action-btn-label{font-size:calc((.9rem + 0px) * var(--velt-base-rem-unit));padding:0 12px 0 4px;font-weight:700;color:currentColor}.action-btn .action-btn-icon{width:calc((var(--legacy-velt-tool-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-icon-size) + 0px) * var(--velt-base-rem-unit));color:currentColor;padding-left:8px;box-sizing:content-box}.action-btn .toolbar-icon-dropdown-arrow{width:16px;height:16px;color:currentColor}.action-btn:focus{border-radius:var(--legacy-velt-tool-focus-border-radius);border:var(--legacy-velt-tool-focus-border);background-color:var(--legacy-velt-tool-focus-bg-color);color:var(--legacy-velt-tool-focus-icon-color)}.action-btn:focus .action-btn-icon{width:calc((var(--legacy-velt-tool-focus-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-focus-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:focus .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-focus-icon-color)}.action-btn:hover{border-radius:var(--legacy-velt-tool-hover-border-radius);border:var(--legacy-velt-tool-hover-border);background-color:var(--legacy-velt-tool-hover-bg-color);color:var(--legacy-velt-tool-hover-icon-color)}.action-btn:hover .action-btn-icon{width:calc((var(--legacy-velt-tool-hover-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-hover-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:hover .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-hover-icon-color)}.action-btn:active,.action-btn.active{border-radius:var(--legacy-velt-tool-active-border-radius);border:var(--legacy-velt-tool-active-border);background-color:var(--legacy-velt-tool-active-bg-color);color:var(--legacy-velt-tool-active-icon-color)}.action-btn:active .action-btn-icon,.action-btn.active .action-btn-icon{width:calc((var(--legacy-velt-tool-active-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-active-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:active .toolbar-icon-dropdown-arrow,.action-btn.active .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-active-icon-color)}
3
3
  `],encapsulation:3,changeDetection:0});let c=l;return c})();var he=class extends ut{constructor(l){super(l),this.getService(C).log("%c[WB] Creating CLASS: ViewsElement","color: blue;"),this.getUniqueViewsByUser=this._getUniqueViewsByUser,this.getUniqueViewsByDate=this._getUniqueViewsByDate}_getUniqueViewsByUser(l){this.getService(C).log("%c[WB] Calling FUNCTION: _getUniqueViewsByUser","color: green;");try{return this.trackEvent(ye.Events.Views.GET_UNIQUE_VIEWS_BY_USER_TRIGGERED,{payload:{clientLocationId:l}}),this.getService(F).getUniqueViewsByUser(l)}catch(r){return this.getService(C).catch("Error in getUniqueViewsByUser: ",r),b({})}}_getUniqueViewsByDate(l){this.getService(C).log("%c[WB] Calling FUNCTION: _getUniqueViewsByDate","color: green;");try{return this.trackEvent(ye.Events.Views.GET_UNIQUE_VIEWS_BY_DATE_TRIGGERED,{payload:{clientLocationId:l}}),this.getService(F).getUniqueViewsByDate(l)}catch(r){return this.getService(C).catch("Error in getUniqueViewsByDate: ",r),b({})}}};var yt=(()=>{let l=class l{};l.\u0275fac=function(t){return new(t||l)},l.\u0275mod=ke({type:l}),l.\u0275inj=Be({imports:[Fe,Me,Ke,dt]});let c=l;return c})();function $t(c){c.get(C).log("%c[WB] Loading view feature chunk","color: blue;"),c.get(me).set(Xe,c.get(F));let t=Ue(yt,c).injector;return zt(t,E.TAGS.VELT_VIEW_ANALYTICS,Ie),new he(c)}function zt(c,l,r){if(customElements.get(l))return;let e=je(r,c);customElements.define(l,e)}export{$t as default};
package/velt.js CHANGED
@@ -1,7 +1,7 @@
1
- var SNIPPYLY_VERSION = '6.0.28';
1
+ var SNIPPYLY_VERSION = '6.0.29';
2
2
  Promise.allSettled||(Promise.allSettled=function(t){return Promise.all(t.map(function(r){return Promise.resolve(r).then(function(e){return{status:"fulfilled",value:e}}).catch(function(e){return{status:"rejected",reason:e}})}))});
3
3
 
4
- import{a as ws}from"./chunk-MP2SDO2E.js";import{a as Ls}from"./chunk-JZCDUWAA.js";import{d as T}from"./chunk-RPLZXBLF.js";import{b as ko,d as re}from"./chunk-R7EWRVMV.js";import"./chunk-XEXFF5FD.js";import{a as jo,d as Wo}from"./chunk-HIEV42PB.js";import{b as Ds,c as xs,j as Ps,q as hi,t as Ns}from"./chunk-4HAFXUDN.js";import"./chunk-CR275X25.js";import"./chunk-R7PIAWZF.js";import"./chunk-3Q5TRC4E.js";import{l as Ho,m as $o,o as Xo,r as Jo,s as ts,u as is,v as rs,w as ns}from"./chunk-SN6HOFPK.js";import{d as Ao}from"./chunk-EB7SHB2S.js";import{d as Zo}from"./chunk-J3IQ7DYW.js";import{a as pi}from"./chunk-FWIDRPYU.js";import{a as Ms}from"./chunk-J35LMO3C.js";import"./chunk-JWSICAW6.js";import"./chunk-IS7ZDK65.js";import"./chunk-TLEK2ADO.js";import"./chunk-VJPZ6E4S.js";import{A as As,B as Rs,C as ks,D as Pr,G as ye,H as Te,a as Ye,c as ai,g as li,h as st,j as Cs,k as ci,l as di,m as ui,n as At,o as bs,p as Ss,q as Es,r as Ts,s as Os,z as Is}from"./chunk-KNYRVMQK.js";import{a as _s}from"./chunk-5ACPKO6C.js";import{a as Ke,b as xe,c as Rt,d as mi}from"./chunk-3BCXNETY.js";import{a as at}from"./chunk-ZRITZXNF.js";import{a as xr}from"./chunk-SYLJZSJP.js";import{Ea as es,Fa as ee,Ha as It,I as ri,l as To,na as Yo,o as Oo,p as Io,ta as bt,v as Ro,y as Dr}from"./chunk-GHN6NWBT.js";import{a as Pe}from"./chunk-67RGQF3Z.js";import{E as D,p as Ot,q as ms,r as ps,t as gs,u as fs,v as vs,z as ys}from"./chunk-NTFMMZRZ.js";import{$ as I,Ad as Po,Ba as Sr,Bb as B,Bd as Mo,Ca as ho,Cb as Ge,Db as je,Dd as No,E as no,Ea as mo,Ed as wo,Fa as po,Fb as Kt,Fd as Lo,Gb as Xt,Ha as W,Hb as Jt,Hc as ei,He as A,Hi as g,Ia as go,Ic as Qe,Id as Fo,Ja as Er,Jd as zo,K as oo,Kb as Or,Kd as Uo,M as so,Mb as yt,Md as qo,Nc as Ct,Pa as fo,Pb as We,Pe as ni,Qb as Ir,Qe as as,Ra as R,Rb as _t,Rd as Bo,Re as Et,Sc as ti,Sd as Vo,Sg as cs,Tc as Co,Td as Go,Uc as bo,Vc as ii,Vd as Qo,Wa as H,Wd as Ko,Xa as ke,Xc as So,Xd as St,Yc as Eo,Yd as fe,Yf as ls,_a as Tr,_f as oi,a as k,ab as ue,ac as Ar,b as j,ba as le,bc as De,c as Zn,ca as Re,cc as vo,d as fl,da as ao,e as Gt,ea as U,ec as Zt,ee as os,f as eo,fa as Fe,fb as Ue,g as L,hb as qe,hc as yo,i as jt,ib as Be,ja as Wt,ka as Ht,l as to,la as $t,m as M,mc as He,mi as ds,na as Ee,nb as q,nc as $e,nk as si,oa as br,ob as $,od as Do,oj as Tt,pb as J,pj as l,qa as lo,qb as Z,qj as V,r as x,rc as Rr,re as C,rk as ve,sa as co,sc as _o,sk as ie,tj as us,ub as ft,ue as ss,uj as hs,v as io,vb as vt,w as ro,wa as Qt,xa as uo,xb as Yt,ya as ze,zb as Ve,zc as kr,zd as xo}from"./chunk-VESMHAEV.js";var $n=fl((Sv,Hn)=>{"use strict";var p={};p.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};p.localCName=p.generateIdentifier();p.splitLines=function(r){return r.trim().split(`
4
+ import{a as ws}from"./chunk-7ZSEYX3G.js";import{a as Ls}from"./chunk-7K4EA6Y5.js";import{d as T}from"./chunk-DJPCTT4F.js";import{b as ko,d as re}from"./chunk-ASGMGCYI.js";import"./chunk-7DTEJ3JT.js";import{a as jo,d as Wo}from"./chunk-RIQYRZB7.js";import{b as Ds,c as xs,j as Ps,q as hi,t as Ns}from"./chunk-35XJQZ27.js";import"./chunk-BG6LRF5O.js";import"./chunk-FQILN45X.js";import"./chunk-AOKM7YOQ.js";import{l as Ho,m as $o,o as Xo,r as Jo,s as ts,u as is,v as rs,w as ns}from"./chunk-MFXS56C3.js";import{d as Ao}from"./chunk-DHVECNH4.js";import{d as Zo}from"./chunk-CRKE5XUX.js";import{a as pi}from"./chunk-OITZJHUL.js";import{a as Ms}from"./chunk-EQWU2DL7.js";import"./chunk-2YDGTFZM.js";import"./chunk-MW45OPL7.js";import"./chunk-QXHO6I75.js";import"./chunk-5TCVSBJS.js";import{A as As,B as Rs,C as ks,D as Pr,G as ye,H as Te,a as Ye,c as ai,g as li,h as st,j as Cs,k as ci,l as di,m as ui,n as At,o as bs,p as Ss,q as Es,r as Ts,s as Os,z as Is}from"./chunk-333ZBMSE.js";import{a as _s}from"./chunk-T6YEK2X2.js";import{a as Ke,b as xe,c as Rt,d as mi}from"./chunk-2DMVX6Z3.js";import{a as at}from"./chunk-ESMJKCYM.js";import{a as xr}from"./chunk-BRCK225M.js";import{Ea as es,Fa as ee,Ha as It,I as ri,l as To,na as Yo,o as Oo,p as Io,ta as bt,v as Ro,y as Dr}from"./chunk-TU6L6SDC.js";import{a as Pe}from"./chunk-M6J3KGG7.js";import{E as D,p as Ot,q as ms,r as ps,t as gs,u as fs,v as vs,z as ys}from"./chunk-4H2TOH52.js";import{$ as I,Ad as Po,Ba as Sr,Bb as B,Bd as Mo,Ca as ho,Cb as Ge,Db as je,Dd as No,E as no,Ea as mo,Ed as wo,Fa as po,Fb as Kt,Fd as Lo,Gb as Xt,Ha as W,Hb as Jt,Hc as ei,He as A,Hi as g,Ia as go,Ic as Qe,Id as Fo,Ja as Er,Jd as zo,K as oo,Kb as Or,Kd as Uo,M as so,Mb as yt,Md as qo,Nc as Ct,Pa as fo,Pb as We,Pe as ni,Qb as Ir,Qe as as,Ra as R,Rb as _t,Rd as Bo,Re as Et,Sc as ti,Sd as Vo,Sg as cs,Tc as Co,Td as Go,Uc as bo,Vc as ii,Vd as Qo,Wa as H,Wd as Ko,Xa as ke,Xc as So,Xd as St,Yc as Eo,Yd as fe,Yf as ls,_a as Tr,_f as oi,a as k,ab as ue,ac as Ar,b as j,ba as le,bc as De,c as Zn,ca as Re,cc as vo,d as fl,da as ao,e as Gt,ea as U,ec as Zt,ee as os,f as eo,fa as Fe,fb as Ue,g as L,hb as qe,hc as yo,i as jt,ib as Be,ja as Wt,ka as Ht,l as to,la as $t,m as M,mc as He,mi as ds,na as Ee,nb as q,nc as $e,oa as br,ob as $,od as Do,oj as Tt,ok as si,pb as J,pj as l,qa as lo,qb as Z,qj as V,r as x,rc as Rr,re as C,sa as co,sc as _o,sk as ve,tj as us,tk as ie,ub as ft,ue as ss,uj as hs,v as io,vb as vt,w as ro,wa as Qt,xa as uo,xb as Yt,ya as ze,zb as Ve,zc as kr,zd as xo}from"./chunk-4QGCX4EY.js";var $n=fl((Sv,Hn)=>{"use strict";var p={};p.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};p.localCName=p.generateIdentifier();p.splitLines=function(r){return r.trim().split(`
5
5
  `).map(e=>e.trim())};p.splitSections=function(r){return r.split(`
6
6
  m=`).map((t,i)=>(i>0?"m="+t:t).trim()+`\r
7
7
  `)};p.getDescription=function(r){let e=p.splitSections(r);return e&&e[0]};p.getMediaSections=function(r){let e=p.splitSections(r);return e.shift(),e};p.matchPrefix=function(r,e){return p.splitLines(r).filter(t=>t.indexOf(e)===0)};p.parseCandidate=function(r){let e;r.indexOf("a=candidate:")===0?e=r.substring(12).split(" "):e=r.substring(10).split(" ");let t={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let i=8;i<e.length;i+=2)switch(e[i]){case"raddr":t.relatedAddress=e[i+1];break;case"rport":t.relatedPort=parseInt(e[i+1],10);break;case"tcptype":t.tcpType=e[i+1];break;case"ufrag":t.ufrag=e[i+1],t.usernameFragment=e[i+1];break;default:t[e[i]]===void 0&&(t[e[i]]=e[i+1]);break}return t};p.writeCandidate=function(r){let e=[];e.push(r.foundation);let t=r.component;t==="rtp"?e.push(1):t==="rtcp"?e.push(2):e.push(t),e.push(r.protocol.toUpperCase()),e.push(r.priority),e.push(r.address||r.ip),e.push(r.port);let i=r.type;return e.push("typ"),e.push(i),i!=="host"&&r.relatedAddress&&r.relatedPort&&(e.push("raddr"),e.push(r.relatedAddress),e.push("rport"),e.push(r.relatedPort)),r.tcpType&&r.protocol.toLowerCase()==="tcp"&&(e.push("tcptype"),e.push(r.tcpType)),(r.usernameFragment||r.ufrag)&&(e.push("ufrag"),e.push(r.usernameFragment||r.ufrag)),"candidate:"+e.join(" ")};p.parseIceOptions=function(r){return r.substring(14).split(" ")};p.parseRtpMap=function(r){let e=r.substring(9).split(" "),t={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),t.name=e[0],t.clockRate=parseInt(e[1],10),t.channels=e.length===3?parseInt(e[2],10):1,t.numChannels=t.channels,t};p.writeRtpMap=function(r){let e=r.payloadType;r.preferredPayloadType!==void 0&&(e=r.preferredPayloadType);let t=r.channels||r.numChannels||1;return"a=rtpmap:"+e+" "+r.name+"/"+r.clockRate+(t!==1?"/"+t:"")+`\r
package/chunk-FWIDRPYU.js DELETED
@@ -1 +0,0 @@
1
- import{Fa as ce}from"./chunk-GHN6NWBT.js";import{D as oe,E as ne,l as re,m as se,p as te,s as ie}from"./chunk-NTFMMZRZ.js";import{$f as M,He as D,Hi as S,Ii as $,M as w,Pf as E,Qd as W,Qf as u,Sj as Z,_f as L,a as f,ag as A,b as y,ba as x,cg as N,ci as z,dg as T,ea as R,ee as v,fa as b,fi as j,g,gi as J,ji as X,kg as B,l as _,li as G,ni as V,nk as Q,pj as q,qj as H,sf as U,sk as ee,tf as P,uf as p,v as K,vg as F,vj as Y}from"./chunk-VESMHAEV.js";var C="public",ae=100,ke=(()=>{let I=class I{constructor(e,r,s,t,o,i,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=t,this.usersService=o,this.commentUtilsService=i,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=b(Y),this.adapterSelectorService=b(Z),this.currentUserPermissions$=new _(null),this.permissionsCache$=new _(null),this.permissionProvider$=new _(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",this.reportedUnknownFolderErrorCodes=new Set;try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(h){this.loggingService.catch("Error in UserPermissionService constructor:",h)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,t,o,i){try{return e.find(a=>a.resourceId===s&&a.type===t&&a.organizationId===o&&a.userId===i)?(r.push({userId:i,resourceId:s,organizationId:o,type:t,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===t&&a.organizationId===o&&a.userId===i))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(D.DEFAULT_VELT_CONTEXT))return!0;let s=r.filter(o=>!B(o));if(!s.length){if(r.some(c=>c.startsWith(D.VISIBILITY_ORG_PREFIX)))return!0;let i=`${D.VISIBILITY_SELF_PREFIX}${L(e).toString()}`;return r.includes(i)}let t=this.contactService.getUserAccessFieldsByUserId(e);return t?.length?s.every(o=>t.includes(o)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}isMetadataProbeUnanswerable(e){try{return this.adapterSelectorService?.isPortableBackendActive()?!re(e)&&!se(e):!1}catch(r){return this.loggingService.catch("Error in UserPermissionService isMetadataProbeUnanswerable: ",r),!1}}organizationDetails(e){return g(this,null,function*(){try{if(this.isMetadataProbeUnanswerable("organizationMetadata"))return{error:!1};let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:u.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:u.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("documentMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(t&&t?.errorCode)return{errorCode:u.PERMISSION_DENIED,error:!0};if(t&&!t?.metadata)return{errorCode:u.DOES_NOT_EXIST,error:!0};let o=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},o),t?.metadata??{}));let i,c=t?.metadata?.veltFolderId;if(c)try{i=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:c,organizationId:r}}))?.folderIamConfig?.accessType}catch(a){this.loggingService.catch("Error fetching folder accessType for document:",a)}return i||(i=t?.docIamConfig?.accessType),{error:!1,accessType:i}}catch(t){return this.loggingService.catch("Error in UserPermissionService documentDetails:",t),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("folderMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return t&&t?.errorCode?{errorCode:u.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:u.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:t?.folderIamConfig?.accessType}}catch(t){return this.loggingService.catch("Error in UserPermissionService folderDetails:",t),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return g(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let o=yield this.validateResources(t),[i,c]=yield this.fetchUserPermissionsFromDB(t),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(t,o,i,c);if(Object.keys(n).length>0){if(!e)this.setCurrentUserPermissions(n);else if(this.permissionsCacheGeneration===r){let d=this.buildPermissionsCacheKey(e);d!==null&&this.requestKeyedPermissionsCache.set(d,JSON.parse(JSON.stringify(n)))}}return n}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return g(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,t=this.requestKeyedPermissionsCache.get(r);if(t)return JSON.parse(JSON.stringify(t));let o=this.inFlightPermissionsRequests.get(r);if(o){let a=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let i=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,i),i.finally(()=>{this.inFlightPermissionsRequests.get(r)===i&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield i;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let t=e[s];t!==void 0&&(r[s]=Array.isArray(t)?[...t].sort():t)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let i=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:i,organizationId:i?N(i):void 0}}let t=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(i=>i.clientDocumentId),clientOrganizationId:t,organizationId:t?N(t):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t,clientOrganizationId:o}=e,i=[],c=[],a=r.length>0||s.length>0;t&&!a&&(i.push(this.organizationDetails(t)),c.push({id:o??"",type:"organization"})),r.forEach(l=>{i.push(this.folderDetails({folderId:T(l),organizationId:t??""})),c.push({id:l,type:"folder"})}),s.forEach(l=>{i.push(this.documentDetails({documentId:A(l),organizationId:t??""})),c.push({id:l,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(i),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,o)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let t=this.getPermissionsCache()??[];if(t.length===0)return e;let o=(n,d,h)=>t.some(l=>l?.userId===s&&l?.resourceId===n&&l?.type===d&&(!h||l?.organizationId===h)&&l?.hasAccess===!0),i=e.failedDocumentIds.filter(n=>!(n.errorCode===u.PERMISSION_DENIED&&o(n.id,p.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===u.PERMISSION_DENIED&&o(n.id,p.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===u.PERMISSION_DENIED&&r&&o(r,p.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:i,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return g(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],t=[],o,i={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let l=n.status==="fulfilled"?n.value.errorCode??u.SOMETHING_WENT_WRONG:u.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:l};switch(d.type){case"organization":if(o=m,l===u.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":t.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(i[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:t,failedOrganizationId:o,folderAccessTypes:i,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t}=e,o=[this.authService.getUser()?.userId??""],i=[...r.map(n=>T(n)),...s.map(n=>A(n)),t??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:o,organizationId:t}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:o,organizationId:t,resourceIds:i})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,t){let{folderIds:o,documentIds:i,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,l={};return this.processRegularUserPermissions(l,s,o,i,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(l,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(l,t),this.processContextPermissions(l),l}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,t,o,i,c,a,n,d,h,l){for(let m of r)for(let O of m)O?.user?.userId&&(e[O.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,O,c,d,l)}),{documents:this.buildDocumentPermissions(t,O,a,h,l),organization:{[o]:this.buildOrganizationPermission(i,O,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,t,o,i,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!o&&!!r,h=(s?.length??0)>0,l=(t?.length??0)>0;if(!d&&!h&&!l)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(o.errorCode,"organization"),errorCode:o.errorCode})),h){e[n].folders||(e[n].folders={});for(let m of s)e[n].folders[m.id]||(e[n].folders[m.id]=f({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===u.PERMISSION_DENIED&&{accessType:i[m.id]??a??C}))}if(l){e[n].documents||(e[n].documents={});for(let m of t)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===u.PERMISSION_DENIED&&{accessType:c[m.id]??a??C}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case u.DOES_NOT_EXIST:return`${r} does not exist`;case u.PERMISSION_DENIED:return`User does not have access to ${r}`;case u.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,t,o){return e.reduce((i,c)=>{let a=s.find(n=>n.id===c);return a?i[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===u.PERMISSION_DENIED&&{accessType:t[c]??o??C}):i[c]={accessRole:r.viewerFolderIds?.includes(T(c))?E.VIEWER:E.EDITOR,accessType:t[c]??o??C},i},{})}buildDocumentPermissions(e,r,s,t,o){return e.reduce((i,c)=>{let a=s.find(n=>n.id===c);return a?i[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===u.PERMISSION_DENIED&&{accessType:t[c]??o??C}):i[c]={accessRole:r.viewerDocumentIds?.includes(A(c))?E.VIEWER:E.EDITOR,accessType:t[c]??o??C},i},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?E.VIEWER:E.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].folders||(e[s].folders={}),e[s].folders[t]={accessRole:o??E.EDITOR,expiresAt:i}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].documents||(e[s].documents={}),e[s].documents[t]={accessRole:o??E.EDITOR,expiresAt:i}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].organization||(e[s].organization={}),e[s].organization[t]={accessRole:o??E.EDITOR,expiresAt:i}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let t=!0,o=this.getCurrentUserPermissionsWithServerIds(),i=this.authService.getUser()?.userId??"";return o&&(e&&typeof e=="string"&&o?.[i]?.organization?.[e]&&(o?.[i]?.organization?.[e]?.accessRole===E.VIEWER||o?.[i]?.organization?.[e]?.errorCode===u.PERMISSION_DENIED)&&(t=!1),r&&typeof r=="string"&&o?.[i]?.folders?.[r]&&(o?.[i]?.folders?.[r]?.accessRole===E.VIEWER||o?.[i]?.folders?.[r]?.errorCode===u.PERMISSION_DENIED)&&(t=!1),s&&typeof s=="string"&&o?.[i]?.documents?.[s]&&(o?.[i]?.documents?.[s]?.accessRole===E.VIEWER||o?.[i]?.documents?.[s]?.errorCode===u.PERMISSION_DENIED)&&(t=!1)),t}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(w(z))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let t=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[t]){let o=N(t);r[s].organization&&(r[s].organization[o]=r[s].organization[t],delete r[s].organization[t])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([o,i])=>[T(o),i]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([o,i])=>[A(o),i])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(K(e=>this.refactorPermissionsWithServerIds(e)),w(z))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return g(this,null,function*(){let e=F();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(o=>{o.userId===s&&o.hasAccess&&(o.type===p.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},o),{hasAccess:!1})):r.push(y(f({},o),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let o=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return g(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let t=this.getPermissionsCache()??[];s.forEach(c=>{t=t.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(t);let o=this.docService.getDocContext(),i=yield this.revokeAccess({requests:s,userId:r,currentContext:o});i.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:i,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:i,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(t){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let o=F();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let i=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,i,d.clientDocumentId,p.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,i,r,p.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,i,c,p.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&X({input:s}).forEach(h=>{let l=JSON.stringify(h.access);n=this.collectRevokeRequest(n,i,l,p.CONTEXT,c,a)}),this.setPermissionsCache(n),i.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:i}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:i}}),i.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=o,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(i){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",i)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let t={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?t.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:t})})}sendGetAccessToProxy(t){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendGetAccessToPortableGateway({requests:e,retryConfig:s?.retryConfig});let o=$(this.functions,V({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield G({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:o,userId:r})})}sendGetAccessToPortableGateway(s){return g(this,arguments,function*({requests:e,retryConfig:r}){try{let t=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let i of M(e,ae)){let c=yield t.getAccess(r===void 0?{scope:"org",data:i}:{scope:"org",data:i,metadata:{retryConfig:r}});if(!c?.ok){let n=c?.code;return this.loggingService.catch("Tier B getAccess denied/failed at the gateway: ",c),{data:[],success:!1,statusCode:this.denialCodeToStatusCode(n)}}let a=c.data?.data??[];o.push(...this.dropUnrequestedEntries(a,i))}return{data:this.skipNotProvidedFolderEntries(o),success:!0,statusCode:200}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",t),{data:[],success:!1,statusCode:500}}})}skipNotProvidedFolderEntries(e){try{this.reportUnrecognizedFolderErrorCodes(e);let r=e.filter(s=>!(s?.type===p.FOLDER&&s?.errorCode==="not_provided"));return r.length!==e.length&&this.loggingService.log(`[WB] Tier B getAccess: ${e.length-r.length} folder answer(s) skipped (errorCode 'not_provided' \u2014 folder subsystem not provisioned on this gateway)`),r}catch(r){return this.loggingService.catch("Error in UserPermissionService skipNotProvidedFolderEntries: ",r),e}}dropUnrequestedEntries(e,r){try{if(!e?.length)return e??[];let s=i=>`${i?.userId}|${i?.resourceId}|${i?.organizationId}|${i?.type}`,t=new Set((r??[]).map(i=>`${i?.userId}|${i?.resource?.id}|${i?.resource?.organizationId}|${i?.resource?.type}`)),o=e.filter(i=>t.has(s(i)));return o.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(i=>!t.has(s(i))),void 0,!0),o}catch(s){return this.loggingService.catch("Error in UserPermissionService dropUnrequestedEntries: ",s),e}}reportUnrecognizedFolderErrorCodes(e){try{for(let r of e??[]){let s=r?.errorCode;!s||r?.type!==p.FOLDER||s==="not_provided"||this.reportedUnknownFolderErrorCodes.has(s)||(this.reportedUnknownFolderErrorCodes.add(s),console.warn(`Velt [portable backend]: a folder permission entry carried an unrecognised errorCode '${s}'. It is being consumed verbatim (hasAccess is honoured as sent). If your gateway means the folder subsystem is not provisioned, the expected literal is the exact lowercase 'not_provided' \u2014 anything else reads as a REAL denial and will withhold folder-scoped access.`))}}catch(r){this.loggingService.catch("Error in UserPermissionService reportUnrecognizedFolderErrorCodes: ",r)}}denialCodeToStatusCode(e){switch(e){case"unauthenticated":return 401;case"permission-denied":return 403;case"not-found":return 404;case"invalid-argument":return 400;case"failed-precondition":return 412;case"resource-exhausted":return 429;case"unimplemented":return 501;default:return 500}}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return g(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return g(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),t=r?.resolveTimeout??6e4,o=yield j(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),t),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!o||!o.success||o.statusCode!==200)throw new Error(o?.message??"Client permission resolver failed");let i=o.data;if(!Array.isArray(i))throw new Error("Client permission resolver returned a malformed payload");return i})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},t=r.endpointConfig?.url?.trim();if(t)return J(t,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let o=yield r.resolvePermissions(s);if(Array.isArray(o))return{data:o,success:!0,statusCode:200};let i=o,c=i?.statusCode??(i?.success===!1?500:200),a=i?.success!==!1&&c===200;return{data:Array.isArray(i?.data)?i.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:i?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,t=new Promise((o,i)=>{s=setTimeout(()=>i(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),t])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(t){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendRevokeAccessToPortableGateway({requests:e,metadata:this.buildRevokeAccessMetadata(s)});let o=$(this.functions,V({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield G({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:this.buildRevokeAccessMetadata(s)},getSdkProxy:o,userId:r})})}buildRevokeAccessMetadata(e){return f({retryConfig:this.getPermissionProviderRetryConfig()},e?.access&&{currentContext:e})}sendRevokeAccessToPortableGateway(s){return g(this,arguments,function*({requests:e,metadata:r}){try{let t=this.adapterSelectorService.resolveDbAdapter();for(let o of M(e,ae)){let i=yield t.revokeAccess({scope:"org",data:o,metadata:r});if(!i?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",i),{success:!1}}return{success:!0}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",t),{success:!1}}})}onResourceAccessRequired(i){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:t,fromCache:o=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&o&&(e.forEach(n=>{let d=a?.find(h=>h.resourceId===n.resource.id&&h.type===n.resource.type&&h.userId===n.userId&&h.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:o,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??t??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:o}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(t=>{let o=`${t.userId}_${t.resourceId}_${t.organizationId}_${t.type}`;r.set(o,t)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};I.\u0275fac=function(r){return new(r||I)(R(ee),R(ne),R(q),R(oe),R(te),R(ie),R(Q),R(W),R(H),R(ce))},I.\u0275prov=x({token:I,factory:I.\u0275fac,providedIn:"root"});let k=I;return k})();export{ke as a};