@veltdev/sdk-dev 6.0.8-beta.2 → 6.0.8-beta.4

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 (66) hide show
  1. package/app/models/data/comment-action.data.model.d.ts +55 -0
  2. package/app/models/data/comment-annotation.data.model.d.ts +11 -0
  3. package/app/models/data/comment-events.data.model.d.ts +52 -0
  4. package/app/models/data/comment-progress.data.model.d.ts +127 -0
  5. package/app/models/data/comment.data.model.d.ts +29 -0
  6. package/app/models/element/comment-element.model.d.ts +9 -0
  7. package/app/utils/enums.d.ts +1 -0
  8. package/{chunk-NCVN3JXT.js → chunk-2VSCJ7FP.js} +6 -6
  9. package/chunk-3W7PWPIA.js +193 -0
  10. package/{chunk-3XNLR5I6.js → chunk-44QKIIUD.js} +1 -1
  11. package/{chunk-ANVOXADQ.js → chunk-4NY6TY72.js} +1 -1
  12. package/{chunk-33F6VZ2D.js → chunk-4Z6JEK4C.js} +1 -1
  13. package/{chunk-IOANBPOF.js → chunk-54WPSIBC.js} +1 -1
  14. package/{chunk-T4CM6UKZ.js → chunk-5AD56Z43.js} +1 -1
  15. package/{chunk-HNZ452CD.js → chunk-5AXDQN2Z.js} +1 -1
  16. package/{chunk-5YU74OX2.js → chunk-67WASIND.js} +1 -1
  17. package/{chunk-JOD7T5HO.js → chunk-6ARAZSKF.js} +1 -1
  18. package/chunk-6GPW7ZK5.js +1 -0
  19. package/{chunk-MRNSRINQ.js → chunk-6VS6CXUM.js} +1 -1
  20. package/chunk-C45R3XT6.js +1 -0
  21. package/{chunk-MIANWP6R.js → chunk-C6NXU52W.js} +1 -1
  22. package/{chunk-D2BOLY5Q.js → chunk-F4COO6HD.js} +1 -1
  23. package/{chunk-Y6KJEASI.js → chunk-F5F6L463.js} +1 -1
  24. package/{chunk-N4APL3ZG.js → chunk-K47CMSNK.js} +1 -1
  25. package/{chunk-24U4LEAT.js → chunk-KGSCJNID.js} +1 -1
  26. package/chunk-LC33EWB5.js +1 -0
  27. package/{chunk-KES24H7E.js → chunk-MIVF7JMQ.js} +1 -1
  28. package/{chunk-7DVALKQ7.js → chunk-PPIN2ZDO.js} +1 -1
  29. package/{chunk-OTEHXO3L.js → chunk-PSDDJB4F.js} +1 -1
  30. package/{chunk-RTIZJ4JW.js → chunk-RD4WD7HR.js} +1 -1
  31. package/{chunk-WNW7AS77.js → chunk-T4Z2W6NR.js} +1 -1
  32. package/{chunk-H2PBKB34.js → chunk-TYOTWEG4.js} +1 -1
  33. package/{chunk-KMCCIFJ3.js → chunk-UGQYGMGF.js} +1 -1
  34. package/{chunk-QC3HLRNI.js → chunk-UZW6GB3Q.js} +1 -1
  35. package/{chunk-I3U6YUMT.js → chunk-WNQGJ6NQ.js} +1 -1
  36. package/{chunk-LFEKCFWQ.js → chunk-WUADE2PV.js} +1 -1
  37. package/{chunk-WNOKX7ML.js → chunk-YMLBHLGQ.js} +1 -1
  38. package/{chunk-CRZGZZVQ.js → chunk-YTAAOIBL.js} +9 -9
  39. package/{chunk-LS3GLCPX.js → chunk-Z4PTG3MC.js} +1 -1
  40. package/{chunk-23NZV3J5.js → chunk-ZDDZXCPC.js} +1 -1
  41. package/models.d.ts +2 -0
  42. package/package.json +1 -1
  43. package/velt-activity-log.js +1 -1
  44. package/velt-area.js +1 -1
  45. package/velt-arrow.js +1 -1
  46. package/velt-comment.js +7 -7
  47. package/velt-crdt.js +1 -1
  48. package/velt-cursor.js +1 -1
  49. package/velt-huddle.js +1 -1
  50. package/velt-live-state-sync.js +1 -1
  51. package/velt-notification.js +1 -1
  52. package/velt-presence.js +1 -1
  53. package/velt-reaction.js +1 -1
  54. package/velt-recorder.js +1 -1
  55. package/velt-rewriter.js +1 -1
  56. package/velt-selection.js +1 -1
  57. package/velt-tag.js +1 -1
  58. package/velt-user-invite.js +1 -1
  59. package/velt-user-request.js +1 -1
  60. package/velt-video-player.js +1 -1
  61. package/velt-views.js +1 -1
  62. package/velt.js +3 -3
  63. package/chunk-7LUSUNI3.js +0 -1
  64. package/chunk-BARZUD2Z.js +0 -1
  65. package/chunk-G4MWCI3H.js +0 -193
  66. package/chunk-QVPRXGEH.js +0 -1
@@ -1 +1 @@
1
- import{a as Zt}from"./chunk-ANVOXADQ.js";import{a as Qt}from"./chunk-OTEHXO3L.js";import{$ as K,$e as q,Ai as Wt,Bf as gt,Bi as st,Cf as z,Ch as L,Df as At,Dh as tt,E as F,Ed as Nt,Ee as P,Ef as ft,Fh as Ft,Fi as kt,G as V,Gi as rt,Hh as Pt,Hi as nt,J as k,Ki as mt,L as J,M as lt,Mi as at,Ni as Jt,O as St,Od as It,Oi as Kt,Pi as qt,Qf as Ut,Rf as Tt,Sh as zt,T as I,Uf as Et,Uh as Bt,Vf as $t,W as vt,Yf as Rt,a as D,af as Q,b as T,be as Ot,bg as wt,ca as m,cg as dt,da as pt,g as E,hg as Z,ii as it,ji as xt,ki as et,l as O,li as jt,oe as yt,oi as Ht,p as G,q as ct,qh as Mt,qi as Vt,r as C,si as Lt,ti as ot,uf as bt,ui as Yt,v as N,vi as _t,w as W,xh as ht,xi as Gt,yf as Dt,zf as Ct,zh as X,zi as ut}from"./chunk-CRZGZZVQ.js";var Xt=(()=>{let A=class A{constructor(t,i,e,o,s,n,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=n,this.serviceBook=r,this.serviceBook.set(Pt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of s)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(zt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return E(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield wt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};A.\u0275fac=function(i){return new(i||A)(m(nt),m(et),m(rt),m(ot),m(st),m(at),m(it))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();var ji=(()=>{let A=class A{constructor(t,i,e,o,s,n,r,a,c,l,g,f,d,h,p,$,M,S,U,R,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=n,this.commentUtilsService=r,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=h,this.notificationUtilsService=p,this.usersService=$,this.functions=M,this.userPermissionService=S,this.coreActionsService=U,this.serviceBook=R,this.realtimeAdapter=w,this.endpointsService=pt(Ht),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new O(null),this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.settingsInitialConfig$=new O([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(Ft,this),this.serviceBook.observe(Bt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(F(v=>!!v),k(1)).subscribe(v=>{if(v){this.db=v;try{let u=this.configService.getProxyConfig(),b=this.endpointsService.getNotificationsDbUrl();Dt(b)?this.notificationsDb=null:(u?.v1DbHost&&b&&(b=Ct(b,u.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(b),u?.v1DbHost&&b&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(u){this.loggingService.catch("Error initializing notifications DB, using default: ",u),this.notificationsDb=v}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},v=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",v)}),this.authService.getUser$().subscribe(v=>{v?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(u=>{this.notificationsByDocumentIdSubscription[u]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let u=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(b=>{let x=u?.[b]?.notifications;x?.length&&x.forEach(y=>{this.notificationUtilsService.mergeLocationWithNotification({notification:y},v)?.notification})}),this.notificationsByDocumentIdMap$.next(u)}})}catch(v){this.loggingService.catch("Error in NotificationService constructor: ",v)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return E(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=z(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let a=r?.values?.find(c=>c.id===r.default);s[r.id]=a||r?.values?.[0]||{id:"NONE",name:"None"}}});let n={};Object.keys(s).forEach(r=>{n[r]=s[r].id}),yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=z(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(F(i=>i===!0),I(()=>W([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(F(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>ct(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(N(s=>{s?.data?.notificationsConfig&&!Z(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(N(i=>{})):C(void 0)))),vt(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(lt(),N(([t,i])=>{let e=t?.map(a=>a.documentId),o=i?.map(a=>a.documentId),s=e?.filter(a=>!o?.includes(a)),n=o?.map(a=>({documentId:a,timestamp:i?.find(c=>c.documentId===a)?.timestamp})).filter(a=>!e?.includes(a.documentId)),r=o?.map(a=>{let c=i?.find(l=>l.documentId===a)?.timestamp;return{documentId:a,timestamp:c}}).filter(a=>{let c=t?.find(l=>l.documentId===a.documentId)?.timestamp;return c&&a.timestamp&&c!==a.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(a=>{this.removeNotificationsForDocumentId(a)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(N(e=>{let o=null,s=this.configService.getApiKey(),n=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&n&&(o=new mt({apiKey:s,organizationId:n})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let n=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;n.setDate(n.getDate()-r);let a=n.getTime(),c=[Yt(ut("timestamp",">=",a),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(Gt("timestamp","desc")),c.push(_t(t)));let l=e?.userId??"";return ct(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===bt.PERMISSION_DENIED?C(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(N(f=>f?.data),N(f=>{let d=[];return Object.keys(f||{}).forEach(h=>{let p=this.commonDbService.shouldUseFirestore()?f[h]?.timestamp??0:f[h],$=this.commonDbService.shouldUseFirestore()?f[h]?.deletedNotification??!1:!1;if($&&$.id&&$?.timestamp===p){let M=$.id,S=f[h]?.metadata?.documentId,U=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),R=U?.[S]??{documentMetadata:null,notifications:[]},w=R.notifications??[],v=w?.findIndex(u=>u.id===M);v!==-1&&(w.splice(v,1),this.notificationsByDocumentIdMap$.next(T(D({},U),{[S]:T(D({},R),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(M)&&this.notificationResolverService.deleteNotification(M,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:h,timestamp:p})}),d}),V(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),C([]))))))}return C(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),C([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}else{let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}s.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),n;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}n.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],a=new Map(r.map(c=>[c.notificationId,c]));n.forEach(c=>{a.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(a.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return E(this,null,function*(){try{if(t?.length){let e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let s=this.getStartAtTimestamp(),n={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(n[S.documentId]=U)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let S=[];if(t.forEach(u=>{this.docService.getDocumentMetadata(u.documentId)||S.push(u.documentId)}),S.length){let u=this.authService.getUser(),b=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let x=yield ht({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:u?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:S},getSdkProxy:b,userId:u?.userId??""});if(x?.data?.length){let y={};x.data.forEach(H=>{H?.documentId&&(y[H.documentId]=H)}),this.docService.setAllDocumentMetadata(D(D({},this.docService.getAllDocumentMetadataMap()),y))}}catch(x){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",x)}}let U=[],R=[];t.forEach(u=>{let b=this.docService.getDocumentMetadata(u.documentId);b?.clientDocumentId?U.push({userId:this.authService.getUser()?.userId??"",resource:D({id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},b.folderId&&{parentFolderId:b.folderId})}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=$t();this.coreActionsService.triggerAction(Ot.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:w,methodName:q.GET_NOTIFICATIONS,source:"internal",payload:{requests:U}});let v=yield this.userPermissionService?.onResourceAccessRequired({requests:U,uniqueId:w,methodName:q.GET_NOTIFICATIONS});v?.success&&v?.data?.length?v.data.forEach(u=>{!u.hasAccess&&u.resourceId&&(t=t.filter(b=>b.documentId!==At(u.resourceId)))}):t=[]}catch(S){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",S),t=[]}if(!t.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let r=this.userPermissionService?.getPermissionsCache()?.filter(S=>S.type===Q.CONTEXT),a={organizationId:o,documentIds:t.filter(S=>!!S.documentId&&!!S.timestamp).map(S=>({documentId:S.documentId,timestamp:S.timestamp??0})),timestamp:s,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:r,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},c=yield this.notificationUtilsService.handleNotificationEncryption({data:a}),l=yield e({veltData:c}),g=l?.data?.data?.veltData||{},f=l?.data?.data?.veltAdditionalData||{},d="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),h=yield dt(g,d),{userNotifications:p=[],userNotificationIdsInDocNotifications:$=[],permissionResults:M=[]}=yield dt(f,d);if(this.userPermissionService?.getIsContextEnabled()){let S=[...this.userPermissionService?.getPermissionsCache()??[],...M??[]];this.userPermissionService?.setPermissionsCache(S)}if(h&&typeof h=="object"){let S=this.usersService.userDataProviderAvailable(),U=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),R=this.notificationResolverService.notificationDataProviderAvailable(),w=[],v=[],u=[];Object.keys(h).forEach((y,H)=>{let _=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(_){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],_))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:_}))}let Y=h[y].notifications||[];Y.forEach(B=>{$.includes(B.notificationId)&&!p.find(ti=>ti.notificationId===B.notificationId)&&p.push(JSON.parse(JSON.stringify(B))),B.notification=this.getClientNotificationObject(B)}),this.setNotificationForDocumentIdInCache(y,_,Y),S&&(w.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldAwait:!0,forceResolve:!0})),w.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldAwait:!0,forceResolve:!0}))),U&&(v.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldNotificationResolverAwait:!0})),u.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldNotificationResolverAwait:!0})))});let b=JSON.parse(JSON.stringify(p));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...p]),(R||S||U)&&(()=>{let y=Promise.resolve();if(R&&(y=y.then(()=>Promise.allSettled(u)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"notification"),this.resolveAndMergeUserNotifications(b,"notification")})),S&&(y=y.then(()=>Promise.allSettled(w)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"user"),this.resolveAndMergeUserNotifications(b,"user")})),U){let H=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",H)})}return y})().catch(y=>{this.loggingService.catch("Error in NotificationService resolveChain: ",y)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),a=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let h=d?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=n||h.metadata.organizationMetadata,h.metadata.documentMetadata=i||h.metadata.documentMetadata),c&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},c)?.notification),h):null})?.filter(d=>!!d)||[],g=new Map(a.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,h)=>(h.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(D({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>C(t).pipe(F(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,a)=>a.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return W([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),C({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=s(a);c!=null&&n.add(c)});let r=[...o];return e.forEach(a=>{let c=s(a);c!=null&&n.has(c)||(c!=null&&n.add(c),r.push(a))}),r.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(D({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(T(D({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),J(),F(t=>!!t),V(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),G))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:z(t),isCollection:!1,useCollectionGroup:!1}}).pipe(V(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),G))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(N(i=>i?.organizationId??""),J(),lt(),F(([i])=>!!i),V(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),G))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let n=Number(o[s]);i[s]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(D({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(D({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return E(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let a=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(a);c?c.push(r):s.set(a,[r])}let n=[];for(let[r,a]of s){let c=a.reduce((g,f,d)=>{let h=f?.notificationId??f?.id??`__cross_org_${d}`;return g[h]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),n.push(...Object.values(l??{}))}return n}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return E(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return E(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return E(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return E(this,null,function*(){let i=this.authService.getUser(),e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:D({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,n=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),a=r?o.organizationIds.filter(d=>!!d).map(d=>ft(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>ft(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(a);d=d.filter($=>p.has($))}d=Array.from(new Set(d)),f.organizationIds=d;let h={};d.forEach(p=>{h[p]=this.crossOrgSeenTimestamps[p]??this.getStartAtTimestamp()}),f.orgTimestamps=h}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,n=o?i.filter(r=>{let a=r?.id??r?.notificationId,c=a!=null&&e.has(a);return c&&(s=!0),!c}):i.map(r=>{let a=r?.id??r?.notificationId;return a!=null&&e.has(a)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=gt(t)),i&&typeof i=="object"){let s=Rt(i);e=gt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(F(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(s.featureAllowed=n,s))):C(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(s).pipe(I(n=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,n.documentPaths=r,n)))),I(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(F(i=>!!i),N(i=>T(D({},t),{config:i})),I(i=>this.authService.getUser$().pipe(N(e=>T(D({},i),{user:e})))),I(i=>Et(i.config,i.user,yt.NOTIFICATION)?C(T(D({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(T(D({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(F(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(V(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),C(null))),N(s=>{let n=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(r);let a=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=z(t?.email));let o;t?.userId&&(o=z(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let a=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(a=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:a,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,a)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],s.set(a,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let n=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=z(n?.email));let c=null;n?.userId&&(c=z(n?.userId));let l=!1,g=!0;(a&&r.notifyUsers?.[a]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=T(D(D({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||s?.notificationSourceData&&(d=s?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(N(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return W([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=Array.isArray(i)?i:[],o=null;return t&&(o=[],t.forEach(s=>{s.notifications.forEach(n=>{o?.push(n)})})),e.length?t?this.mergeCrossOrgForYou(o||[],e):null:t?o.sort((s,n)=>n.timestamp-s.timestamp):null}))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=Ut(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let s=Object.values(t?.annotationData?.subscribedUsers||{}).map(r=>r?.user?.userId).filter(r=>!!r),n=Tt(t?.annotationData,s);n.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...n])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&s.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!s.has(n.id)&&s.set(n.id,n)}),Array.from(s.values()).sort((n,r)=>(r.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),St()):C(null)),J(Mt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,n=e.replace(s,(r,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:r);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return E(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let d=l[f];if(!d.some(p=>p.notificationId===g.id))i=i.filter(p=>p.notificationId!==g.id);else{let p=i.find(M=>M.notificationId===g.id),$=d.find(M=>M.notificationId===g.id);p&&$?.views&&(p.views=$.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let r=n.metadata?.documentId;if(r&&o?.[r]){let a=o?.[r]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[r].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!Z(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return E(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(N(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),C({forYou:null,all:null})}}setNotificationAsRead(e){return E(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=z(o?.userId),{metadata:n}=t;if(n){let{apiKey:r,organizationId:a,documentId:c}=n;if(r&&a&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return E(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return E(this,null,function*(){try{let i=this.authService.getUser(),e=z(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),n=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};A.\u0275fac=function(i){return new(i||A)(m(Nt),m(xt),m(ot),m(jt),m(qt),m(Jt),m(nt),m(st),m(at),m(Wt),m(kt),m(Lt),m(Qt),m(et),m(Xt),m(rt),m(It),m(Zt),m(Vt),m(it),m(Kt))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();export{Xt as a,ji as b};
1
+ import{a as Zt}from"./chunk-4NY6TY72.js";import{a as Qt}from"./chunk-PSDDJB4F.js";import{$ as K,$e as q,Ai as Wt,Bf as gt,Bi as st,Cf as z,Ch as L,Df as At,Dh as tt,E as F,Ed as Nt,Ee as P,Ef as ft,Fh as Ft,Fi as kt,G as V,Gi as rt,Hh as Pt,Hi as nt,J as k,Ki as mt,L as J,M as lt,Mi as at,Ni as Jt,O as St,Od as It,Oi as Kt,Pi as qt,Qf as Ut,Rf as Tt,Sh as zt,T as I,Uf as Et,Uh as Bt,Vf as $t,W as vt,Yf as Rt,a as D,af as Q,b as T,be as Ot,bg as wt,ca as m,cg as dt,da as pt,g as E,hg as Z,ii as it,ji as xt,ki as et,l as O,li as jt,oe as yt,oi as Ht,p as G,q as ct,qh as Mt,qi as Vt,r as C,si as Lt,ti as ot,uf as bt,ui as Yt,v as N,vi as _t,w as W,xh as ht,xi as Gt,yf as Dt,zf as Ct,zh as X,zi as ut}from"./chunk-YTAAOIBL.js";var Xt=(()=>{let A=class A{constructor(t,i,e,o,s,n,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=n,this.serviceBook=r,this.serviceBook.set(Pt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of s)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(zt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return E(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield wt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};A.\u0275fac=function(i){return new(i||A)(m(nt),m(et),m(rt),m(ot),m(st),m(at),m(it))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();var ji=(()=>{let A=class A{constructor(t,i,e,o,s,n,r,a,c,l,g,f,d,h,p,$,M,S,U,R,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=n,this.commentUtilsService=r,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=h,this.notificationUtilsService=p,this.usersService=$,this.functions=M,this.userPermissionService=S,this.coreActionsService=U,this.serviceBook=R,this.realtimeAdapter=w,this.endpointsService=pt(Ht),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new O(null),this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.settingsInitialConfig$=new O([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(Ft,this),this.serviceBook.observe(Bt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(F(v=>!!v),k(1)).subscribe(v=>{if(v){this.db=v;try{let u=this.configService.getProxyConfig(),b=this.endpointsService.getNotificationsDbUrl();Dt(b)?this.notificationsDb=null:(u?.v1DbHost&&b&&(b=Ct(b,u.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(b),u?.v1DbHost&&b&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(u){this.loggingService.catch("Error initializing notifications DB, using default: ",u),this.notificationsDb=v}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},v=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",v)}),this.authService.getUser$().subscribe(v=>{v?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(u=>{this.notificationsByDocumentIdSubscription[u]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let u=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(b=>{let x=u?.[b]?.notifications;x?.length&&x.forEach(y=>{this.notificationUtilsService.mergeLocationWithNotification({notification:y},v)?.notification})}),this.notificationsByDocumentIdMap$.next(u)}})}catch(v){this.loggingService.catch("Error in NotificationService constructor: ",v)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return E(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=z(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let a=r?.values?.find(c=>c.id===r.default);s[r.id]=a||r?.values?.[0]||{id:"NONE",name:"None"}}});let n={};Object.keys(s).forEach(r=>{n[r]=s[r].id}),yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=z(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(F(i=>i===!0),I(()=>W([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(F(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>ct(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(N(s=>{s?.data?.notificationsConfig&&!Z(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(N(i=>{})):C(void 0)))),vt(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(lt(),N(([t,i])=>{let e=t?.map(a=>a.documentId),o=i?.map(a=>a.documentId),s=e?.filter(a=>!o?.includes(a)),n=o?.map(a=>({documentId:a,timestamp:i?.find(c=>c.documentId===a)?.timestamp})).filter(a=>!e?.includes(a.documentId)),r=o?.map(a=>{let c=i?.find(l=>l.documentId===a)?.timestamp;return{documentId:a,timestamp:c}}).filter(a=>{let c=t?.find(l=>l.documentId===a.documentId)?.timestamp;return c&&a.timestamp&&c!==a.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(a=>{this.removeNotificationsForDocumentId(a)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(N(e=>{let o=null,s=this.configService.getApiKey(),n=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&n&&(o=new mt({apiKey:s,organizationId:n})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let n=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;n.setDate(n.getDate()-r);let a=n.getTime(),c=[Yt(ut("timestamp",">=",a),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(Gt("timestamp","desc")),c.push(_t(t)));let l=e?.userId??"";return ct(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===bt.PERMISSION_DENIED?C(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(N(f=>f?.data),N(f=>{let d=[];return Object.keys(f||{}).forEach(h=>{let p=this.commonDbService.shouldUseFirestore()?f[h]?.timestamp??0:f[h],$=this.commonDbService.shouldUseFirestore()?f[h]?.deletedNotification??!1:!1;if($&&$.id&&$?.timestamp===p){let M=$.id,S=f[h]?.metadata?.documentId,U=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),R=U?.[S]??{documentMetadata:null,notifications:[]},w=R.notifications??[],v=w?.findIndex(u=>u.id===M);v!==-1&&(w.splice(v,1),this.notificationsByDocumentIdMap$.next(T(D({},U),{[S]:T(D({},R),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(M)&&this.notificationResolverService.deleteNotification(M,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:h,timestamp:p})}),d}),V(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),C([]))))))}return C(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),C([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}else{let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}s.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),n;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}n.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],a=new Map(r.map(c=>[c.notificationId,c]));n.forEach(c=>{a.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(a.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return E(this,null,function*(){try{if(t?.length){let e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let s=this.getStartAtTimestamp(),n={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(n[S.documentId]=U)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let S=[];if(t.forEach(u=>{this.docService.getDocumentMetadata(u.documentId)||S.push(u.documentId)}),S.length){let u=this.authService.getUser(),b=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let x=yield ht({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:u?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:S},getSdkProxy:b,userId:u?.userId??""});if(x?.data?.length){let y={};x.data.forEach(H=>{H?.documentId&&(y[H.documentId]=H)}),this.docService.setAllDocumentMetadata(D(D({},this.docService.getAllDocumentMetadataMap()),y))}}catch(x){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",x)}}let U=[],R=[];t.forEach(u=>{let b=this.docService.getDocumentMetadata(u.documentId);b?.clientDocumentId?U.push({userId:this.authService.getUser()?.userId??"",resource:D({id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},b.folderId&&{parentFolderId:b.folderId})}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=$t();this.coreActionsService.triggerAction(Ot.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:w,methodName:q.GET_NOTIFICATIONS,source:"internal",payload:{requests:U}});let v=yield this.userPermissionService?.onResourceAccessRequired({requests:U,uniqueId:w,methodName:q.GET_NOTIFICATIONS});v?.success&&v?.data?.length?v.data.forEach(u=>{!u.hasAccess&&u.resourceId&&(t=t.filter(b=>b.documentId!==At(u.resourceId)))}):t=[]}catch(S){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",S),t=[]}if(!t.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let r=this.userPermissionService?.getPermissionsCache()?.filter(S=>S.type===Q.CONTEXT),a={organizationId:o,documentIds:t.filter(S=>!!S.documentId&&!!S.timestamp).map(S=>({documentId:S.documentId,timestamp:S.timestamp??0})),timestamp:s,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:r,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},c=yield this.notificationUtilsService.handleNotificationEncryption({data:a}),l=yield e({veltData:c}),g=l?.data?.data?.veltData||{},f=l?.data?.data?.veltAdditionalData||{},d="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),h=yield dt(g,d),{userNotifications:p=[],userNotificationIdsInDocNotifications:$=[],permissionResults:M=[]}=yield dt(f,d);if(this.userPermissionService?.getIsContextEnabled()){let S=[...this.userPermissionService?.getPermissionsCache()??[],...M??[]];this.userPermissionService?.setPermissionsCache(S)}if(h&&typeof h=="object"){let S=this.usersService.userDataProviderAvailable(),U=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),R=this.notificationResolverService.notificationDataProviderAvailable(),w=[],v=[],u=[];Object.keys(h).forEach((y,H)=>{let _=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(_){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],_))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:_}))}let Y=h[y].notifications||[];Y.forEach(B=>{$.includes(B.notificationId)&&!p.find(ti=>ti.notificationId===B.notificationId)&&p.push(JSON.parse(JSON.stringify(B))),B.notification=this.getClientNotificationObject(B)}),this.setNotificationForDocumentIdInCache(y,_,Y),S&&(w.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldAwait:!0,forceResolve:!0})),w.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldAwait:!0,forceResolve:!0}))),U&&(v.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldNotificationResolverAwait:!0})),u.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldNotificationResolverAwait:!0})))});let b=JSON.parse(JSON.stringify(p));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...p]),(R||S||U)&&(()=>{let y=Promise.resolve();if(R&&(y=y.then(()=>Promise.allSettled(u)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"notification"),this.resolveAndMergeUserNotifications(b,"notification")})),S&&(y=y.then(()=>Promise.allSettled(w)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"user"),this.resolveAndMergeUserNotifications(b,"user")})),U){let H=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",H)})}return y})().catch(y=>{this.loggingService.catch("Error in NotificationService resolveChain: ",y)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),a=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let h=d?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=n||h.metadata.organizationMetadata,h.metadata.documentMetadata=i||h.metadata.documentMetadata),c&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},c)?.notification),h):null})?.filter(d=>!!d)||[],g=new Map(a.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,h)=>(h.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(D({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>C(t).pipe(F(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,a)=>a.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return W([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),C({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=s(a);c!=null&&n.add(c)});let r=[...o];return e.forEach(a=>{let c=s(a);c!=null&&n.has(c)||(c!=null&&n.add(c),r.push(a))}),r.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(D({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(T(D({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),J(),F(t=>!!t),V(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),G))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:z(t),isCollection:!1,useCollectionGroup:!1}}).pipe(V(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),G))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(N(i=>i?.organizationId??""),J(),lt(),F(([i])=>!!i),V(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),G))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let n=Number(o[s]);i[s]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(D({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(D({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return E(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let a=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(a);c?c.push(r):s.set(a,[r])}let n=[];for(let[r,a]of s){let c=a.reduce((g,f,d)=>{let h=f?.notificationId??f?.id??`__cross_org_${d}`;return g[h]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),n.push(...Object.values(l??{}))}return n}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return E(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return E(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return E(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return E(this,null,function*(){let i=this.authService.getUser(),e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:D({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,n=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),a=r?o.organizationIds.filter(d=>!!d).map(d=>ft(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>ft(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(a);d=d.filter($=>p.has($))}d=Array.from(new Set(d)),f.organizationIds=d;let h={};d.forEach(p=>{h[p]=this.crossOrgSeenTimestamps[p]??this.getStartAtTimestamp()}),f.orgTimestamps=h}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,n=o?i.filter(r=>{let a=r?.id??r?.notificationId,c=a!=null&&e.has(a);return c&&(s=!0),!c}):i.map(r=>{let a=r?.id??r?.notificationId;return a!=null&&e.has(a)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=gt(t)),i&&typeof i=="object"){let s=Rt(i);e=gt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(F(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(s.featureAllowed=n,s))):C(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(s).pipe(I(n=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,n.documentPaths=r,n)))),I(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(F(i=>!!i),N(i=>T(D({},t),{config:i})),I(i=>this.authService.getUser$().pipe(N(e=>T(D({},i),{user:e})))),I(i=>Et(i.config,i.user,yt.NOTIFICATION)?C(T(D({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(T(D({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(F(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(V(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),C(null))),N(s=>{let n=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(r);let a=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=z(t?.email));let o;t?.userId&&(o=z(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let a=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(a=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:a,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,a)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],s.set(a,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let n=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=z(n?.email));let c=null;n?.userId&&(c=z(n?.userId));let l=!1,g=!0;(a&&r.notifyUsers?.[a]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=T(D(D({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||s?.notificationSourceData&&(d=s?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(N(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return W([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=Array.isArray(i)?i:[],o=null;return t&&(o=[],t.forEach(s=>{s.notifications.forEach(n=>{o?.push(n)})})),e.length?t?this.mergeCrossOrgForYou(o||[],e):null:t?o.sort((s,n)=>n.timestamp-s.timestamp):null}))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=Ut(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let s=Object.values(t?.annotationData?.subscribedUsers||{}).map(r=>r?.user?.userId).filter(r=>!!r),n=Tt(t?.annotationData,s);n.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...n])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&s.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!s.has(n.id)&&s.set(n.id,n)}),Array.from(s.values()).sort((n,r)=>(r.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),St()):C(null)),J(Mt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,n=e.replace(s,(r,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:r);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return E(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let d=l[f];if(!d.some(p=>p.notificationId===g.id))i=i.filter(p=>p.notificationId!==g.id);else{let p=i.find(M=>M.notificationId===g.id),$=d.find(M=>M.notificationId===g.id);p&&$?.views&&(p.views=$.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let r=n.metadata?.documentId;if(r&&o?.[r]){let a=o?.[r]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[r].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!Z(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return E(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(N(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),C({forYou:null,all:null})}}setNotificationAsRead(e){return E(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=z(o?.userId),{metadata:n}=t;if(n){let{apiKey:r,organizationId:a,documentId:c}=n;if(r&&a&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return E(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return E(this,null,function*(){try{let i=this.authService.getUser(),e=z(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),n=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};A.\u0275fac=function(i){return new(i||A)(m(Nt),m(xt),m(ot),m(jt),m(qt),m(Jt),m(nt),m(st),m(at),m(Wt),m(kt),m(Lt),m(Qt),m(et),m(Xt),m(rt),m(It),m(Zt),m(Vt),m(it),m(Kt))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();export{Xt as a,ji as b};
@@ -1,4 +1,4 @@
1
- import{b as Y}from"./chunk-7LUSUNI3.js";import{$ as j,Ai as N,C as A,Cf as D,E as g,Fi as K,Jd as w,L as S,Ld as y,M as B,Md as U,Nd as O,Ni as _,Oi as x,Pi as Q,S as F,T as H,W as E,ca as b,g as $,ki as W,l as C,li as L,p as k,qh as P,r as u,si as R,ti as M,v as m,w as z}from"./chunk-CRZGZZVQ.js";var he=(()=>{let p=class p{constructor(e,t,r,a,s,c,n,i,d,o){this.authService=e,this.commonDbService=t,this.databaseService=r,this.docService=a,this.domService=s,this.loggingService=c,this.metadataService=n,this.commonDbUtils=i,this.configService=d,this.realtimeAdapter=o,this.HEARTBEAT_DURATION=5*1e3,this.heartbeatEnabled$=new C(!1),this.subscriptions=[],this.heartbeatCreatedTimestamps=new Map,this.initializedHeartbeatIds=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: HeartbeatService","color: blue;"),this.heartbeatEnabled$.pipe(S()).subscribe(h=>{h?this.setupHeartbeat():this.teardownHeartbeat()}),this.docService.addPreDocumentIdChangeFunction("heartbeat-service",h=>h?.documentId?this.removeDocumentHeartbeat(h):Promise.resolve())}catch(h){this.loggingService.catch("Error in HeartbeatService constructor: ",h)}}setupWebWorker(e){try{let t=`
1
+ import{b as Y}from"./chunk-C45R3XT6.js";import{$ as j,Ai as N,C as A,Cf as D,E as g,Fi as K,Jd as w,L as S,Ld as y,M as B,Md as U,Nd as O,Ni as _,Oi as x,Pi as Q,S as F,T as H,W as E,ca as b,g as $,ki as W,l as C,li as L,p as k,qh as P,r as u,si as R,ti as M,v as m,w as z}from"./chunk-YTAAOIBL.js";var he=(()=>{let p=class p{constructor(e,t,r,a,s,c,n,i,d,o){this.authService=e,this.commonDbService=t,this.databaseService=r,this.docService=a,this.domService=s,this.loggingService=c,this.metadataService=n,this.commonDbUtils=i,this.configService=d,this.realtimeAdapter=o,this.HEARTBEAT_DURATION=5*1e3,this.heartbeatEnabled$=new C(!1),this.subscriptions=[],this.heartbeatCreatedTimestamps=new Map,this.initializedHeartbeatIds=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: HeartbeatService","color: blue;"),this.heartbeatEnabled$.pipe(S()).subscribe(h=>{h?this.setupHeartbeat():this.teardownHeartbeat()}),this.docService.addPreDocumentIdChangeFunction("heartbeat-service",h=>h?.documentId?this.removeDocumentHeartbeat(h):Promise.resolve())}catch(h){this.loggingService.catch("Error in HeartbeatService constructor: ",h)}}setupWebWorker(e){try{let t=`
2
2
  let intervalId;
3
3
  self.addEventListener('message', (event) => {
4
4
  if (event.data === 'start') {
@@ -1 +1 @@
1
- import{Aa as F}from"./chunk-NCVN3JXT.js";import{$ as A,Ai as U,Cf as g,Ch as D,E as h,Ee as $,Fi as C,G as d,J as v,L as l,Pi as w,T as n,Xe as M,ca as s,ji as E,ki as R,l as p,li as y,qh as I,r as u,te as a,ti as k,ue as m,v as c}from"./chunk-CRZGZZVQ.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.getUser(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(k),s(F),s(U),s(C),s(y),s(R),s(w))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
1
+ import{Ea as F}from"./chunk-2VSCJ7FP.js";import{$ as A,Ai as U,Cf as g,Ch as D,E as h,Ee as $,Fi as C,G as d,J as v,L as l,Pi as w,T as n,Xe as M,ca as s,ji as E,ki as R,l as p,li as y,qh as I,r as u,te as a,ti as k,ue as m,v as c}from"./chunk-YTAAOIBL.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.getUser(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(k),s(F),s(U),s(C),s(y),s(R),s(w))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
@@ -1 +1 @@
1
- import{a as m}from"./chunk-5YU74OX2.js";import{Pa as c,Xa as f}from"./chunk-CRZGZZVQ.js";var l=(()=>{let t=class t{constructor(r){this.translateService=r}transform(r,...i){try{let n=(new Date().getTime()-new Date(r).getTime())/1e3;if(n<1)return this.translateService.translate("now");let s={y:31536e3,mo:2592e3,w:604800,d:86400,h:3600,m:60,s:1};for(let a in s){let o=Math.floor(n/s[a]);if(o>0)return`${o}${this.translateService.translate(a)}`}return r}catch{return r}}};t.\u0275fac=function(i){return new(i||t)(c(m,16))},t.\u0275pipe=f({name:"timeAgo",type:t,pure:!0});let e=t;return e})();export{l as a};
1
+ import{a as m}from"./chunk-67WASIND.js";import{Pa as c,Xa as f}from"./chunk-YTAAOIBL.js";var l=(()=>{let t=class t{constructor(r){this.translateService=r}transform(r,...i){try{let n=(new Date().getTime()-new Date(r).getTime())/1e3;if(n<1)return this.translateService.translate("now");let s={y:31536e3,mo:2592e3,w:604800,d:86400,h:3600,m:60,s:1};for(let a in s){let o=Math.floor(n/s[a]);if(o>0)return`${o}${this.translateService.translate(a)}`}return r}catch{return r}}};t.\u0275fac=function(i){return new(i||t)(c(m,16))},t.\u0275pipe=f({name:"timeAgo",type:t,pure:!0});let e=t;return e})();export{l as a};
@@ -1,4 +1,4 @@
1
- import{$c as ne,Ad as qe,Fd as $e,Ha as ke,_c as ye,ad as Ee,ba as Re,bd as Ue,cd as Ae,dd as Oe,ea as Te,ed as C,fd as Se,g as K,gd as Ie,hd as Pe,id as Ne,jd as Ce,kd as xe,la as we,ld as H,qd as ve,rd as De,sd as Le,ta as $,td as Be,ud as x,vd as Me,wd as Fe}from"./chunk-CRZGZZVQ.js";var Ke="firebasestorage.googleapis.com",Ze="storageBucket",Tt=120*1e3,wt=600*1e3,kt=1e3;var d=class t extends Oe{constructor(e,n,s=0){super(se(e),`Firebase Storage: ${n} (${se(e)})`),this.status_=s,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,t.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return se(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
1
+ import{$c as ne,Ad as qe,Fd as $e,Ha as ke,_c as ye,ad as Ee,ba as Re,bd as Ue,cd as Ae,dd as Oe,ea as Te,ed as C,fd as Se,g as K,gd as Ie,hd as Pe,id as Ne,jd as Ce,kd as xe,la as we,ld as H,qd as ve,rd as De,sd as Le,ta as $,td as Be,ud as x,vd as Me,wd as Fe}from"./chunk-YTAAOIBL.js";var Ke="firebasestorage.googleapis.com",Ze="storageBucket",Tt=120*1e3,wt=600*1e3,kt=1e3;var d=class t extends Oe{constructor(e,n,s=0){super(se(e),`Firebase Storage: ${n} (${se(e)})`),this.status_=s,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,t.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return se(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
2
2
  ${this.customData.serverResponse}`:this.message=this._baseMessage}},h=(function(t){return t.UNKNOWN="unknown",t.OBJECT_NOT_FOUND="object-not-found",t.BUCKET_NOT_FOUND="bucket-not-found",t.PROJECT_NOT_FOUND="project-not-found",t.QUOTA_EXCEEDED="quota-exceeded",t.UNAUTHENTICATED="unauthenticated",t.UNAUTHORIZED="unauthorized",t.UNAUTHORIZED_APP="unauthorized-app",t.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",t.INVALID_CHECKSUM="invalid-checksum",t.CANCELED="canceled",t.INVALID_EVENT_NAME="invalid-event-name",t.INVALID_URL="invalid-url",t.INVALID_DEFAULT_BUCKET="invalid-default-bucket",t.NO_DEFAULT_BUCKET="no-default-bucket",t.CANNOT_SLICE_BLOB="cannot-slice-blob",t.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",t.NO_DOWNLOAD_URL="no-download-url",t.INVALID_ARGUMENT="invalid-argument",t.INVALID_ARGUMENT_COUNT="invalid-argument-count",t.APP_DELETED="app-deleted",t.INVALID_ROOT_OPERATION="invalid-root-operation",t.INVALID_FORMAT="invalid-format",t.INTERNAL_ERROR="internal-error",t.UNSUPPORTED_ENVIRONMENT="unsupported-environment",t})(h||{});function se(t){return"storage/"+t}function de(){let t="An unknown error occurred, please check the error payload for server response.";return new d(h.UNKNOWN,t)}function yt(t){return new d(h.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function Et(t){return new d(h.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function Ut(){let t="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new d(h.UNAUTHENTICATED,t)}function At(){return new d(h.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function Ot(t){return new d(h.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function Ye(){return new d(h.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Je(){return new d(h.CANCELED,"User canceled the upload/download.")}function St(t){return new d(h.INVALID_URL,"Invalid URL '"+t+"'.")}function It(t){return new d(h.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function Pt(){return new d(h.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Ze+"' property when initializing the app?")}function Qe(){return new d(h.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function Nt(){return new d(h.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function Ct(){return new d(h.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function xt(t){return new d(h.UNSUPPORTED_ENVIRONMENT,`${t} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function oe(t){return new d(h.INVALID_ARGUMENT,t)}function et(){return new d(h.APP_DELETED,"The Firebase app was deleted.")}function vt(t){return new d(h.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function z(t,e){return new d(h.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function j(t){throw new d(h.INTERNAL_ERROR,"Internal error: "+t)}var y=class t{constructor(e,n){this.bucket=e,this.path_=n}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){let e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,n){let s;try{s=t.makeFromUrl(e,n)}catch{return new t(e,"")}if(s.path==="")return s;throw It(e)}static makeFromUrl(e,n){let s=null,r="([A-Za-z0-9.\\-_]+)";function o(b){b.path.charAt(b.path.length-1)==="/"&&(b.path_=b.path_.slice(0,-1))}let i="(/(.*))?$",u=new RegExp("^gs://"+r+i,"i"),a={bucket:1,path:3};function c(b){b.path_=decodeURIComponent(b.path)}let l="v[A-Za-z0-9_]+",f=n.replace(/[.]/g,"\\."),p="(/([^?#]*).*)?$",m=new RegExp(`^https?://${f}/${l}/b/${r}/o${p}`,"i"),g={bucket:1,path:3},w=n===Ke?"(?:storage.googleapis.com|storage.cloud.google.com)":n,_="([^?#]*)",U=new RegExp(`^https?://${w}/${r}/${_}`,"i"),T=[{regex:u,indices:a,postModify:o},{regex:m,indices:g,postModify:c},{regex:U,indices:{bucket:1,path:2},postModify:c}];for(let b=0;b<T.length;b++){let P=T[b],N=P.regex.exec(e);if(N){let ee=N[P.indices.bucket],q=N[P.indices.path];q||(q=""),s=new t(ee,q),P.postModify(s);break}}if(s==null)throw St(e);return s}},ie=class{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}};function Dt(t,e,n){let s=1,r=null,o=null,i=!1,u=0;function a(){return u===2}let c=!1;function l(..._){c||(c=!0,e.apply(null,_))}function f(_){r=setTimeout(()=>{r=null,t(m,a())},_)}function p(){o&&clearTimeout(o)}function m(_,...U){if(c){p();return}if(_){p(),l.call(null,_,...U);return}if(a()||i){p(),l.call(null,_,...U);return}s<64&&(s*=2);let T;u===1?(u=2,T=0):T=(s+Math.random())*1e3,f(T)}let g=!1;function w(_){g||(g=!0,p(),!c&&(r!==null?(_||(u=2),clearTimeout(r),f(0)):_||(u=1)))}return f(0),o=setTimeout(()=>{i=!0,w(!0)},n),w}function Lt(t){t(!1)}function Bt(t){return t!==void 0}function Mt(t){return typeof t=="function"}function Ft(t){return typeof t=="object"&&!Array.isArray(t)}function Q(t){return typeof t=="string"||t instanceof String}function He(t){return fe()&&t instanceof Blob}function fe(){return typeof Blob<"u"}function je(t,e,n,s){if(s<e)throw oe(`Invalid value for '${t}'. Expected ${e} or greater.`);if(s>n)throw oe(`Invalid value for '${t}'. Expected ${n} or less.`)}function F(t,e,n){let s=e;return n==null&&(s=`https://${e}`),`${n}://${s}/v0${t}`}function tt(t){let e=encodeURIComponent,n="?";for(let s in t)if(t.hasOwnProperty(s)){let r=e(s)+"="+e(t[s]);n=n+r+"&"}return n=n.slice(0,-1),n}var L=(function(t){return t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT",t})(L||{});function nt(t,e){let n=t>=500&&t<600,r=[408,429].indexOf(t)!==-1,o=e.indexOf(t)!==-1;return n||r||o}var ae=class{constructor(e,n,s,r,o,i,u,a,c,l,f,p=!0,m=!1){this.url_=e,this.method_=n,this.headers_=s,this.body_=r,this.successCodes_=o,this.additionalRetryCodes_=i,this.callback_=u,this.errorCallback_=a,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=f,this.retry=p,this.isUsingEmulator=m,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((g,w)=>{this.resolve_=g,this.reject_=w,this.start_()})}start_(){let e=(s,r)=>{if(r){s(!1,new D(!1,null,!0));return}let o=this.connectionFactory_();this.pendingConnection_=o;let i=u=>{let a=u.loaded,c=u.lengthComputable?u.total:-1;this.progressCallback_!==null&&this.progressCallback_(a,c)};this.progressCallback_!==null&&o.addUploadProgressListener(i),o.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&o.removeUploadProgressListener(i),this.pendingConnection_=null;let u=o.getErrorCode()===L.NO_ERROR,a=o.getStatus();if(!u||nt(a,this.additionalRetryCodes_)&&this.retry){let l=o.getErrorCode()===L.ABORT;s(!1,new D(!1,null,l));return}let c=this.successCodes_.indexOf(a)!==-1;s(!0,new D(c,o))})},n=(s,r)=>{let o=this.resolve_,i=this.reject_,u=r.connection;if(r.wasSuccessCode)try{let a=this.callback_(u,u.getResponse());Bt(a)?o(a):o()}catch(a){i(a)}else if(u!==null){let a=de();a.serverResponse=u.getErrorText(),this.errorCallback_?i(this.errorCallback_(u,a)):i(a)}else if(r.canceled){let a=this.appDelete_?et():Je();i(a)}else{let a=Ye();i(a)}};this.canceled_?n(!1,new D(!1,null,!0)):this.backoffId_=Dt(e,n,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&Lt(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}},D=class{constructor(e,n,s){this.wasSuccessCode=e,this.connection=n,this.canceled=!!s}};function qt(t,e){e!==null&&e.length>0&&(t.Authorization="Firebase "+e)}function $t(t,e){t["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function Ht(t,e){e&&(t["X-Firebase-GMPID"]=e)}function jt(t,e){e!==null&&(t["X-Firebase-AppCheck"]=e)}function zt(t,e,n,s,r,o,i=!0,u=!1){let a=tt(t.urlParams),c=t.url+a,l=Object.assign({},t.headers);return Ht(l,e),qt(l,n),$t(l,o),jt(l,s),new ae(c,t.method,l,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,r,i,u)}function Gt(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function Wt(...t){let e=Gt();if(e!==void 0){let n=new e;for(let s=0;s<t.length;s++)n.append(t[s]);return n.getBlob()}else{if(fe())return new Blob(t);throw new d(h.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function Vt(t,e,n){return t.webkitSlice?t.webkitSlice(e,n):t.mozSlice?t.mozSlice(e,n):t.slice?t.slice(e,n):null}function Xt(t){if(typeof atob>"u")throw xt("base-64");return atob(t)}var E={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},G=class{constructor(e,n){this.data=e,this.contentType=n||null}};function Kt(t,e){switch(t){case E.RAW:return new G(st(e));case E.BASE64:case E.BASE64URL:return new G(rt(t,e));case E.DATA_URL:return new G(Yt(e),Jt(e))}throw de()}function st(t){let e=[];for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);if(s<=127)e.push(s);else if(s<=2047)e.push(192|s>>6,128|s&63);else if((s&64512)===55296)if(!(n<t.length-1&&(t.charCodeAt(n+1)&64512)===56320))e.push(239,191,189);else{let o=s,i=t.charCodeAt(++n);s=65536|(o&1023)<<10|i&1023,e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else(s&64512)===56320?e.push(239,191,189):e.push(224|s>>12,128|s>>6&63,128|s&63)}return new Uint8Array(e)}function Zt(t){let e;try{e=decodeURIComponent(t)}catch{throw z(E.DATA_URL,"Malformed data URL.")}return st(e)}function rt(t,e){switch(t){case E.BASE64:{let r=e.indexOf("-")!==-1,o=e.indexOf("_")!==-1;if(r||o)throw z(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break}case E.BASE64URL:{let r=e.indexOf("+")!==-1,o=e.indexOf("/")!==-1;if(r||o)throw z(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=Xt(e)}catch(r){throw r.message.includes("polyfill")?r:z(t,"Invalid character found")}let s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}var Y=class{constructor(e){this.base64=!1,this.contentType=null;let n=e.match(/^data:([^,]+)?,/);if(n===null)throw z(E.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");let s=n[1]||null;s!=null&&(this.base64=Qt(s,";base64"),this.contentType=this.base64?s.substring(0,s.length-7):s),this.rest=e.substring(e.indexOf(",")+1)}};function Yt(t){let e=new Y(t);return e.base64?rt(E.BASE64,e.rest):Zt(e.rest)}function Jt(t){return new Y(t).contentType}function Qt(t,e){return t.length>=e.length?t.substring(t.length-e.length)===e:!1}var J=class t{constructor(e,n){let s=0,r="";He(e)?(this.data_=e,s=e.size,r=e.type):e instanceof ArrayBuffer?(n?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),s=this.data_.length):e instanceof Uint8Array&&(n?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),s=e.length),this.size_=s,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,n){if(He(this.data_)){let s=this.data_,r=Vt(s,e,n);return r===null?null:new t(r)}else{let s=new Uint8Array(this.data_.buffer,e,n-e);return new t(s,!0)}}static getBlob(...e){if(fe()){let n=e.map(s=>s instanceof t?s.data_:s);return new t(Wt.apply(null,n))}else{let n=e.map(i=>Q(i)?Kt(E.RAW,i).data:i.data_),s=0;n.forEach(i=>{s+=i.byteLength});let r=new Uint8Array(s),o=0;return n.forEach(i=>{for(let u=0;u<i.length;u++)r[o++]=i[u]}),new t(r,!0)}}uploadData(){return this.data_}};function ot(t){let e;try{e=JSON.parse(t)}catch{return null}return Ft(e)?e:null}function en(t){if(t.length===0)return null;let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function tn(t,e){let n=e.split("/").filter(s=>s.length>0).join("/");return t.length===0?n:t+"/"+n}function it(t){let e=t.lastIndexOf("/",t.length-2);return e===-1?t:t.slice(e+1)}function nn(t,e){return e}var R=class{constructor(e,n,s,r){this.server=e,this.local=n||e,this.writable=!!s,this.xform=r||nn}},Z=null;function sn(t){return!Q(t)||t.length<2?t:it(t)}function at(){if(Z)return Z;let t=[];t.push(new R("bucket")),t.push(new R("generation")),t.push(new R("metageneration")),t.push(new R("name","fullPath",!0));function e(o,i){return sn(i)}let n=new R("name");n.xform=e,t.push(n);function s(o,i){return i!==void 0?Number(i):i}let r=new R("size");return r.xform=s,t.push(r),t.push(new R("timeCreated")),t.push(new R("updated")),t.push(new R("md5Hash",null,!0)),t.push(new R("cacheControl",null,!0)),t.push(new R("contentDisposition",null,!0)),t.push(new R("contentEncoding",null,!0)),t.push(new R("contentLanguage",null,!0)),t.push(new R("contentType",null,!0)),t.push(new R("metadata","customMetadata",!0)),Z=t,Z}function rn(t,e){function n(){let s=t.bucket,r=t.fullPath,o=new y(s,r);return e._makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function on(t,e,n){let s={};s.type="file";let r=n.length;for(let o=0;o<r;o++){let i=n[o];s[i.local]=i.xform(s,e[i.server])}return rn(s,t),s}function ut(t,e,n){let s=ot(e);return s===null?null:on(t,s,n)}function an(t,e,n,s){let r=ot(e);if(r===null||!Q(r.downloadTokens))return null;let o=r.downloadTokens;if(o.length===0)return null;let i=encodeURIComponent;return o.split(",").map(c=>{let l=t.bucket,f=t.fullPath,p="/b/"+i(l)+"/o/"+i(f),m=F(p,n,s),g=tt({alt:"media",token:c});return m+g})[0]}function ct(t,e){let n={},s=e.length;for(let r=0;r<s;r++){let o=e[r];o.writable&&(n[o.server]=t[o.local])}return JSON.stringify(n)}var S=class{constructor(e,n,s,r){this.url=e,this.method=n,this.handler=s,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}};function O(t){if(!t)throw de()}function _e(t,e){function n(s,r){let o=ut(t,r,e);return O(o!==null),o}return n}function un(t,e){function n(s,r){let o=ut(t,r,e);return O(o!==null),an(o,r,t.host,t._protocol)}return n}function V(t){function e(n,s){let r;return n.getStatus()===401?n.getErrorText().includes("Firebase App Check token is invalid")?r=At():r=Ut():n.getStatus()===402?r=Et(t.bucket):n.getStatus()===403?r=Ot(t.path):r=s,r.status=n.getStatus(),r.serverResponse=s.serverResponse,r}return e}function pe(t){let e=V(t);function n(s,r){let o=e(s,r);return s.getStatus()===404&&(o=yt(t.path)),o.serverResponse=r.serverResponse,o}return n}function cn(t,e,n){let s=e.fullServerUrl(),r=F(s,t.host,t._protocol),o="GET",i=t.maxOperationRetryTime,u=new S(r,o,_e(t,n),i);return u.errorHandler=pe(e),u}function ln(t,e,n){let s=e.fullServerUrl(),r=F(s,t.host,t._protocol),o="GET",i=t.maxOperationRetryTime,u=new S(r,o,un(t,n),i);return u.errorHandler=pe(e),u}function hn(t,e){let n=e.fullServerUrl(),s=F(n,t.host,t._protocol),r="DELETE",o=t.maxOperationRetryTime;function i(a,c){}let u=new S(s,r,i,o);return u.successCodes=[200,204],u.errorHandler=pe(e),u}function dn(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}function lt(t,e,n){let s=Object.assign({},n);return s.fullPath=t.path,s.size=e.size(),s.contentType||(s.contentType=dn(null,e)),s}function fn(t,e,n,s,r){let o=e.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};function u(){let T="";for(let b=0;b<2;b++)T=T+Math.random().toString().slice(2);return T}let a=u();i["Content-Type"]="multipart/related; boundary="+a;let c=lt(e,s,r),l=ct(c,n),f="--"+a+`\r
3
3
  Content-Type: application/json; charset=utf-8\r
4
4
  \r
@@ -1 +1 @@
1
- import{Ga as c,Pa as n,Wa as o,si as h,ua as a,wa as r}from"./chunk-CRZGZZVQ.js";var I=(()=>{let e=class e{constructor(t,i){this.domService=t,this.elementRef=i,this.clickOutside=new c}ngOnInit(){}ngAfterViewInit(){setTimeout(()=>{this.subscription=this.domService.onDocumentClickSubject$().subscribe(t=>{let i=this.checkInsideClick(t,this.elementRef.nativeElement);!i&&this.clickOutsideHandler&&typeof this.clickOutsideHandler=="function"&&(i=this.clickOutsideHandler(t.target,this.elementRef.nativeElement)),i||this.clickOutside.emit()})},500)}ngOnDestroy(){this.subscription?.unsubscribe()}checkInsideClick(t,i){return t.composedPath().includes(i)}};e.\u0275fac=function(i){return new(i||e)(n(h),n(r))},e.\u0275dir=o({type:e,selectors:[["","snippylyClickOutside",""]],inputs:{clickOutsideHandler:"clickOutsideHandler"},outputs:{clickOutside:"clickOutside"}});let s=e;return s})();var b=(()=>{let e=class e{constructor(t){this.elementRef=t,this.lastPosition=null,this.positionChange=new c,this.disabled=!1,this.timeSpentInMs=0,this.MAX_TIME_SPENT_IN_MS=6e4}ngAfterViewInit(){try{this.toggleTrackingPosition()}catch{}}toggleTrackingPosition(){try{this.disabled?this.stopTracking():this.startTrackingPosition()}catch{}}startTrackingPosition(){try{if(this.intervalId)return;this.intervalId=setInterval(()=>{if(this.timeSpentInMs+=10,this.timeSpentInMs>this.MAX_TIME_SPENT_IN_MS){this.stopTracking();return}let t=this.elementRef.nativeElement.getBoundingClientRect();(!this.lastPosition||!this.arePositionsEqual(this.lastPosition,t))&&(this.lastPosition=t,this.positionChange.emit(t))},10)}catch{}}stopTracking(){try{this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.timeSpentInMs=0)}catch{}}arePositionsEqual(t,i){try{return t.top===i.top&&t.left===i.left&&t.bottom===i.bottom&&t.right===i.right&&t.width===i.width&&t.height===i.height}catch{return!0}}ngOnChanges(){try{this.toggleTrackingPosition()}catch{}}ngOnDestroy(){try{this.stopTracking()}catch{}}};e.\u0275fac=function(i){return new(i||e)(n(r))},e.\u0275dir=o({type:e,selectors:[["","veltPositionObserver",""]],inputs:{disabled:[0,"veltPositionObserverDisabled","disabled"]},outputs:{positionChange:"positionChange"},features:[a]});let s=e;return s})();export{I as a,b};
1
+ import{Ga as c,Pa as n,Wa as o,si as h,ua as a,wa as r}from"./chunk-YTAAOIBL.js";var I=(()=>{let e=class e{constructor(t,i){this.domService=t,this.elementRef=i,this.clickOutside=new c}ngOnInit(){}ngAfterViewInit(){setTimeout(()=>{this.subscription=this.domService.onDocumentClickSubject$().subscribe(t=>{let i=this.checkInsideClick(t,this.elementRef.nativeElement);!i&&this.clickOutsideHandler&&typeof this.clickOutsideHandler=="function"&&(i=this.clickOutsideHandler(t.target,this.elementRef.nativeElement)),i||this.clickOutside.emit()})},500)}ngOnDestroy(){this.subscription?.unsubscribe()}checkInsideClick(t,i){return t.composedPath().includes(i)}};e.\u0275fac=function(i){return new(i||e)(n(h),n(r))},e.\u0275dir=o({type:e,selectors:[["","snippylyClickOutside",""]],inputs:{clickOutsideHandler:"clickOutsideHandler"},outputs:{clickOutside:"clickOutside"}});let s=e;return s})();var b=(()=>{let e=class e{constructor(t){this.elementRef=t,this.lastPosition=null,this.positionChange=new c,this.disabled=!1,this.timeSpentInMs=0,this.MAX_TIME_SPENT_IN_MS=6e4}ngAfterViewInit(){try{this.toggleTrackingPosition()}catch{}}toggleTrackingPosition(){try{this.disabled?this.stopTracking():this.startTrackingPosition()}catch{}}startTrackingPosition(){try{if(this.intervalId)return;this.intervalId=setInterval(()=>{if(this.timeSpentInMs+=10,this.timeSpentInMs>this.MAX_TIME_SPENT_IN_MS){this.stopTracking();return}let t=this.elementRef.nativeElement.getBoundingClientRect();(!this.lastPosition||!this.arePositionsEqual(this.lastPosition,t))&&(this.lastPosition=t,this.positionChange.emit(t))},10)}catch{}}stopTracking(){try{this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.timeSpentInMs=0)}catch{}}arePositionsEqual(t,i){try{return t.top===i.top&&t.left===i.left&&t.bottom===i.bottom&&t.right===i.right&&t.width===i.width&&t.height===i.height}catch{return!0}}ngOnChanges(){try{this.toggleTrackingPosition()}catch{}}ngOnDestroy(){try{this.stopTracking()}catch{}}};e.\u0275fac=function(i){return new(i||e)(n(r))},e.\u0275dir=o({type:e,selectors:[["","veltPositionObserver",""]],inputs:{disabled:[0,"veltPositionObserverDisabled","disabled"]},outputs:{positionChange:"positionChange"},features:[a]});let s=e;return s})();export{I as a,b};