@veltdev/sdk
Version:
Velt is an SDK to add collaborative features to your product within minutes. Example: Comments like Figma, Frame.io, Google docs or sheets, Recording like Loom, Huddles like Slack and much more.
1 lines • 68 kB
JavaScript
import{a as qt}from"./chunk-ZATQYC4Y.js";import{a as Kt}from"./chunk-KEM6PWSD.js";import{$ as K,$e as q,Ah as Mt,Ai as nt,Bf as gt,Cf as z,Df as At,Di as mt,E as F,Ed as Nt,Ee as P,Ef as ft,Fi as at,G as V,Gi as Wt,Hi as kt,Ii as Jt,J as k,L as J,Lh as Ft,M as lt,Nf as Ut,Nh as Pt,O as St,Od as It,Of as Tt,Rf as Et,T as I,W as vt,Wf as $t,Xf as dt,a as D,af as Q,ag as Z,b as T,be as Ot,bi as it,ca as m,ci as zt,da as pt,di as et,ei as Bt,g as E,hi as xt,jh as Rt,ji as Ht,l as O,li as jt,mi as ot,ni as Vt,oe as yt,oi as Lt,p as G,q as ct,qh as ht,qi as _t,r as C,sh as X,si as ut,ti as Yt,uf as bt,ui as st,v as N,vh as L,w as W,wh as tt,yf as Dt,yh as wt,yi as Gt,zf as Ct,zi as rt}from"./chunk-GR3NESUB.js";var Qt=(()=>{let A=class A{constructor(t,i,e,o,s,a,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=a,this.serviceBook=r,this.serviceBook.set(Mt,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 a of s)i.add(a)}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(Ft)?.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 $t(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 H=A;return H})();var Bi=(()=>{let A=class A{constructor(t,i,e,o,s,a,r,n,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=a,this.commentUtilsService=r,this.commentAnnotationsResolverService=n,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(xt),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(wt,this),this.serviceBook.observe(Pt).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 n=r?.values?.find(c=>c.id===r.default);s[r.id]=n||r?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(s).forEach(r=>{a[r]=s[r].id}),yield this.updateSettingsConfigToDb(a)}}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(n=>n.documentId),o=i?.map(n=>n.documentId),s=e?.filter(n=>!o?.includes(n)),a=o?.map(n=>({documentId:n,timestamp:i?.find(c=>c.documentId===n)?.timestamp})).filter(n=>!e?.includes(n.documentId)),r=o?.map(n=>{let c=i?.find(l=>l.documentId===n)?.timestamp;return{documentId:n,timestamp:c}}).filter(n=>{let c=t?.find(l=>l.documentId===n.documentId)?.timestamp;return c&&n.timestamp&&c!==n.timestamp});a?.length&&this.fetchNotificationsForDocumentIds(a),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(n=>{this.removeNotificationsForDocumentId(n)}),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(),a=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&a&&(o=new mt({apiKey:s,organizationId:a})),{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 a=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;a.setDate(a.getDate()-r);let n=a.getTime(),c=[Vt(ut("timestamp",">=",n),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(_t("timestamp","desc")),c.push(Lt(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 a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}else{let a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}s.forEach(a=>{a.notification=this.getClientNotificationObject(a)}),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),{}),a;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}a.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],n=new Map(r.map(c=>[c.notificationId,c]));a.forEach(c=>{n.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(n.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(),a={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(a[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(j=>{j?.documentId&&(y[j.documentId]=j)}),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:{id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=Tt();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),n={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:n}),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,j)=>{let Y=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(Y){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],Y))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:Y}))}let _=h[y].notifications||[];_.forEach(B=>{$.includes(B.notificationId)&&!p.find(Zt=>Zt.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:_,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:_,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,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 j=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",j)})}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(a=>a.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??"",a=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),a||(a=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),n=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=a||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(n.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((n,c)=>(n[c.notificationId]=c,n),{});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,n)=>n.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=n=>n?.id??n?.notificationId,a=new Set;o.forEach(n=>{let c=s(n);c!=null&&a.add(c)});let r=[...o];return e.forEach(n=>{let c=s(n);c!=null&&a.has(c)||(c!=null&&a.add(c),r.push(n))}),r.sort((n,c)=>(c?.timestamp||0)-(n?.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 a=Number(o[s]);i[s]=Number.isFinite(a)?a: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 n=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(n);c?c.push(r):s.set(n,[r])}let a=[];for(let[r,n]of s){let c=n.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??{}})),a.push(...Object.values(l??{}))}return a}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||{},a=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!a.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:a}),n=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(n?.pendingPermissionQueries)?n.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(n,{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:a,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),a=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(a);if(i.fetchGeneration!==this.crossOrgGeneration)return;let n=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=n:c=this.mergeCrossOrgForYou(n,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,a=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),n=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(n,l));else{let d=a.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(n);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,a=o?i.filter(r=>{let n=r?.id??r?.notificationId,c=n!=null&&e.has(n);return c&&(s=!0),!c}):i.map(r=>{let n=r?.id??r?.notificationId;return n!=null&&e.has(n)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(a)}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=Et(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(a=>(s.featureAllowed=a,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(a=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,a.documentPaths=r,a)))),I(a=>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=>Ut(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 a=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&a.push(l)}),a.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(a),this.rawNotificationsByIdMap$.next(r);let n=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&n.push(l)}),this.processedNotifications$.next(n),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 n=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(n=!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:n,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,n)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[n]?.views?.[t?.userSnippylyId],s.set(n,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 a=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&a){let n=null;a?.email&&(n=z(a?.email));let c=null;a?.userId&&(c=z(a?.userId));let l=!1,g=!0;(n&&r.notifyUsers?.[n]||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