@veltdev/sdk-dev 6.0.34-beta.2 → 6.0.35

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-events.data.model.d.ts +5 -0
  2. package/app/models/data/comment-resolver.data.model.d.ts +1 -1
  3. package/app/models/data/comment-sidebar-config.model.d.ts +12 -0
  4. package/app/models/data/suggestion-events.data.model.d.ts +15 -0
  5. package/app/models/data/suggestion.data.model.d.ts +75 -0
  6. package/app/models/element/comment-element.model.d.ts +4 -2
  7. package/app/models/element/suggestion-element.model.d.ts +25 -0
  8. package/{chunk-XHGU5ZIA.js → chunk-3AXVWFWQ.js} +1 -1
  9. package/{chunk-BYI3X5XU.js → chunk-4GZINSJB.js} +1 -1
  10. package/{chunk-4JDKBL6T.js → chunk-5K23BJBD.js} +1 -1
  11. package/{chunk-HBFQOXCU.js → chunk-5OVPOQXM.js} +1 -1
  12. package/{chunk-ENEBYFM2.js → chunk-6456EREF.js} +1 -1
  13. package/{chunk-GXUATG32.js → chunk-74M4LLJN.js} +1 -1
  14. package/{chunk-XRSE2VTK.js → chunk-7CAYUDV6.js} +25 -25
  15. package/{chunk-67IFTVAR.js → chunk-B4ARTZCP.js} +1 -1
  16. package/{chunk-RA5LKFCC.js → chunk-C3KNUFAS.js} +1 -1
  17. package/{chunk-CABROX7X.js → chunk-CFURN7DG.js} +1 -1
  18. package/{chunk-CTRB5TVE.js → chunk-E4ZYSIOW.js} +1 -1
  19. package/{chunk-UGGDJCBS.js → chunk-ENKKDM6C.js} +1 -1
  20. package/{chunk-YCJV74EN.js → chunk-FPLYS2CV.js} +1 -1
  21. package/{chunk-FDBP2MR3.js → chunk-GSIBDB7Y.js} +1 -1
  22. package/chunk-H6I5XVHO.js +2 -0
  23. package/{chunk-HGX4FLFA.js → chunk-HJVIKKUT.js} +1 -1
  24. package/{chunk-ULT44YLH.js → chunk-JU4BFBOY.js} +1 -1
  25. package/{chunk-XCZQHLLQ.js → chunk-K7FVY4KN.js} +1 -1
  26. package/{chunk-BEFW7P3U.js → chunk-NHKDUTEY.js} +1 -1
  27. package/{chunk-EP7CZ3EM.js → chunk-NX5SHREB.js} +1 -1
  28. package/{chunk-R2ZBBZD3.js → chunk-OB5UEYMT.js} +1 -1
  29. package/{chunk-NFPV353N.js → chunk-SPPCMWKD.js} +1 -1
  30. package/{chunk-34LFLBX5.js → chunk-UW7EL7NW.js} +1 -1
  31. package/{chunk-E5X4SNAK.js → chunk-VGGU4K4I.js} +1 -1
  32. package/{chunk-B6EXKCBS.js → chunk-VI5OSZIQ.js} +1 -1
  33. package/{chunk-VS5M5ZP4.js → chunk-W3PIDHPP.js} +1 -1
  34. package/{chunk-5NN3THOV.js → chunk-W7JRUP3U.js} +1 -1
  35. package/{chunk-IBZ4MVH2.js → chunk-WAIRKNL2.js} +1 -1
  36. package/{chunk-EXDARMGC.js → chunk-WFVUCWNJ.js} +1 -1
  37. package/{chunk-4CIMEMHA.js → chunk-XFGIV7R7.js} +1 -1
  38. package/{chunk-KK5MKT6K.js → chunk-XM5YSR4I.js} +1 -1
  39. package/{chunk-TRW3DRCQ.js → chunk-XQXBBGCT.js} +1 -1
  40. package/{chunk-76PJTJAE.js → chunk-YBUWC65O.js} +1 -1
  41. package/{chunk-UFYGLYSF.js → chunk-YFONDDLR.js} +1 -1
  42. package/{chunk-NGQMBPNS.js → chunk-YGZDTBCO.js} +1 -1
  43. package/{chunk-QRWZNVD6.js → chunk-ZJPFBKE2.js} +1 -1
  44. package/package.json +1 -1
  45. package/velt-activity-log.js +1 -1
  46. package/velt-area.js +1 -1
  47. package/velt-arrow.js +1 -1
  48. package/velt-comment.js +32 -7
  49. package/velt-crdt.js +1 -1
  50. package/velt-cursor.js +1 -1
  51. package/velt-huddle.js +1 -1
  52. package/velt-live-state-sync.js +1 -1
  53. package/velt-notification.js +1 -1
  54. package/velt-portable.js +1 -1
  55. package/velt-presence.js +1 -1
  56. package/velt-reaction.js +1 -1
  57. package/velt-recorder.js +1 -1
  58. package/velt-rewriter.js +1 -1
  59. package/velt-selection.js +1 -1
  60. package/velt-tag.js +1 -1
  61. package/velt-user-invite.js +1 -1
  62. package/velt-user-request.js +1 -1
  63. package/velt-video-player.js +1 -1
  64. package/velt-views.js +1 -1
  65. package/velt.js +4 -4
  66. package/chunk-OE6TZOZO.js +0 -2
@@ -1 +1 @@
1
- import{a as li}from"./chunk-4JDKBL6T.js";import{a as ci}from"./chunk-BYI3X5XU.js";import{A as si,D as ni,E as ai,c as oi,k as ht,o as ri,p as ot,q as rt,s as st,x as mt,z as nt}from"./chunk-VS5M5ZP4.js";import{Ak as et,Bj as Wt,Cj as Jt,Dg as zt,Di as Lt,E as w,Eg as gt,Ej as Kt,G as _,Gd as yt,Gj as dt,He as P,Ii as j,Ji as q,Jj as Qt,K as k,Kg as X,Li as _t,Lj as Xt,M as W,Mj as Zt,Ni as jt,O as at,Pj as ut,Q as Nt,Qd as Dt,Qf as Ut,U as It,Uf as Et,Uj as qt,V as O,Wf as $t,Xf as wt,Y as Ot,Yi as Ht,Zd as Ct,Zf as ct,_f as R,_i as Vt,a as I,ag as Pt,b as T,ba as J,cg as lt,ck as ti,di as Bt,ea as S,ee as At,fa as bt,g as y,i as vt,l as b,mi as ft,oi as Z,oj as tt,p as Y,pj as Yt,q as G,qi as xt,qj as it,r as D,re as Tt,rj as Gt,tf as K,uf as Q,ug as Rt,v as N,vg as Ft,vk as ii,w as V,wj as kt,x as pt,yg as Mt,zk as ei}from"./chunk-XRSE2VTK.js";var gi=(()=>{let m=class m{constructor(t,i,e,o,r,n,s){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=r,this.notificationResolverService=n,this.serviceBook=s,this.serviceBook.set(jt,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 r=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of r)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,r=i?.comments?.[e]?.commentHtml;return o&&r&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=r),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 r=i?.[o]?.[e];return r&&(t.notification.notificationSourceData.location=r?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=r?.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{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),this.usersService.userResolverConfigured?.()&&t&&typeof t=="object")for(let e of Object.keys(t))e!=="annotationData"&&e!=="targetAnnotationData"&&Lt(t[e])&&(t[e]=xt(t[e],Et));switch(t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData),t=this.commentUtilsService.stripCommentNotificationPayload(t);break;default:m.carriesCommentPayload(t)&&(t=this.commentUtilsService.stripCommentNotificationPayload(t));break;case"recorder":this.serviceBook.get(Ht)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),m.carriesCommentPayload(t)?this.commentUtilsService?.stripCommentNotificationPayload?.(I({},t))??t:t}}static carriesCommentPayload(t){return!t||typeof t!="object"?!1:t.notificationSource==="comment"||t.notificationSource===void 0&&Array.isArray(t.annotationData?.comments)}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 y(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 zt(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 r=o?.notification?.id||o?.notificationId;r&&i.add(r)}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 r of o)e[r]!==void 0&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]));return Object.keys(e).forEach(r=>{!o.includes(r)&&r!=="notificationId"&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};m.\u0275fac=function(i){return new(i||m)(S(st),S(it),S(ot),S(et),S(rt),S(nt),S(tt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();function St(v,m=new Date){let F=v>0?v:15,t=new Date(m.getTime());return t.setDate(t.getDate()-F),t.getTime()}function fi(v){let m={startAtTimestamp:v.startAtTimestamp};return v.currentDocumentOnly&&v.currentDocumentId&&(m.documentId=v.currentDocumentId),v.currentDocumentOnly||(m.limit=v.limit),m}function di(v,m){let F=[];if(!v||typeof v!="object")return{};for(let e of Object.keys(v)){let o=v[e];if(!o||typeof o!="object")continue;let r=o.timestamp;typeof r!="number"||Number.isNaN(r)||!(r>=m.startAtTimestamp)||m.documentId!==void 0&&o.metadata?.documentId!==m.documentId||F.push({id:e,timestamp:r,row:v[e]})}let t=F;m.limit!==void 0&&(t=[...F].sort((e,o)=>o.timestamp-e.timestamp||(e.id<o.id?1:e.id>o.id?-1:0)).slice(0,Math.max(0,m.limit)));let i={};for(let e of t)i[e.id]=e.row;return i}function ui(v){if(typeof v!="number"||!Number.isFinite(v))return 25;let t=Math.floor(v);return t<1?25:Math.min(200,t)}function hi(v,m){let F=t=>!!t&&typeof t=="object"&&Object.keys(t).length>0;return F(v)?v:F(m)?m:{}}var ge=(()=>{let m=class m{constructor(t,i,e,o,r,n,s,a,c,l,g,f,d,p,h,A,U,z,B,x,M,H){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=r,this.commonDbUtilsService=n,this.commentUtilsService=s,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=p,this.notificationUtilsService=h,this.usersService=A,this.functions=U,this.userPermissionService=z,this.coreActionsService=B,this.serviceBook=x,this.realtimeAdapter=M,this.adapterSelectorService=H,this.endpointsService=bt(kt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new b([]),this.rawNotificationsByIdMap$=new b(new Map),this.processedNotifications$=new b([]),this.userNotificationsFromServer$=new b(null),this.readNotificationsOnForYouTab$=new b(!1),this.currentDocumentOnly$=new b(!1),this.notificationViews$=new b({}),this.notificationsByIdMap$=new b(new Map),this.historyPanelVisible$=new b(!1),this.notificationsForYou$=new b(null),this.notificationsByDocumentIdMap$=new b(null),this.notificationsByDocumentIdSubscription={},this.notificationsHubDisabled=!1,this.reportedDroppedHubPushes=new Set,this.allowedDocumentMetadataMap$=new b(null),this.documentIdsPipelineOnPortableTrigger=!1,this.maxNotificationDays$=new b(15),this.tabConfig$=new b({people:{enable:!1}}),this.settingsConfig$=new b(null),this.setSettingsConfigByOrganization$=new b(!1),this.muteAllNotifications$=new b(!1),this.enableSettings$=new b(!1),this.selfNotifications$=new b(!1),this.userScopedNotifications$=new b({enabled:!1,limit:25}),this.settingsInitialConfig$=new b([{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.notificationListGeneration=0,this.notificationsPanelVisible$=new b(!1),this.crossOrganizationConfig$=new b({enabled:!1}),this.crossOrgNotifications$=new b([]),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(_t,this),this.serviceBook.observe(Vt).subscribe(u=>{this.commentService=u??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(w(u=>!!u),k(1)).subscribe(u=>{if(u){this.db=u;try{let C=this.configService.getProxyConfig(),E=this.endpointsService.getNotificationsDbUrl();$t(E)?(this.notificationsDb=null,this.notificationsHubDisabled=!0):(C?.v1DbHost&&E&&(E=wt(E,C.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(E),C?.v1DbHost&&E&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(C){this.loggingService.catch("Error initializing notifications DB, using default: ",C),this.notificationsDb=u}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},u=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",u)}),this.authService.getUser$().subscribe(u=>{u?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(C=>{this.notificationsByDocumentIdSubscription[C]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),ut(()=>{try{if(this.adapterSelectorService?.isPortableBackendActive()){if(this.documentIdsPipelineOnPortableTrigger)return;this.getDocumentIds()}}catch(u){this.loggingService.catch("Error re-evaluating portable notification list on chunk registration: ",u)}}),this.docService.getLocationMetadata$().subscribe(u=>{if(u){let C=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(u||{}).forEach(E=>{let L=C?.[E]?.notifications;L?.length&&L.forEach($=>{this.notificationUtilsService.mergeLocationWithNotification({notification:$},u)?.notification})}),this.notificationsByDocumentIdMap$.next(C)}})}catch(u){this.loggingService.catch("Error in NotificationService constructor: ",u)}}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 y(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=R(this.authService.getUser()?.userId??""),o,r=!0;if(this.commonDbService?.isPortableSession?.()===!0){let n=yield this.readPortableSettingsConfig(t,e);o=n.data,r=n.answered}else 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 if(!r)this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue()),this.setDBConfigDataToInitialConfig(this.buildDefaultSettingsConfig());else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let n=this.buildDefaultSettingsConfig();yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}buildDefaultSettingsConfig(){let t={};this.settingsInitialConfig$.getValue().forEach(e=>{if(e.enable){let o=e?.values?.find(r=>r.id===e.default);t[e.id]=o||e?.values?.[0]||{id:"NONE",name:"None"}}});let i={};return Object.keys(t).forEach(e=>{i[e]=t[e].id}),i}readPortableSettingsConfig(t,i){return y(this,null,function*(){try{let e=this.resolvePortableSettingsTarget(t,this.getSettingsConfigByOrganization(),this.docService.getOrganizationConfig(),i);return e?yield this.commonDbService.readPortableDoc(e.feature,e.properties):{answered:!1}}catch(e){return this.loggingService.catch("Error in NotificationService readPortableSettingsConfig: ",e),{answered:!1}}})}resolvePortableSettingsTarget(t,i,e,o){if(!this.authService.getUser()?.userId)return null;let r=t?.organizationId??e?.organizationId;return i?this.commonDbService.announcesPortableCapability(ti)?{feature:"organizationUserConfig",properties:{organizationId:r,userId:o}}:null:t?.documentId?{feature:"userConfig",properties:{id:t.documentId,organizationId:r,userId:o}}:null}portableUserSettingsListener$(t,i,e,o){let r=this.resolvePortableSettingsTarget(t,i,e,o);return r?this.commonDbService.dbListener({feature:r.feature,properties:r.properties}):D(void 0)}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=R(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(w(i=>i===!0),O(()=>V([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(w(([i,e,o])=>(e||!!i)&&!!o?.organizationId),O(([i,e,o])=>{let r=N(n=>{n?.data?.notificationsConfig&&!X(n?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(n?.data?.notificationsConfig)});return this.commonDbService?.isPortableSession?.()===!0?this.commonDbService.portableConnectionChanges$().pipe(O(()=>G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.portableUserSettingsListener$(i,e,o,t).pipe(r))))):G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(r)))})))).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=pt(()=>{let t=!!this.adapterSelectorService?.isPortableBackendActive();return this.documentIdsPipelineOnPortableTrigger=t,this.notificationListPipeline$(t)}).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}notificationListPipeline$(t=!1){return this.selfNotifications$.pipe(O(()=>this.getCurrentDocumentOnly$().pipe(O(i=>i?this.docService.getDocumentPaths$().pipe(N(e=>{})):D(void 0)))),Ot(()=>{this.notificationListGeneration++,this.notificationsByDocumentIdMap$.next(null)}),O(()=>this.getDocumentIdsByLastNotificationTimestamp(void 0,t).pipe(at(),N(([i,e])=>{let o=i?.map(c=>c.documentId),r=e?.map(c=>c.documentId),n=o?.filter(c=>!r?.includes(c)),s=r?.map(c=>({documentId:c,timestamp:e?.find(l=>l.documentId===c)?.timestamp})).filter(c=>!o?.includes(c.documentId)),a=r?.map(c=>{let l=e?.find(g=>g.documentId===c)?.timestamp;return{documentId:c,timestamp:l}}).filter(c=>{let l=i?.find(g=>g.documentId===c.documentId)?.timestamp;return l&&c.timestamp&&l!==c.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),a?.length&&this.fetchNotificationsForDocumentIds(a,1),n?.forEach(c=>{this.removeNotificationsForDocumentId(c)}),e&&!e?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))}))))}portableNotificationTriggerRows$(t,i){return new vt(e=>{let o=!1,r=null,n=()=>{try{r?.unsubscribe()}catch(c){this.loggingService.catch("Error releasing the notification trigger subscription: ",c)}r=null},s=()=>{o||(n(),r=this.openPortableNotificationTrigger(t,c=>e.next(c),i))},a=ut(s);return s(),()=>{o=!0;try{a()}catch(c){this.loggingService.catch("Error disposing the notification trigger registration listener: ",c)}n()}})}openPortableNotificationTrigger(t,i,e){try{let o=ri(ht,{apiKey:this.configService.getApiKey(),organizationId:t}),r=this.adapterSelectorService?.resolveRealtimeAdapter?.();if(!o||!r)return null;let n=Xt(o.feature)?.mode??"persistent",s={},a={},c=!1,l=!1;return r.subscribe(o,n,g=>{try{if(l)return;if(typeof g.seq=="number"){let f=a[g.id];if(f!==void 0&&g.seq<=f)return;a[g.id]=g.seq}g.type==="removed"?delete s[g.id]:s[g.id]=g.data,c&&typeof g.seq=="number"&&i(I({},s))}catch(f){this.loggingService.catch("Error materializing a notification trigger delta: ",f)}},I({onSnapshotComplete:g=>{try{if(l)return;if(g?.full===!0)for(let f of Object.keys(a))delete a[f];c=!0,i(I({},s))}catch(f){this.loggingService.catch("Error completing the notification trigger snapshot: ",f)}},onError:g=>{l=!0,this.loggingService.catch(`Portable channel denied for ${ht}: `,{ok:!1,code:g})}},e?{documentId:e}:{}))}catch(o){return this.loggingService.catch("Error subscribing the notification trigger channel: ",o),null}}getDocumentIdsByLastNotificationTimestamp(t=15,i=!1){try{return this.authService.getUser$().pipe(O(e=>this.docService.getOrganizationConfig$().pipe(N(o=>{let r=null,n=this.configService.getApiKey(),s=o?.organizationId||e?.organizationId,a=o?.clientOrganizationId||e?.clientOrganizationId||"";return n&&s&&(r=new mt({apiKey:n,organizationId:s})),{user:e,documentPaths:r,clientOrganizationId:a}}))),O(e=>{let{user:o,documentPaths:r,clientOrganizationId:n}=e;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return D(null);if(o&&r?.organizationNotificationsLastNotificationTimestamp){let s=St(this.maxNotificationDays$.getValue()),a=fi({startAtTimestamp:s,currentDocumentOnly:this.getCurrentDocumentOnly(),currentDocumentId:this.docService.getDocumentPaths()?.documentId,limit:t}),c=o?.userId??"";return G(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:n})??Promise.resolve({})).pipe(O(l=>c&&n&&l?.[c]?.organization?.[n]?.errorCode===Ut.PERMISSION_DENIED?D(null):this.lastNotificationTimestampRows$(r,a,i).pipe(N(g=>{let f=()=>i||this.commonDbService.shouldUseFirestore(),d=[];return Object.keys(g||{}).forEach(p=>{let h=f()?g[p]?.timestamp??0:g[p],A=f()?g[p]?.deletedNotification??!1:!1;if(A&&A.id&&A?.timestamp===h){let U=A.id,z=g[p]?.metadata?.documentId,B=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),x=B?.[z]??{documentMetadata:null,notifications:[]},M=x.notifications??[],H=M?.findIndex(u=>u.id===U);H!==-1&&(M.splice(H,1),this.notificationsByDocumentIdMap$.next(T(I({},B),{[z]:T(I({},x),{notifications:M})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(U)&&this.notificationResolverService.deleteNotification(U,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:p,timestamp:h})}),d}),_(g=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",g),D([]))))))}return D(null)}))}catch(e){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",e),D([])}}lastNotificationTimestampRows$(t,i,e=!1){return e?this.portableNotificationTriggerRows$(t?.organizationId,i.documentId).pipe(N(o=>di(o,i)),It(void 0)):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:t?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:this.toFirestoreTriggerQuery(i)}}).pipe(N(o=>o?.data))}toFirestoreTriggerQuery(t){let i=[Wt(dt("timestamp",">=",t.startAtTimestamp),...t.documentId!==void 0?[dt("metadata.documentId","==",t.documentId)]:[])];return t.limit!==void 0&&(i.push(Kt("timestamp","desc")),i.push(Jt(t.limit))),i}resolveAndUpdateDocumentNotifications(t,i,e){try{if(e!==void 0&&e!==this.notificationListGeneration)return;Object.keys(t).forEach(o=>{let r=t[o]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[o]||{},n;if(i==="user")n=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[o]?.notifications||[]});else if(i==="notification"){let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}else{let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}n.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),this.setNotificationForDocumentIdInCache(o,r,n)})}catch(o){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",o)}}resolveAndMergeUserNotifications(t,i,e=!1,o){try{if(o!==void 0&&o!==this.notificationListGeneration)return;let r=t;if(e&&i==="comment"){let l=this.getUserNotificationsFromServer()??[],g=new Set(t.map(f=>f.notificationId));r=l.filter(f=>g.has(f.notificationId)).concat(t.filter(f=>!l.some(d=>d.notificationId===f.notificationId)))}let n=r.reduce((l,g)=>(l[g.notificationId]=g,l),{}),s;if(i==="user"){let l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else if(i==="notification"){let l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else{let l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}s.forEach(l=>{l.notification=this.getClientNotificationObject(l)});let a=this.getUserNotificationsFromServer()??[],c=new Map(a.map(l=>[l.notificationId,l]));s.forEach(l=>{c.set(l.notificationId,l)}),this.setUserNotificationsFromServer(Array.from(c.values()))}catch(r){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",r)}}fetchNotificationsForDocumentIds(t,i=15){return y(this,null,function*(){try{if(t?.length){let e=this.notificationListGeneration,o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let r=this.getStartAtTimestamp(),n={};t.forEach(h=>{if(h?.documentId){let A=this.getAllowedDocumentMetadataByDocumentId(h.documentId);A&&(n[h.documentId]=A)}}),this.userPermissionService?.isPermissionProviderAvailable()&&(t=yield this.filterDocumentIdsByPermissionProvider(t));let s=this.userScopedNotifications$.getValue(),a=!!s?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!a))return[];let c=this.userPermissionService?.getPermissionsCache()?.filter(h=>h.type===Q.CONTEXT),l=I({organizationId:o,documentIds:t.filter(h=>!!h.documentId&&!!h.timestamp).map(h=>({documentId:h.documentId,timestamp:h.timestamp??0})),timestamp:r,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:c,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},a&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:ui(s?.limit)}),{notificationsByDocumentId:g,userNotifications:f=[],userNotificationIdsInDocNotifications:d=[],permissionResults:p=[]}=yield this.callGetNotificationsForDocuments(l);if(e!==this.notificationListGeneration)return[];if(this.userPermissionService?.getIsContextEnabled()){let h=[...this.userPermissionService?.getPermissionsCache()??[],...p??[]];this.userPermissionService?.setPermissionsCache(h)}if(g&&typeof g=="object"){let h=this.usersService.userDataProviderAvailable(),A=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),U=this.notificationResolverService.notificationDataProviderAvailable(),z=[],B=[],x=[];Object.keys(g).forEach((u,C)=>{let E=g[u].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[u];if(E){let $=this.allowedDocumentMetadataMap$.value||{};(!$?.[u]||!X($?.[u],E))&&this.allowedDocumentMetadataMap$.next(T(I({},$),{[u]:E}))}let L=g[u].notifications||[];L.forEach($=>{d.includes($.notificationId)&&!f.find(mi=>mi.notificationId===$.notificationId)&&f.push(JSON.parse(JSON.stringify($))),$.notification=this.getClientNotificationObject($)}),this.setNotificationForDocumentIdInCache(u,E,L),h&&(z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldAwait:!0,forceResolve:!0})),z.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldAwait:!0,forceResolve:!0}))),A&&(B.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldCommentAnnotationsResolverAwait:!0})),B.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldCommentAnnotationsResolverAwait:!0}))),U&&(x.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldNotificationResolverAwait:!0})),x.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldNotificationResolverAwait:!0})))});let M=JSON.parse(JSON.stringify(f));if(a){let u=new Map((this.getUserNotificationsFromServer()??[]).map(C=>[C?.notificationId,C]));f.forEach(C=>u.set(C?.notificationId,C)),this.setUserNotificationsFromServer(Array.from(u.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...f]);(U||h||A)&&(()=>{let u=Promise.resolve();if(U&&(u=u.then(()=>Promise.allSettled(x)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"notification",e),this.resolveAndMergeUserNotifications(M,"notification",!1,e)})),h&&(u=u.then(()=>Promise.allSettled(z)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"user",e),this.resolveAndMergeUserNotifications(M,"user",!1,e)})),A){let C=U||h;u=u.then(()=>Promise.allSettled(B)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"comment",e),this.resolveAndMergeUserNotifications(M,"comment",C,e)})}return u})().catch(u=>{this.loggingService.catch("Error in NotificationService resolveChain: ",u)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}filterDocumentIdsByPermissionProvider(t){return y(this,null,function*(){try{let i=[];if(t.forEach(s=>{this.docService.getDocumentMetadata(s.documentId)||i.push(s.documentId)}),i.length){let s=this.authService.getUser(),a={type:"getDocumentMetadataFromIds",metadata:{organizationId:s?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:i},c=!!this.adapterSelectorService?.isPortableBackendActive(),l=c?void 0:q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let g=c?yield this.invokePortableSdkProxyOp("getDocumentMetadataFromIds",a):yield ft({methodName:"getDocumentMetadataFromIds",data:a,getSdkProxy:l,userId:s?.userId??""});if(g?.data?.length){let f={};g.data.forEach(d=>{d?.documentId&&(f[d.documentId]=d)}),this.docService.setAllDocumentMetadata(I(I({},this.docService.getAllDocumentMetadataMap()),f))}}catch(g){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",g)}}let e=[],o=[];t.forEach(s=>{let a=this.docService.getDocumentMetadata(s.documentId);a?.clientDocumentId?e.push({userId:this.authService.getUser()?.userId??"",resource:I({id:a.clientDocumentId,type:Q.DOCUMENT,source:K.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},a.folderId&&{parentFolderId:a.folderId})}):o.push(s.documentId)}),o.length&&(t=t.filter(s=>!o.includes(s.documentId)));let r=Ft();this.coreActionsService.triggerAction(At.PERMISSION_PROVIDER,{event:j.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:K.GET_NOTIFICATIONS,source:"internal",payload:{requests:e}});let n=yield this.userPermissionService?.onResourceAccessRequired({requests:e,uniqueId:r,methodName:K.GET_NOTIFICATIONS});return n?.success&&n?.data?.length?n.data.forEach(s=>{!s.hasAccess&&s.resourceId&&(t=t.filter(a=>a.documentId!==Pt(s.resourceId)))}):t=[],t}catch(i){return this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}callGetNotificationsForDocuments(t){return y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.callPortableGetNotificationsForDocuments(t);let i=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),r=o?.data?.data?.veltData||{},n=o?.data?.data?.veltAdditionalData||{},s="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),a=yield gt(r,s),{userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield gt(n,s);return{notificationsByDocumentId:a,userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}})}callPortableGetNotificationsForDocuments(t){return y(this,null,function*(){let i=yield this.adapterSelectorService.resolveDbAdapter().getNotificationsForDocuments({scope:"org",data:t});if(!i?.ok)throw new Error(`getNotificationsForDocuments failed on the portable gateway: ${i?.code??"unknown"}`);let e=i.data??{},o=e.veltData??{},{userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}=e.veltAdditionalData??{};return{notificationsByDocumentId:o,userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}})}invokePortableSdkProxyOp(t,i){return y(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveDbAdapter()[t]({scope:"org",data:i});return e?.ok?e.data?.veltData:(this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i)}catch(e){return this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,r)=>o===r.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 r=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(r);i||(i=this.getOwnDocumentMetadata(t)),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{})));let s=this.notificationsByDocumentIdMap$.getValue(),a=s?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let p=d?.notification;return p?(p.metadata&&(p.metadata.documentName=i?.documentName||p.metadata.documentName,p.metadata.organizationMetadata=n||p.metadata.organizationMetadata,p.metadata.documentMetadata=hi(i,p.metadata.documentMetadata)),c&&(p=this.notificationUtilsService.mergeLocationWithNotification({notification:p},c)?.notification),p):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,p)=>(p.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},s),{[t]:{notifications:f,documentMetadata:i||{}}}))}catch(r){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",r)}}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{return St(this.maxNotificationDays$.getValue())}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(O(t=>D(t).pipe(w(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),r=this.notificationResolverService?.notificationDataProviderAvailable();if(r||e||o){let s=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});r&&(s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s||[]})),e&&(s=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s||[]})),o&&(s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s||[]})),i=Object.values(s??{})}return i.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),i.sort((s,a)=>a.timestamp-s.timestamp),i.map(s=>s.notification).filter(s=>!!s)}),O(i=>{let e={data:i?.reduce((o,r)=>(o[r.id]={notification:r},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(r=>r?.notification)))}))),O(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),O(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),r=this.docService.getOrganizationMetadata(e);o||(o=this.getOwnDocumentMetadata(i.metadata.documentId)),r||(r=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=r||i.metadata.organizationMetadata,i.metadata.documentMetadata=hi(o,i.metadata.documentMetadata)}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),D(null)}}getNotificationsForYou(){try{return V([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),D({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],r=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=r(a);c!=null&&n.add(c)});let s=[...o];return e.forEach(a=>{let c=r(a);c!=null&&n.has(c)||(c!=null&&n.add(c),s.push(a))}),s.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(I({},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(I({},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(r=>r==="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),W(),w(t=>!!t),_(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),Y))).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:R(t),isCollection:!1,useCollectionGroup:!1}}).pipe(_(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),Y))).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??""),W(),at(),w(([i])=>!!i),_(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),Y))).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(r=>{typeof r=="string"&&r.length&&(i[r]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(r=>{if(typeof r=="string"&&r.length){let n=Number(o[r]);i[r]=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(I({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(I({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return y(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 r=this.commonDbService?.isPortableSession?.()===!0,n=new Map;for(let a of t){let c=r?a?.metadata?.clientOrganizationId??"":a?.metadata?.clientOrganizationId??a?.metadata?.organizationId??"",l=n.get(c);l?l.push(a):n.set(c,[a])}let s=[];for(let[a,c]of n){if(r&&!a){s.push(...c);continue}let l=c.reduce((f,d,p)=>{let h=d?.notificationId??d?.id??`__cross_org_${p}`;return f[h]=d,f},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:l,organizationId:a||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let g=l;i&&(g=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:g??{}})),e&&(g=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:g??{}})),o&&(g=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:g??{}})),s.push(...Object.values(g??{}))}return s}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return y(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,r=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(r).filter(f=>f!==e&&(r[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let s=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(s);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:r,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:r})}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 y(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 r=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(r,{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 y(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||[],r=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=r(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),s=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=s.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>r(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 y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.invokePortableSdkProxyOp("getCrossOrgUserNotifications",I({type:"getCrossOrgUserNotifications"},t));let i=this.authService.getUser(),e=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ft({methodName:"getCrossOrgUserNotifications",data:I({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},r=e?.isInitial??!0,n=e?.bumpedOrgs??[],s=Array.isArray(o.organizationIds),a=s?o.organizationIds.filter(d=>!!d).map(d=>lt(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>lt(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),r)s&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(h=>!!h&&!l.has(h));if(s){let h=new Set(a);d=d.filter(A=>h.has(A))}d=Array.from(new Set(d)),f.organizationIds=d;let p={};d.forEach(h=>{p[h]=this.crossOrgSeenTimestamps[h]??this.getStartAtTimestamp()}),f.orgTimestamps=p}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(s=>s?.id??s?.notificationId).filter(s=>s!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),r=!1,n=o?i.filter(s=>{let a=s?.id??s?.notificationId,c=a!=null&&e.has(a);return c&&(r=!0),!c}):i.map(s=>{let a=s?.id??s?.notificationId;return a!=null&&e.has(a)&&s?.isUnread!==!1?(r=!0,T(I({},s),{isUnread:!1})):s});r&&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=ct(t)),i&&typeof i=="object"){let r=Mt(i);e=ct(JSON.stringify(r))}}catch(r){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",r)}return this.authService.getAuthState$().pipe(w(r=>!!r),O(r=>this.isFeatureAllowed({firebaseUser:r})),O(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(r.featureAllowed=n,r))):D(r)),O(r=>!r.featureAllowed||r?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),D([])):D(r).pipe(O(n=>this.docService.getDocumentPaths$().pipe(N(s=>(this.documentPaths=s,n.documentPaths=s,n)))),O(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(w(i=>!!i),N(i=>T(I({},t),{config:i})),O(i=>this.authService.getUser$().pipe(N(e=>T(I({},i),{user:e})))),O(i=>Rt(i.config,i.user,Tt.NOTIFICATION)?D(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),D(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(w(i=>!!i),O(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(_(r=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",r),D(null))),N(r=>{let n=[],s=new Map;r?.raw&&(Object.keys(r?.raw||{}).forEach(c=>{let l=r?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&s.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(s);let a=[];r?.processed&&Object.keys(r?.processed||{}).forEach(c=>{let l=r?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return D(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=R(t?.email));let o;t?.userId&&(o=R(t?.userId));let r=new Map;this.processedNotifications$.getValue().forEach(s=>{if(s.id&&s?.displayHeadlineMessageTemplate){let a=!1;(e&&s.notifyUsers?.[e]||o&&s.notifyUsers?.[o])&&(a=!0);let c={id:s.id,notificationSource:s.notificationSource,actionType:s.actionType,actionUser:s.actionUser,timestamp:s.timestamp,targetAnnotationId:s.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:a,notificationSourceData:s.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))}r.set(s.id,c)}}),r.forEach((s,a)=>{s.isUnread=s?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],r.set(a,s)}),this.notificationsByIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:r}){try{let n=this.authService.getUser(),s=r||t;if(s.id&&s?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=R(n?.email));let c=null;n?.userId&&(c=R(n?.userId));let l=!1,g=!0;(a&&s.notifyUsers?.[a]||c&&s.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:s.id};if(r?f=T(I(I({},f),r),{displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),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||r?.notificationSourceData&&(d=r?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),r?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=r.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,r=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:r,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return V([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(N(([t,i,e])=>{let o=Array.isArray(i)?i:[],r=Array.isArray(e)?e:[],n=null;if(t&&(n=[],t.forEach(a=>{a.notifications.forEach(c=>{n?.push(c)})})),!o.length&&!r.length)return t?n.sort((a,c)=>c.timestamp-a.timestamp):null;if(!t)return null;let s=n||[];return r.length&&(s=this.mergeCrossOrgForYou(s,r)),o.length&&(s=this.mergeCrossOrgForYou(s,o)),s}))}getUserScopedAllTabRows$(){return V([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(N(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}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 r=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=r?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=r?.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 s=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,s);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}reportDroppedHubPush(t){try{if(!this.notificationsHubDisabled)return;let i=String(t?.notificationSource??"comment");if(this.isCarriedByPortableDeleteOp(t)||this.reportedDroppedHubPushes.has(i))return;this.reportedDroppedHubPushes.add(i),this.loggingService.catch(`Velt [self-hosted]: a client-side notification-hub push (source '${i}') was dropped \u2014 the notifications hub is deliberately disabled on this deployment (no-egress). Whatever this push fed (in-app notification, email, or webhook fan-out) will not happen for this source.`,void 0,void 0,!0)}catch{}}isCarriedByPortableDeleteOp(t){try{return t?.notificationSource==="comment"&&t?.actionType===Ct.DELETED&&!t?.annotationData?.isDraft&&!!this.adapterSelectorService?.isPortableBackendActive()}catch{return!1}}updateNotificationDatabase(t){try{if(!this.notificationsDb){this.reportDroppedHubPush(t);return}let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=oi(t,o=>this.processNotificationData(o),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(O(i=>i?i.organizationId?this.getAllNotifications$().pipe(O(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let r=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&r.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!r.has(n.id)&&r.set(n.id,n)}),Array.from(r.values()).sort((n,s)=>(s.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,r)=>r.timestamp-o.timestamp)),Nt()):D(null)),W(Bt))}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,r=/\{(\w+)\}/g,n=e.replace(r,(s,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]:s);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(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(j.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(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(j.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 y(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(h=>h.notificationId===g.id))i=i.filter(h=>h.notificationId!==g.id);else{let h=i.find(U=>U.notificationId===g.id),A=d.find(U=>U.notificationId===g.id);h&&A?.views&&(h.views=A.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let s=n.metadata?.documentId;if(s&&o?.[s]){let a=o?.[s]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[s].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!X(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return y(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),O(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),D({forYou:null,all:null})}}setNotificationAsRead(e){return y(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let r=R(o?.userId),{metadata:n}=t;if(n){let{apiKey:s,organizationId:a,documentId:c}=n;if(s&&a&&c&&r){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s}});l?.notificationId&&(l?.views?.[r]||(l.views||(l.views={}),l.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[r]){g.views||(g.views={}),g.views[r]={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:r,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 y(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)}})}getOwnDocumentMetadata(t){try{let i=t==null||t===""?null:this.docService.getDocumentMetadata(String(t));return i?JSON.parse(JSON.stringify(i)):null}catch(i){return this.loggingService.catch("Error in NotificationService getOwnDocumentMetadata: ",i),null}}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)}}enableUserScopedNotifications(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableUserScopedNotifications();return}this.userScopedNotifications$.next({enabled:!0,limit:ui(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",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 y(this,null,function*(){try{let i=this.authService.getUser(),e=R(i?.userId??""),o=this.docService.getDocumentPaths(),r=this.docService.getOrganizationConfig(),n=o?.organizationId??r?.organizationId,s=o?.clientOrganizationId??r?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:s,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:s??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:I({documentId:o?.documentId,userId:e},this.commonDbService?.isPortableSession?.()===!0?{id:o.documentId}:{}),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}};m.\u0275fac=function(i){return new(i||m)(S(yt),S(Yt),S(et),S(Gt),S(ni),S(si),S(st),S(rt),S(nt),S(Qt),S(ai),S(ei),S(ci),S(it),S(gi),S(ot),S(Dt),S(li),S(ii),S(tt),S(Zt),S(qt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();export{gi as a,ge as b};
1
+ import{a as li}from"./chunk-5K23BJBD.js";import{a as ci}from"./chunk-4GZINSJB.js";import{A as si,D as ni,E as ai,c as oi,k as ht,o as ri,p as ot,q as rt,s as st,x as mt,z as nt}from"./chunk-W3PIDHPP.js";import{Ak as et,Bj as Wt,Cj as Jt,Dg as zt,Di as Lt,E as w,Eg as gt,Ej as Kt,G as _,Gd as yt,Gj as dt,He as P,Ii as j,Ji as q,Jj as Qt,K as k,Kg as X,Li as _t,Lj as Xt,M as W,Mj as Zt,Ni as jt,O as at,Pj as ut,Q as Nt,Qd as Dt,Qf as Ut,U as It,Uf as Et,Uj as qt,V as O,Wf as $t,Xf as wt,Y as Ot,Yi as Ht,Zd as Ct,Zf as ct,_f as R,_i as Vt,a as I,ag as Pt,b as T,ba as J,cg as lt,ck as ti,di as Bt,ea as S,ee as At,fa as bt,g as y,i as vt,l as b,mi as ft,oi as Z,oj as tt,p as Y,pj as Yt,q as G,qi as xt,qj as it,r as D,re as Tt,rj as Gt,tf as K,uf as Q,ug as Rt,v as N,vg as Ft,vk as ii,w as V,wj as kt,x as pt,yg as Mt,zk as ei}from"./chunk-7CAYUDV6.js";var gi=(()=>{let m=class m{constructor(t,i,e,o,r,n,s){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=r,this.notificationResolverService=n,this.serviceBook=s,this.serviceBook.set(jt,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 r=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of r)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,r=i?.comments?.[e]?.commentHtml;return o&&r&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=r),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 r=i?.[o]?.[e];return r&&(t.notification.notificationSourceData.location=r?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=r?.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{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),this.usersService.userResolverConfigured?.()&&t&&typeof t=="object")for(let e of Object.keys(t))e!=="annotationData"&&e!=="targetAnnotationData"&&Lt(t[e])&&(t[e]=xt(t[e],Et));switch(t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData),t=this.commentUtilsService.stripCommentNotificationPayload(t);break;default:m.carriesCommentPayload(t)&&(t=this.commentUtilsService.stripCommentNotificationPayload(t));break;case"recorder":this.serviceBook.get(Ht)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),m.carriesCommentPayload(t)?this.commentUtilsService?.stripCommentNotificationPayload?.(I({},t))??t:t}}static carriesCommentPayload(t){return!t||typeof t!="object"?!1:t.notificationSource==="comment"||t.notificationSource===void 0&&Array.isArray(t.annotationData?.comments)}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 y(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 zt(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 r=o?.notification?.id||o?.notificationId;r&&i.add(r)}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 r of o)e[r]!==void 0&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]));return Object.keys(e).forEach(r=>{!o.includes(r)&&r!=="notificationId"&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};m.\u0275fac=function(i){return new(i||m)(S(st),S(it),S(ot),S(et),S(rt),S(nt),S(tt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();function St(v,m=new Date){let F=v>0?v:15,t=new Date(m.getTime());return t.setDate(t.getDate()-F),t.getTime()}function fi(v){let m={startAtTimestamp:v.startAtTimestamp};return v.currentDocumentOnly&&v.currentDocumentId&&(m.documentId=v.currentDocumentId),v.currentDocumentOnly||(m.limit=v.limit),m}function di(v,m){let F=[];if(!v||typeof v!="object")return{};for(let e of Object.keys(v)){let o=v[e];if(!o||typeof o!="object")continue;let r=o.timestamp;typeof r!="number"||Number.isNaN(r)||!(r>=m.startAtTimestamp)||m.documentId!==void 0&&o.metadata?.documentId!==m.documentId||F.push({id:e,timestamp:r,row:v[e]})}let t=F;m.limit!==void 0&&(t=[...F].sort((e,o)=>o.timestamp-e.timestamp||(e.id<o.id?1:e.id>o.id?-1:0)).slice(0,Math.max(0,m.limit)));let i={};for(let e of t)i[e.id]=e.row;return i}function ui(v){if(typeof v!="number"||!Number.isFinite(v))return 25;let t=Math.floor(v);return t<1?25:Math.min(200,t)}function hi(v,m){let F=t=>!!t&&typeof t=="object"&&Object.keys(t).length>0;return F(v)?v:F(m)?m:{}}var ge=(()=>{let m=class m{constructor(t,i,e,o,r,n,s,a,c,l,g,f,d,p,h,A,U,z,B,x,M,H){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=r,this.commonDbUtilsService=n,this.commentUtilsService=s,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=p,this.notificationUtilsService=h,this.usersService=A,this.functions=U,this.userPermissionService=z,this.coreActionsService=B,this.serviceBook=x,this.realtimeAdapter=M,this.adapterSelectorService=H,this.endpointsService=bt(kt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new b([]),this.rawNotificationsByIdMap$=new b(new Map),this.processedNotifications$=new b([]),this.userNotificationsFromServer$=new b(null),this.readNotificationsOnForYouTab$=new b(!1),this.currentDocumentOnly$=new b(!1),this.notificationViews$=new b({}),this.notificationsByIdMap$=new b(new Map),this.historyPanelVisible$=new b(!1),this.notificationsForYou$=new b(null),this.notificationsByDocumentIdMap$=new b(null),this.notificationsByDocumentIdSubscription={},this.notificationsHubDisabled=!1,this.reportedDroppedHubPushes=new Set,this.allowedDocumentMetadataMap$=new b(null),this.documentIdsPipelineOnPortableTrigger=!1,this.maxNotificationDays$=new b(15),this.tabConfig$=new b({people:{enable:!1}}),this.settingsConfig$=new b(null),this.setSettingsConfigByOrganization$=new b(!1),this.muteAllNotifications$=new b(!1),this.enableSettings$=new b(!1),this.selfNotifications$=new b(!1),this.userScopedNotifications$=new b({enabled:!1,limit:25}),this.settingsInitialConfig$=new b([{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.notificationListGeneration=0,this.notificationsPanelVisible$=new b(!1),this.crossOrganizationConfig$=new b({enabled:!1}),this.crossOrgNotifications$=new b([]),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(_t,this),this.serviceBook.observe(Vt).subscribe(u=>{this.commentService=u??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(w(u=>!!u),k(1)).subscribe(u=>{if(u){this.db=u;try{let C=this.configService.getProxyConfig(),E=this.endpointsService.getNotificationsDbUrl();$t(E)?(this.notificationsDb=null,this.notificationsHubDisabled=!0):(C?.v1DbHost&&E&&(E=wt(E,C.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(E),C?.v1DbHost&&E&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(C){this.loggingService.catch("Error initializing notifications DB, using default: ",C),this.notificationsDb=u}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},u=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",u)}),this.authService.getUser$().subscribe(u=>{u?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(C=>{this.notificationsByDocumentIdSubscription[C]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),ut(()=>{try{if(this.adapterSelectorService?.isPortableBackendActive()){if(this.documentIdsPipelineOnPortableTrigger)return;this.getDocumentIds()}}catch(u){this.loggingService.catch("Error re-evaluating portable notification list on chunk registration: ",u)}}),this.docService.getLocationMetadata$().subscribe(u=>{if(u){let C=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(u||{}).forEach(E=>{let L=C?.[E]?.notifications;L?.length&&L.forEach($=>{this.notificationUtilsService.mergeLocationWithNotification({notification:$},u)?.notification})}),this.notificationsByDocumentIdMap$.next(C)}})}catch(u){this.loggingService.catch("Error in NotificationService constructor: ",u)}}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 y(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=R(this.authService.getUser()?.userId??""),o,r=!0;if(this.commonDbService?.isPortableSession?.()===!0){let n=yield this.readPortableSettingsConfig(t,e);o=n.data,r=n.answered}else 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 if(!r)this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue()),this.setDBConfigDataToInitialConfig(this.buildDefaultSettingsConfig());else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let n=this.buildDefaultSettingsConfig();yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}buildDefaultSettingsConfig(){let t={};this.settingsInitialConfig$.getValue().forEach(e=>{if(e.enable){let o=e?.values?.find(r=>r.id===e.default);t[e.id]=o||e?.values?.[0]||{id:"NONE",name:"None"}}});let i={};return Object.keys(t).forEach(e=>{i[e]=t[e].id}),i}readPortableSettingsConfig(t,i){return y(this,null,function*(){try{let e=this.resolvePortableSettingsTarget(t,this.getSettingsConfigByOrganization(),this.docService.getOrganizationConfig(),i);return e?yield this.commonDbService.readPortableDoc(e.feature,e.properties):{answered:!1}}catch(e){return this.loggingService.catch("Error in NotificationService readPortableSettingsConfig: ",e),{answered:!1}}})}resolvePortableSettingsTarget(t,i,e,o){if(!this.authService.getUser()?.userId)return null;let r=t?.organizationId??e?.organizationId;return i?this.commonDbService.announcesPortableCapability(ti)?{feature:"organizationUserConfig",properties:{organizationId:r,userId:o}}:null:t?.documentId?{feature:"userConfig",properties:{id:t.documentId,organizationId:r,userId:o}}:null}portableUserSettingsListener$(t,i,e,o){let r=this.resolvePortableSettingsTarget(t,i,e,o);return r?this.commonDbService.dbListener({feature:r.feature,properties:r.properties}):D(void 0)}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=R(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(w(i=>i===!0),O(()=>V([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(w(([i,e,o])=>(e||!!i)&&!!o?.organizationId),O(([i,e,o])=>{let r=N(n=>{n?.data?.notificationsConfig&&!X(n?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(n?.data?.notificationsConfig)});return this.commonDbService?.isPortableSession?.()===!0?this.commonDbService.portableConnectionChanges$().pipe(O(()=>G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.portableUserSettingsListener$(i,e,o,t).pipe(r))))):G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(r)))})))).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=pt(()=>{let t=!!this.adapterSelectorService?.isPortableBackendActive();return this.documentIdsPipelineOnPortableTrigger=t,this.notificationListPipeline$(t)}).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}notificationListPipeline$(t=!1){return this.selfNotifications$.pipe(O(()=>this.getCurrentDocumentOnly$().pipe(O(i=>i?this.docService.getDocumentPaths$().pipe(N(e=>{})):D(void 0)))),Ot(()=>{this.notificationListGeneration++,this.notificationsByDocumentIdMap$.next(null)}),O(()=>this.getDocumentIdsByLastNotificationTimestamp(void 0,t).pipe(at(),N(([i,e])=>{let o=i?.map(c=>c.documentId),r=e?.map(c=>c.documentId),n=o?.filter(c=>!r?.includes(c)),s=r?.map(c=>({documentId:c,timestamp:e?.find(l=>l.documentId===c)?.timestamp})).filter(c=>!o?.includes(c.documentId)),a=r?.map(c=>{let l=e?.find(g=>g.documentId===c)?.timestamp;return{documentId:c,timestamp:l}}).filter(c=>{let l=i?.find(g=>g.documentId===c.documentId)?.timestamp;return l&&c.timestamp&&l!==c.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),a?.length&&this.fetchNotificationsForDocumentIds(a,1),n?.forEach(c=>{this.removeNotificationsForDocumentId(c)}),e&&!e?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))}))))}portableNotificationTriggerRows$(t,i){return new vt(e=>{let o=!1,r=null,n=()=>{try{r?.unsubscribe()}catch(c){this.loggingService.catch("Error releasing the notification trigger subscription: ",c)}r=null},s=()=>{o||(n(),r=this.openPortableNotificationTrigger(t,c=>e.next(c),i))},a=ut(s);return s(),()=>{o=!0;try{a()}catch(c){this.loggingService.catch("Error disposing the notification trigger registration listener: ",c)}n()}})}openPortableNotificationTrigger(t,i,e){try{let o=ri(ht,{apiKey:this.configService.getApiKey(),organizationId:t}),r=this.adapterSelectorService?.resolveRealtimeAdapter?.();if(!o||!r)return null;let n=Xt(o.feature)?.mode??"persistent",s={},a={},c=!1,l=!1;return r.subscribe(o,n,g=>{try{if(l)return;if(typeof g.seq=="number"){let f=a[g.id];if(f!==void 0&&g.seq<=f)return;a[g.id]=g.seq}g.type==="removed"?delete s[g.id]:s[g.id]=g.data,c&&typeof g.seq=="number"&&i(I({},s))}catch(f){this.loggingService.catch("Error materializing a notification trigger delta: ",f)}},I({onSnapshotComplete:g=>{try{if(l)return;if(g?.full===!0)for(let f of Object.keys(a))delete a[f];c=!0,i(I({},s))}catch(f){this.loggingService.catch("Error completing the notification trigger snapshot: ",f)}},onError:g=>{l=!0,this.loggingService.catch(`Portable channel denied for ${ht}: `,{ok:!1,code:g})}},e?{documentId:e}:{}))}catch(o){return this.loggingService.catch("Error subscribing the notification trigger channel: ",o),null}}getDocumentIdsByLastNotificationTimestamp(t=15,i=!1){try{return this.authService.getUser$().pipe(O(e=>this.docService.getOrganizationConfig$().pipe(N(o=>{let r=null,n=this.configService.getApiKey(),s=o?.organizationId||e?.organizationId,a=o?.clientOrganizationId||e?.clientOrganizationId||"";return n&&s&&(r=new mt({apiKey:n,organizationId:s})),{user:e,documentPaths:r,clientOrganizationId:a}}))),O(e=>{let{user:o,documentPaths:r,clientOrganizationId:n}=e;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return D(null);if(o&&r?.organizationNotificationsLastNotificationTimestamp){let s=St(this.maxNotificationDays$.getValue()),a=fi({startAtTimestamp:s,currentDocumentOnly:this.getCurrentDocumentOnly(),currentDocumentId:this.docService.getDocumentPaths()?.documentId,limit:t}),c=o?.userId??"";return G(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:n})??Promise.resolve({})).pipe(O(l=>c&&n&&l?.[c]?.organization?.[n]?.errorCode===Ut.PERMISSION_DENIED?D(null):this.lastNotificationTimestampRows$(r,a,i).pipe(N(g=>{let f=()=>i||this.commonDbService.shouldUseFirestore(),d=[];return Object.keys(g||{}).forEach(p=>{let h=f()?g[p]?.timestamp??0:g[p],A=f()?g[p]?.deletedNotification??!1:!1;if(A&&A.id&&A?.timestamp===h){let U=A.id,z=g[p]?.metadata?.documentId,B=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),x=B?.[z]??{documentMetadata:null,notifications:[]},M=x.notifications??[],H=M?.findIndex(u=>u.id===U);H!==-1&&(M.splice(H,1),this.notificationsByDocumentIdMap$.next(T(I({},B),{[z]:T(I({},x),{notifications:M})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(U)&&this.notificationResolverService.deleteNotification(U,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:p,timestamp:h})}),d}),_(g=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",g),D([]))))))}return D(null)}))}catch(e){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",e),D([])}}lastNotificationTimestampRows$(t,i,e=!1){return e?this.portableNotificationTriggerRows$(t?.organizationId,i.documentId).pipe(N(o=>di(o,i)),It(void 0)):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:t?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:this.toFirestoreTriggerQuery(i)}}).pipe(N(o=>o?.data))}toFirestoreTriggerQuery(t){let i=[Wt(dt("timestamp",">=",t.startAtTimestamp),...t.documentId!==void 0?[dt("metadata.documentId","==",t.documentId)]:[])];return t.limit!==void 0&&(i.push(Kt("timestamp","desc")),i.push(Jt(t.limit))),i}resolveAndUpdateDocumentNotifications(t,i,e){try{if(e!==void 0&&e!==this.notificationListGeneration)return;Object.keys(t).forEach(o=>{let r=t[o]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[o]||{},n;if(i==="user")n=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[o]?.notifications||[]});else if(i==="notification"){let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}else{let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}n.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),this.setNotificationForDocumentIdInCache(o,r,n)})}catch(o){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",o)}}resolveAndMergeUserNotifications(t,i,e=!1,o){try{if(o!==void 0&&o!==this.notificationListGeneration)return;let r=t;if(e&&i==="comment"){let l=this.getUserNotificationsFromServer()??[],g=new Set(t.map(f=>f.notificationId));r=l.filter(f=>g.has(f.notificationId)).concat(t.filter(f=>!l.some(d=>d.notificationId===f.notificationId)))}let n=r.reduce((l,g)=>(l[g.notificationId]=g,l),{}),s;if(i==="user"){let l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else if(i==="notification"){let l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else{let l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}s.forEach(l=>{l.notification=this.getClientNotificationObject(l)});let a=this.getUserNotificationsFromServer()??[],c=new Map(a.map(l=>[l.notificationId,l]));s.forEach(l=>{c.set(l.notificationId,l)}),this.setUserNotificationsFromServer(Array.from(c.values()))}catch(r){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",r)}}fetchNotificationsForDocumentIds(t,i=15){return y(this,null,function*(){try{if(t?.length){let e=this.notificationListGeneration,o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let r=this.getStartAtTimestamp(),n={};t.forEach(h=>{if(h?.documentId){let A=this.getAllowedDocumentMetadataByDocumentId(h.documentId);A&&(n[h.documentId]=A)}}),this.userPermissionService?.isPermissionProviderAvailable()&&(t=yield this.filterDocumentIdsByPermissionProvider(t));let s=this.userScopedNotifications$.getValue(),a=!!s?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!a))return[];let c=this.userPermissionService?.getPermissionsCache()?.filter(h=>h.type===Q.CONTEXT),l=I({organizationId:o,documentIds:t.filter(h=>!!h.documentId&&!!h.timestamp).map(h=>({documentId:h.documentId,timestamp:h.timestamp??0})),timestamp:r,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:c,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},a&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:ui(s?.limit)}),{notificationsByDocumentId:g,userNotifications:f=[],userNotificationIdsInDocNotifications:d=[],permissionResults:p=[]}=yield this.callGetNotificationsForDocuments(l);if(e!==this.notificationListGeneration)return[];if(this.userPermissionService?.getIsContextEnabled()){let h=[...this.userPermissionService?.getPermissionsCache()??[],...p??[]];this.userPermissionService?.setPermissionsCache(h)}if(g&&typeof g=="object"){let h=this.usersService.userDataProviderAvailable(),A=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),U=this.notificationResolverService.notificationDataProviderAvailable(),z=[],B=[],x=[];Object.keys(g).forEach((u,C)=>{let E=g[u].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[u];if(E){let $=this.allowedDocumentMetadataMap$.value||{};(!$?.[u]||!X($?.[u],E))&&this.allowedDocumentMetadataMap$.next(T(I({},$),{[u]:E}))}let L=g[u].notifications||[];L.forEach($=>{d.includes($.notificationId)&&!f.find(mi=>mi.notificationId===$.notificationId)&&f.push(JSON.parse(JSON.stringify($))),$.notification=this.getClientNotificationObject($)}),this.setNotificationForDocumentIdInCache(u,E,L),h&&(z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldAwait:!0,forceResolve:!0})),z.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldAwait:!0,forceResolve:!0}))),A&&(B.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldCommentAnnotationsResolverAwait:!0})),B.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldCommentAnnotationsResolverAwait:!0}))),U&&(x.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldNotificationResolverAwait:!0})),x.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldNotificationResolverAwait:!0})))});let M=JSON.parse(JSON.stringify(f));if(a){let u=new Map((this.getUserNotificationsFromServer()??[]).map(C=>[C?.notificationId,C]));f.forEach(C=>u.set(C?.notificationId,C)),this.setUserNotificationsFromServer(Array.from(u.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...f]);(U||h||A)&&(()=>{let u=Promise.resolve();if(U&&(u=u.then(()=>Promise.allSettled(x)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"notification",e),this.resolveAndMergeUserNotifications(M,"notification",!1,e)})),h&&(u=u.then(()=>Promise.allSettled(z)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"user",e),this.resolveAndMergeUserNotifications(M,"user",!1,e)})),A){let C=U||h;u=u.then(()=>Promise.allSettled(B)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"comment",e),this.resolveAndMergeUserNotifications(M,"comment",C,e)})}return u})().catch(u=>{this.loggingService.catch("Error in NotificationService resolveChain: ",u)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}filterDocumentIdsByPermissionProvider(t){return y(this,null,function*(){try{let i=[];if(t.forEach(s=>{this.docService.getDocumentMetadata(s.documentId)||i.push(s.documentId)}),i.length){let s=this.authService.getUser(),a={type:"getDocumentMetadataFromIds",metadata:{organizationId:s?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:i},c=!!this.adapterSelectorService?.isPortableBackendActive(),l=c?void 0:q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let g=c?yield this.invokePortableSdkProxyOp("getDocumentMetadataFromIds",a):yield ft({methodName:"getDocumentMetadataFromIds",data:a,getSdkProxy:l,userId:s?.userId??""});if(g?.data?.length){let f={};g.data.forEach(d=>{d?.documentId&&(f[d.documentId]=d)}),this.docService.setAllDocumentMetadata(I(I({},this.docService.getAllDocumentMetadataMap()),f))}}catch(g){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",g)}}let e=[],o=[];t.forEach(s=>{let a=this.docService.getDocumentMetadata(s.documentId);a?.clientDocumentId?e.push({userId:this.authService.getUser()?.userId??"",resource:I({id:a.clientDocumentId,type:Q.DOCUMENT,source:K.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},a.folderId&&{parentFolderId:a.folderId})}):o.push(s.documentId)}),o.length&&(t=t.filter(s=>!o.includes(s.documentId)));let r=Ft();this.coreActionsService.triggerAction(At.PERMISSION_PROVIDER,{event:j.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:K.GET_NOTIFICATIONS,source:"internal",payload:{requests:e}});let n=yield this.userPermissionService?.onResourceAccessRequired({requests:e,uniqueId:r,methodName:K.GET_NOTIFICATIONS});return n?.success&&n?.data?.length?n.data.forEach(s=>{!s.hasAccess&&s.resourceId&&(t=t.filter(a=>a.documentId!==Pt(s.resourceId)))}):t=[],t}catch(i){return this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}callGetNotificationsForDocuments(t){return y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.callPortableGetNotificationsForDocuments(t);let i=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),r=o?.data?.data?.veltData||{},n=o?.data?.data?.veltAdditionalData||{},s="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),a=yield gt(r,s),{userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield gt(n,s);return{notificationsByDocumentId:a,userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}})}callPortableGetNotificationsForDocuments(t){return y(this,null,function*(){let i=yield this.adapterSelectorService.resolveDbAdapter().getNotificationsForDocuments({scope:"org",data:t});if(!i?.ok)throw new Error(`getNotificationsForDocuments failed on the portable gateway: ${i?.code??"unknown"}`);let e=i.data??{},o=e.veltData??{},{userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}=e.veltAdditionalData??{};return{notificationsByDocumentId:o,userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}})}invokePortableSdkProxyOp(t,i){return y(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveDbAdapter()[t]({scope:"org",data:i});return e?.ok?e.data?.veltData:(this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i)}catch(e){return this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,r)=>o===r.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 r=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(r);i||(i=this.getOwnDocumentMetadata(t)),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{})));let s=this.notificationsByDocumentIdMap$.getValue(),a=s?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let p=d?.notification;return p?(p.metadata&&(p.metadata.documentName=i?.documentName||p.metadata.documentName,p.metadata.organizationMetadata=n||p.metadata.organizationMetadata,p.metadata.documentMetadata=hi(i,p.metadata.documentMetadata)),c&&(p=this.notificationUtilsService.mergeLocationWithNotification({notification:p},c)?.notification),p):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,p)=>(p.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},s),{[t]:{notifications:f,documentMetadata:i||{}}}))}catch(r){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",r)}}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{return St(this.maxNotificationDays$.getValue())}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(O(t=>D(t).pipe(w(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),r=this.notificationResolverService?.notificationDataProviderAvailable();if(r||e||o){let s=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});r&&(s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s||[]})),e&&(s=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s||[]})),o&&(s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s||[]})),i=Object.values(s??{})}return i.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),i.sort((s,a)=>a.timestamp-s.timestamp),i.map(s=>s.notification).filter(s=>!!s)}),O(i=>{let e={data:i?.reduce((o,r)=>(o[r.id]={notification:r},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(r=>r?.notification)))}))),O(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),O(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),r=this.docService.getOrganizationMetadata(e);o||(o=this.getOwnDocumentMetadata(i.metadata.documentId)),r||(r=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=r||i.metadata.organizationMetadata,i.metadata.documentMetadata=hi(o,i.metadata.documentMetadata)}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),D(null)}}getNotificationsForYou(){try{return V([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),D({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],r=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=r(a);c!=null&&n.add(c)});let s=[...o];return e.forEach(a=>{let c=r(a);c!=null&&n.has(c)||(c!=null&&n.add(c),s.push(a))}),s.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(I({},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(I({},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(r=>r==="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),W(),w(t=>!!t),_(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),Y))).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:R(t),isCollection:!1,useCollectionGroup:!1}}).pipe(_(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),Y))).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??""),W(),at(),w(([i])=>!!i),_(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),Y))).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(r=>{typeof r=="string"&&r.length&&(i[r]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(r=>{if(typeof r=="string"&&r.length){let n=Number(o[r]);i[r]=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(I({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(I({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return y(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 r=this.commonDbService?.isPortableSession?.()===!0,n=new Map;for(let a of t){let c=r?a?.metadata?.clientOrganizationId??"":a?.metadata?.clientOrganizationId??a?.metadata?.organizationId??"",l=n.get(c);l?l.push(a):n.set(c,[a])}let s=[];for(let[a,c]of n){if(r&&!a){s.push(...c);continue}let l=c.reduce((f,d,p)=>{let h=d?.notificationId??d?.id??`__cross_org_${p}`;return f[h]=d,f},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:l,organizationId:a||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let g=l;i&&(g=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:g??{}})),e&&(g=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:g??{}})),o&&(g=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:g??{}})),s.push(...Object.values(g??{}))}return s}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return y(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,r=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(r).filter(f=>f!==e&&(r[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let s=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(s);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:r,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:r})}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 y(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 r=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(r,{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 y(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||[],r=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=r(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),s=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=s.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>r(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 y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.invokePortableSdkProxyOp("getCrossOrgUserNotifications",I({type:"getCrossOrgUserNotifications"},t));let i=this.authService.getUser(),e=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ft({methodName:"getCrossOrgUserNotifications",data:I({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},r=e?.isInitial??!0,n=e?.bumpedOrgs??[],s=Array.isArray(o.organizationIds),a=s?o.organizationIds.filter(d=>!!d).map(d=>lt(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>lt(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),r)s&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(h=>!!h&&!l.has(h));if(s){let h=new Set(a);d=d.filter(A=>h.has(A))}d=Array.from(new Set(d)),f.organizationIds=d;let p={};d.forEach(h=>{p[h]=this.crossOrgSeenTimestamps[h]??this.getStartAtTimestamp()}),f.orgTimestamps=p}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(s=>s?.id??s?.notificationId).filter(s=>s!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),r=!1,n=o?i.filter(s=>{let a=s?.id??s?.notificationId,c=a!=null&&e.has(a);return c&&(r=!0),!c}):i.map(s=>{let a=s?.id??s?.notificationId;return a!=null&&e.has(a)&&s?.isUnread!==!1?(r=!0,T(I({},s),{isUnread:!1})):s});r&&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=ct(t)),i&&typeof i=="object"){let r=Mt(i);e=ct(JSON.stringify(r))}}catch(r){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",r)}return this.authService.getAuthState$().pipe(w(r=>!!r),O(r=>this.isFeatureAllowed({firebaseUser:r})),O(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(r.featureAllowed=n,r))):D(r)),O(r=>!r.featureAllowed||r?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),D([])):D(r).pipe(O(n=>this.docService.getDocumentPaths$().pipe(N(s=>(this.documentPaths=s,n.documentPaths=s,n)))),O(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(w(i=>!!i),N(i=>T(I({},t),{config:i})),O(i=>this.authService.getUser$().pipe(N(e=>T(I({},i),{user:e})))),O(i=>Rt(i.config,i.user,Tt.NOTIFICATION)?D(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),D(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(w(i=>!!i),O(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(_(r=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",r),D(null))),N(r=>{let n=[],s=new Map;r?.raw&&(Object.keys(r?.raw||{}).forEach(c=>{let l=r?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&s.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(s);let a=[];r?.processed&&Object.keys(r?.processed||{}).forEach(c=>{let l=r?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return D(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=R(t?.email));let o;t?.userId&&(o=R(t?.userId));let r=new Map;this.processedNotifications$.getValue().forEach(s=>{if(s.id&&s?.displayHeadlineMessageTemplate){let a=!1;(e&&s.notifyUsers?.[e]||o&&s.notifyUsers?.[o])&&(a=!0);let c={id:s.id,notificationSource:s.notificationSource,actionType:s.actionType,actionUser:s.actionUser,timestamp:s.timestamp,targetAnnotationId:s.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:a,notificationSourceData:s.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))}r.set(s.id,c)}}),r.forEach((s,a)=>{s.isUnread=s?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],r.set(a,s)}),this.notificationsByIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:r}){try{let n=this.authService.getUser(),s=r||t;if(s.id&&s?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=R(n?.email));let c=null;n?.userId&&(c=R(n?.userId));let l=!1,g=!0;(a&&s.notifyUsers?.[a]||c&&s.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:s.id};if(r?f=T(I(I({},f),r),{displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),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||r?.notificationSourceData&&(d=r?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),r?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=r.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,r=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:r,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return V([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(N(([t,i,e])=>{let o=Array.isArray(i)?i:[],r=Array.isArray(e)?e:[],n=null;if(t&&(n=[],t.forEach(a=>{a.notifications.forEach(c=>{n?.push(c)})})),!o.length&&!r.length)return t?n.sort((a,c)=>c.timestamp-a.timestamp):null;if(!t)return null;let s=n||[];return r.length&&(s=this.mergeCrossOrgForYou(s,r)),o.length&&(s=this.mergeCrossOrgForYou(s,o)),s}))}getUserScopedAllTabRows$(){return V([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(N(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}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 r=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=r?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=r?.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 s=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,s);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}reportDroppedHubPush(t){try{if(!this.notificationsHubDisabled)return;let i=String(t?.notificationSource??"comment");if(this.isCarriedByPortableDeleteOp(t)||this.reportedDroppedHubPushes.has(i))return;this.reportedDroppedHubPushes.add(i),this.loggingService.catch(`Velt [self-hosted]: a client-side notification-hub push (source '${i}') was dropped \u2014 the notifications hub is deliberately disabled on this deployment (no-egress). Whatever this push fed (in-app notification, email, or webhook fan-out) will not happen for this source.`,void 0,void 0,!0)}catch{}}isCarriedByPortableDeleteOp(t){try{return t?.notificationSource==="comment"&&t?.actionType===Ct.DELETED&&!t?.annotationData?.isDraft&&!!this.adapterSelectorService?.isPortableBackendActive()}catch{return!1}}updateNotificationDatabase(t){try{if(!this.notificationsDb){this.reportDroppedHubPush(t);return}let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=oi(t,o=>this.processNotificationData(o),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(O(i=>i?i.organizationId?this.getAllNotifications$().pipe(O(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let r=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&r.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!r.has(n.id)&&r.set(n.id,n)}),Array.from(r.values()).sort((n,s)=>(s.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,r)=>r.timestamp-o.timestamp)),Nt()):D(null)),W(Bt))}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,r=/\{(\w+)\}/g,n=e.replace(r,(s,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]:s);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(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(j.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(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(j.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 y(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(h=>h.notificationId===g.id))i=i.filter(h=>h.notificationId!==g.id);else{let h=i.find(U=>U.notificationId===g.id),A=d.find(U=>U.notificationId===g.id);h&&A?.views&&(h.views=A.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let s=n.metadata?.documentId;if(s&&o?.[s]){let a=o?.[s]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[s].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!X(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return y(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),O(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),D({forYou:null,all:null})}}setNotificationAsRead(e){return y(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let r=R(o?.userId),{metadata:n}=t;if(n){let{apiKey:s,organizationId:a,documentId:c}=n;if(s&&a&&c&&r){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s}});l?.notificationId&&(l?.views?.[r]||(l.views||(l.views={}),l.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[r]){g.views||(g.views={}),g.views[r]={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:r,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 y(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)}})}getOwnDocumentMetadata(t){try{let i=t==null||t===""?null:this.docService.getDocumentMetadata(String(t));return i?JSON.parse(JSON.stringify(i)):null}catch(i){return this.loggingService.catch("Error in NotificationService getOwnDocumentMetadata: ",i),null}}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)}}enableUserScopedNotifications(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableUserScopedNotifications();return}this.userScopedNotifications$.next({enabled:!0,limit:ui(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",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 y(this,null,function*(){try{let i=this.authService.getUser(),e=R(i?.userId??""),o=this.docService.getDocumentPaths(),r=this.docService.getOrganizationConfig(),n=o?.organizationId??r?.organizationId,s=o?.clientOrganizationId??r?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:s,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:s??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:I({documentId:o?.documentId,userId:e},this.commonDbService?.isPortableSession?.()===!0?{id:o.documentId}:{}),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}};m.\u0275fac=function(i){return new(i||m)(S(yt),S(Yt),S(et),S(Gt),S(ni),S(si),S(st),S(rt),S(nt),S(Qt),S(ai),S(ei),S(ci),S(it),S(gi),S(ot),S(Dt),S(li),S(ii),S(tt),S(Zt),S(qt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();export{gi as a,ge as b};
@@ -1,2 +1,2 @@
1
- import{Cb as a,Db as h,Ra as o,Wa as c,fb as m,qj as g,ya as s,zk as l}from"./chunk-XRSE2VTK.js";var d=["*"],C=(()=>{let i=class i{constructor(t,e,n){this.elementRef=t,this.domService=e,this.loggingService=n,this.veltElement=!0}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(t){this.loggingService.catch("Error in ShadowDomComponent ngAfterViewInit: ",t)}}ngOnDestroy(){try{this.customCssSubscription?.unsubscribe()}catch(t){this.loggingService.catch("Error in ShadowDomComponent ngOnDestroy: ",t)}}};i.\u0275fac=function(e){return new(e||i)(o(s),o(l),o(g))},i.\u0275cmp=c({type:i,selectors:[["velt-shadow-dom-internal"]],hostVars:1,hostBindings:function(e,n){e&2&&m("data-velt-element",n.veltElement)},ngContentSelectors:d,decls:1,vars:0,template:function(e,n){e&1&&(a(),h(0))},styles:[`:host{width:100%}
1
+ import{Cb as a,Db as h,Ra as o,Wa as c,fb as m,qj as g,ya as s,zk as l}from"./chunk-7CAYUDV6.js";var d=["*"],C=(()=>{let i=class i{constructor(t,e,n){this.elementRef=t,this.domService=e,this.loggingService=n,this.veltElement=!0}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(t){this.loggingService.catch("Error in ShadowDomComponent ngAfterViewInit: ",t)}}ngOnDestroy(){try{this.customCssSubscription?.unsubscribe()}catch(t){this.loggingService.catch("Error in ShadowDomComponent ngOnDestroy: ",t)}}};i.\u0275fac=function(e){return new(e||i)(o(s),o(l),o(g))},i.\u0275cmp=c({type:i,selectors:[["velt-shadow-dom-internal"]],hostVars:1,hostBindings:function(e,n){e&2&&m("data-velt-element",n.veltElement)},ngContentSelectors:d,decls:1,vars:0,template:function(e,n){e&1&&(a(),h(0))},styles:[`:host{width:100%}
2
2
  `],encapsulation:3,changeDetection:0});let r=i;return r})();export{C as a};
@@ -1 +1 @@
1
- import{$ as w,_ as V,aa as j,ba as T,ca as Z}from"./chunk-IBZ4MVH2.js";import{D as E,Ja as R,La as S,Ma as F,Oa as l,V as b,db as C,i as g,m as y,na as I,ta as v}from"./chunk-XRSE2VTK.js";var _={schedule(n,t){let e=setTimeout(n,t);return()=>clearTimeout(e)}};function O(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function k(n){return!!n&&n.nodeType===Node.ELEMENT_NODE}var h;function N(n,t){if(!h){let e=Element.prototype;h=e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector}return n.nodeType===Node.ELEMENT_NODE?h.call(n,t):!1}function z(n){let t={};return n.forEach(({propName:e,templateName:s,transform:u})=>{t[O(s)]=[e,u]}),t}function A(n,t){return t.get(l).resolveComponentFactory(n).inputs}function P(n,t){let e=n.childNodes,s=t.map(()=>[]),u=-1;t.some((r,o)=>r==="*"?(u=o,!0):!1);for(let r=0,o=e.length;r<o;++r){let i=e[r],c=L(i,t,u);c!==-1&&s[c].push(i)}return s}function L(n,t,e){let s=e;return k(n)&&t.some((u,r)=>u!=="*"&&N(n,u)?(s=r,!0):!1),s}var Y=10,p=class{componentFactory;inputMap=new Map;constructor(t,e){this.componentFactory=e.get(l).resolveComponentFactory(t);for(let s of this.componentFactory.inputs)this.inputMap.set(s.propName,s.templateName)}create(t){return new m(this.componentFactory,t,this.inputMap)}},m=class{componentFactory;injector;inputMap;eventEmitters=new y(1);events=this.eventEmitters.pipe(b(t=>E(...t)));componentRef=null;scheduledDestroyFn=null;initialInputValues=new Map;ngZone;elementZone;appRef;cdScheduler;constructor(t,e,s){this.componentFactory=t,this.injector=e,this.inputMap=s,this.ngZone=this.injector.get(R),this.appRef=this.injector.get(C),this.cdScheduler=e.get(v),this.elementZone=typeof Zone>"u"?null:this.ngZone.run(()=>Zone.current)}connect(t){this.runInZone(()=>{if(this.scheduledDestroyFn!==null){this.scheduledDestroyFn(),this.scheduledDestroyFn=null;return}this.componentRef===null&&this.initializeComponent(t)})}disconnect(){this.runInZone(()=>{this.componentRef===null||this.scheduledDestroyFn!==null||(this.scheduledDestroyFn=_.schedule(()=>{this.componentRef!==null&&(this.componentRef.destroy(),this.componentRef=null)},Y))})}getInputValue(t){return this.runInZone(()=>this.componentRef===null?this.initialInputValues.get(t):this.componentRef.instance[t])}setInputValue(t,e){if(this.componentRef===null){this.initialInputValues.set(t,e);return}this.runInZone(()=>{this.componentRef.setInput(this.inputMap.get(t)??t,e),S(this.componentRef.hostView)&&(F(this.componentRef.changeDetectorRef),this.cdScheduler.notify(6))})}initializeComponent(t){let e=I.create({providers:[],parent:this.injector}),s=P(t,this.componentFactory.ngContentSelectors);this.componentRef=this.componentFactory.create(e,s,t),this.initializeInputs(),this.initializeOutputs(this.componentRef),this.appRef.attachView(this.componentRef.hostView),this.componentRef.hostView.detectChanges()}initializeInputs(){for(let[t,e]of this.initialInputValues)this.setInputValue(t,e);this.initialInputValues.clear()}initializeOutputs(t){let e=this.componentFactory.outputs.map(({propName:s,templateName:u})=>{let r=t.instance[s];return new g(o=>{let i=r.subscribe(c=>o.next({name:u,value:c}));return()=>i.unsubscribe()})});this.eventEmitters.next(e)}runInZone(t){return this.elementZone&&Zone.current!==this.elementZone?this.ngZone.run(t):t()}},f=class extends HTMLElement{ngElementEventsSubscription=null};function D(n,t){let e=A(n,t.injector),s=t.strategyFactory||new p(n,t.injector),u=z(e);class r extends f{injector;static observedAttributes=Object.keys(u);get ngElementStrategy(){if(!this._ngElementStrategy){let i=this._ngElementStrategy=s.create(this.injector||t.injector);e.forEach(({propName:c,transform:a})=>{if(!this.hasOwnProperty(c))return;let d=this[c];delete this[c],i.setInputValue(c,d,a)})}return this._ngElementStrategy}_ngElementStrategy;constructor(i){super(),this.injector=i}attributeChangedCallback(i,c,a,d){let[M,x]=u[i];this.ngElementStrategy.setInputValue(M,a,x)}connectedCallback(){let i=!1;this.ngElementStrategy.events&&(this.subscribeToEvents(),i=!0),this.ngElementStrategy.connect(this),i||this.subscribeToEvents()}disconnectedCallback(){this._ngElementStrategy&&this._ngElementStrategy.disconnect(),this.ngElementEventsSubscription&&(this.ngElementEventsSubscription.unsubscribe(),this.ngElementEventsSubscription=null)}subscribeToEvents(){this.ngElementEventsSubscription=this.ngElementStrategy.events.subscribe(i=>{let c=new CustomEvent(i.name,{detail:i.value});this.dispatchEvent(c)})}}return e.forEach(({propName:o,transform:i})=>{Object.defineProperty(r.prototype,o,{get(){return this.ngElementStrategy.getInputValue(o)},set(c){this.ngElementStrategy.setInputValue(o,c,i)},configurable:!0,enumerable:!0})}),r}function K(n,t){let e=D(n,{injector:t});class s extends e{connectedCallback(){let r;try{let o=this;Z(o),r=V(o)}catch{}super.connectedCallback?.();try{if(w(r),r){let o=this;setTimeout(()=>{j(o),T(o)},0)}}catch{}}}return s}export{K as a};
1
+ import{$ as w,_ as V,aa as j,ba as T,ca as Z}from"./chunk-WAIRKNL2.js";import{D as E,Ja as R,La as S,Ma as F,Oa as l,V as b,db as C,i as g,m as y,na as I,ta as v}from"./chunk-7CAYUDV6.js";var _={schedule(n,t){let e=setTimeout(n,t);return()=>clearTimeout(e)}};function O(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function k(n){return!!n&&n.nodeType===Node.ELEMENT_NODE}var h;function N(n,t){if(!h){let e=Element.prototype;h=e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector}return n.nodeType===Node.ELEMENT_NODE?h.call(n,t):!1}function z(n){let t={};return n.forEach(({propName:e,templateName:s,transform:u})=>{t[O(s)]=[e,u]}),t}function A(n,t){return t.get(l).resolveComponentFactory(n).inputs}function P(n,t){let e=n.childNodes,s=t.map(()=>[]),u=-1;t.some((r,o)=>r==="*"?(u=o,!0):!1);for(let r=0,o=e.length;r<o;++r){let i=e[r],c=L(i,t,u);c!==-1&&s[c].push(i)}return s}function L(n,t,e){let s=e;return k(n)&&t.some((u,r)=>u!=="*"&&N(n,u)?(s=r,!0):!1),s}var Y=10,p=class{componentFactory;inputMap=new Map;constructor(t,e){this.componentFactory=e.get(l).resolveComponentFactory(t);for(let s of this.componentFactory.inputs)this.inputMap.set(s.propName,s.templateName)}create(t){return new m(this.componentFactory,t,this.inputMap)}},m=class{componentFactory;injector;inputMap;eventEmitters=new y(1);events=this.eventEmitters.pipe(b(t=>E(...t)));componentRef=null;scheduledDestroyFn=null;initialInputValues=new Map;ngZone;elementZone;appRef;cdScheduler;constructor(t,e,s){this.componentFactory=t,this.injector=e,this.inputMap=s,this.ngZone=this.injector.get(R),this.appRef=this.injector.get(C),this.cdScheduler=e.get(v),this.elementZone=typeof Zone>"u"?null:this.ngZone.run(()=>Zone.current)}connect(t){this.runInZone(()=>{if(this.scheduledDestroyFn!==null){this.scheduledDestroyFn(),this.scheduledDestroyFn=null;return}this.componentRef===null&&this.initializeComponent(t)})}disconnect(){this.runInZone(()=>{this.componentRef===null||this.scheduledDestroyFn!==null||(this.scheduledDestroyFn=_.schedule(()=>{this.componentRef!==null&&(this.componentRef.destroy(),this.componentRef=null)},Y))})}getInputValue(t){return this.runInZone(()=>this.componentRef===null?this.initialInputValues.get(t):this.componentRef.instance[t])}setInputValue(t,e){if(this.componentRef===null){this.initialInputValues.set(t,e);return}this.runInZone(()=>{this.componentRef.setInput(this.inputMap.get(t)??t,e),S(this.componentRef.hostView)&&(F(this.componentRef.changeDetectorRef),this.cdScheduler.notify(6))})}initializeComponent(t){let e=I.create({providers:[],parent:this.injector}),s=P(t,this.componentFactory.ngContentSelectors);this.componentRef=this.componentFactory.create(e,s,t),this.initializeInputs(),this.initializeOutputs(this.componentRef),this.appRef.attachView(this.componentRef.hostView),this.componentRef.hostView.detectChanges()}initializeInputs(){for(let[t,e]of this.initialInputValues)this.setInputValue(t,e);this.initialInputValues.clear()}initializeOutputs(t){let e=this.componentFactory.outputs.map(({propName:s,templateName:u})=>{let r=t.instance[s];return new g(o=>{let i=r.subscribe(c=>o.next({name:u,value:c}));return()=>i.unsubscribe()})});this.eventEmitters.next(e)}runInZone(t){return this.elementZone&&Zone.current!==this.elementZone?this.ngZone.run(t):t()}},f=class extends HTMLElement{ngElementEventsSubscription=null};function D(n,t){let e=A(n,t.injector),s=t.strategyFactory||new p(n,t.injector),u=z(e);class r extends f{injector;static observedAttributes=Object.keys(u);get ngElementStrategy(){if(!this._ngElementStrategy){let i=this._ngElementStrategy=s.create(this.injector||t.injector);e.forEach(({propName:c,transform:a})=>{if(!this.hasOwnProperty(c))return;let d=this[c];delete this[c],i.setInputValue(c,d,a)})}return this._ngElementStrategy}_ngElementStrategy;constructor(i){super(),this.injector=i}attributeChangedCallback(i,c,a,d){let[M,x]=u[i];this.ngElementStrategy.setInputValue(M,a,x)}connectedCallback(){let i=!1;this.ngElementStrategy.events&&(this.subscribeToEvents(),i=!0),this.ngElementStrategy.connect(this),i||this.subscribeToEvents()}disconnectedCallback(){this._ngElementStrategy&&this._ngElementStrategy.disconnect(),this.ngElementEventsSubscription&&(this.ngElementEventsSubscription.unsubscribe(),this.ngElementEventsSubscription=null)}subscribeToEvents(){this.ngElementEventsSubscription=this.ngElementStrategy.events.subscribe(i=>{let c=new CustomEvent(i.name,{detail:i.value});this.dispatchEvent(c)})}}return e.forEach(({propName:o,transform:i})=>{Object.defineProperty(r.prototype,o,{get(){return this.ngElementStrategy.getInputValue(o)},set(c){this.ngElementStrategy.setInputValue(o,c,i)},configurable:!0,enumerable:!0})}),r}function K(n,t){let e=D(n,{injector:t});class s extends e{connectedCallback(){let r;try{let o=this;Z(o),r=V(o)}catch{}super.connectedCallback?.();try{if(w(r),r){let o=this;setTimeout(()=>{j(o),T(o)},0)}}catch{}}}return s}export{K as a};
@@ -1,2 +1,2 @@
1
- import{b as L}from"./chunk-HBFQOXCU.js";import{Ha as z,Ja as B}from"./chunk-IBZ4MVH2.js";import{Bb as c,Ha as r,Ia as S,Ic as N,Mb as T,Pb as f,Qb as D,Ra as s,Sb as h,Wa as I,_a as O,a as y,ab as m,b as u,ja as w,ka as _,mc as v,nb as p,nc as g,ob as a,pb as d,qj as j,sa as C,ub as E,vb as k,xb as F,ya as b,zb as x,zk as V}from"./chunk-XRSE2VTK.js";function A(t,i){if(t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2){let o=c(2).ngIf;r(),h("",g(2,2,"You are following")," ",o.leaderName)}}function P(t,i){t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2&&(r(),D(g(2,1,"You are leading.")))}function R(t,i){if(t&1){let o=F();a(0,"div",2),x("click",function(){w(o);let e=c().ngIf,l=c();return _(e.type==="following"?l.closeOverlay():void 0)}),a(1,"div",3),m(2,A,3,4,"span",4)(3,P,3,3,"span",4),a(4,"button",5),x("click",function(){w(o);let e=c(2);return _(e.closeOverlay())}),f(5),v(6,"translate"),v(7,"translate"),d()()()}if(t&2){let o=c().ngIf;T("no-pointer",o.type==="leading"),r(2),p("ngIf",o.type==="following"),r(),p("ngIf",o.type==="leading"),r(2),h("",g(6,6,"Stop")," ",g(7,8,o.type))}}function Y(t,i){if(t&1&&(E(0),m(1,R,8,10,"div",1),k()),t&2){let o=i.ngIf;r(),p("ngIf",o.leaderName!==""||o.type==="leading")}}var te=(()=>{let i=class i extends B{closeOverlay(){this.closeOverlayEvent.emit()}constructor(n,e,l,M){super(e,l),this.loggingService=n,this.elementRef=e,this.themeService=l,this.domService=M,this.closeOverlayEvent=new S,this.componentConfigSignal=C({leaderName:"",type:"following"})}ngOnInit(){}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngAfterViewInit: ",n)}}setLeaderName(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{leaderName:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",e)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{type:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setType: ",e)}}ngOnDestroy(){try{super.ngOnDestroy(),this.customCssSubscription?.unsubscribe()}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngOnDestroy: ",n)}}};i.\u0275fac=function(e){return new(e||i)(s(j),s(b),s(z),s(V))},i.\u0275cmp=I({type:i,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[O],decls:1,vars:1,consts:[[4,"ngIf"],["data-velt-ignore","","class","follow-overlay-container",3,"no-pointer","click",4,"ngIf"],["data-velt-ignore","",1,"follow-overlay-container",3,"click"],["data-velt-ignore","",1,"follow-dialog"],["data-velt-ignore","","class","follow-text",4,"ngIf"],["data-velt-ignore","",1,"follow-btn",3,"click"],["data-velt-ignore","",1,"follow-text"]],template:function(e,l){e&1&&m(0,Y,2,1,"ng-container",0),e&2&&p("ngIf",l.componentConfigSignal())},dependencies:[N,L],styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}.follow-overlay-container{position:fixed;top:0;left:0;width:100%;height:100%;background-color:transparent;z-index:var(--velt-follow-mode-overlay-z-index);display:flex;justify-content:center;align-items:flex-end}.follow-overlay-container .follow-dialog{background-color:var(--legacy-velt-follow-overlay-bg-color);color:var(--legacy-velt-follow-overlay-text-color);font-size:12px;display:flex;justify-content:center;align-items:center;gap:calc((1.2rem + 0px) * var(--velt-base-rem-unit));padding:calc((.9rem + 0px) * var(--velt-base-rem-unit)) calc((1.1rem + 0px) * var(--velt-base-rem-unit));border-radius:90px;margin-bottom:calc((2rem + 0px) * var(--velt-base-rem-unit));box-shadow:0 8px 16px -8px #0f0f0f1a;border:1px solid var(--legacy-velt-follow-overlay-border-color)}.follow-overlay-container .follow-dialog .follow-btn{background-color:var(--legacy-velt-follow-overlay-btn-color);padding:8px 12px;border-radius:90px;display:inline-flex;justify-content:center;align-items:center;border:none;font-weight:600;font-size:14px;cursor:pointer;pointer-events:all}.follow-overlay-container .follow-dialog .follow-btn:hover{transition:background-color .5s;background-color:var(--legacy-velt-follow-overlay-btn-hover-color)}.follow-overlay-container.no-pointer{pointer-events:none}
1
+ import{b as L}from"./chunk-5OVPOQXM.js";import{Ha as z,Ja as B}from"./chunk-WAIRKNL2.js";import{Bb as c,Ha as r,Ia as S,Ic as N,Mb as T,Pb as f,Qb as D,Ra as s,Sb as h,Wa as I,_a as O,a as y,ab as m,b as u,ja as w,ka as _,mc as v,nb as p,nc as g,ob as a,pb as d,qj as j,sa as C,ub as E,vb as k,xb as F,ya as b,zb as x,zk as V}from"./chunk-7CAYUDV6.js";function A(t,i){if(t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2){let o=c(2).ngIf;r(),h("",g(2,2,"You are following")," ",o.leaderName)}}function P(t,i){t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2&&(r(),D(g(2,1,"You are leading.")))}function R(t,i){if(t&1){let o=F();a(0,"div",2),x("click",function(){w(o);let e=c().ngIf,l=c();return _(e.type==="following"?l.closeOverlay():void 0)}),a(1,"div",3),m(2,A,3,4,"span",4)(3,P,3,3,"span",4),a(4,"button",5),x("click",function(){w(o);let e=c(2);return _(e.closeOverlay())}),f(5),v(6,"translate"),v(7,"translate"),d()()()}if(t&2){let o=c().ngIf;T("no-pointer",o.type==="leading"),r(2),p("ngIf",o.type==="following"),r(),p("ngIf",o.type==="leading"),r(2),h("",g(6,6,"Stop")," ",g(7,8,o.type))}}function Y(t,i){if(t&1&&(E(0),m(1,R,8,10,"div",1),k()),t&2){let o=i.ngIf;r(),p("ngIf",o.leaderName!==""||o.type==="leading")}}var te=(()=>{let i=class i extends B{closeOverlay(){this.closeOverlayEvent.emit()}constructor(n,e,l,M){super(e,l),this.loggingService=n,this.elementRef=e,this.themeService=l,this.domService=M,this.closeOverlayEvent=new S,this.componentConfigSignal=C({leaderName:"",type:"following"})}ngOnInit(){}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngAfterViewInit: ",n)}}setLeaderName(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{leaderName:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",e)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{type:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setType: ",e)}}ngOnDestroy(){try{super.ngOnDestroy(),this.customCssSubscription?.unsubscribe()}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngOnDestroy: ",n)}}};i.\u0275fac=function(e){return new(e||i)(s(j),s(b),s(z),s(V))},i.\u0275cmp=I({type:i,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[O],decls:1,vars:1,consts:[[4,"ngIf"],["data-velt-ignore","","class","follow-overlay-container",3,"no-pointer","click",4,"ngIf"],["data-velt-ignore","",1,"follow-overlay-container",3,"click"],["data-velt-ignore","",1,"follow-dialog"],["data-velt-ignore","","class","follow-text",4,"ngIf"],["data-velt-ignore","",1,"follow-btn",3,"click"],["data-velt-ignore","",1,"follow-text"]],template:function(e,l){e&1&&m(0,Y,2,1,"ng-container",0),e&2&&p("ngIf",l.componentConfigSignal())},dependencies:[N,L],styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}.follow-overlay-container{position:fixed;top:0;left:0;width:100%;height:100%;background-color:transparent;z-index:var(--velt-follow-mode-overlay-z-index);display:flex;justify-content:center;align-items:flex-end}.follow-overlay-container .follow-dialog{background-color:var(--legacy-velt-follow-overlay-bg-color);color:var(--legacy-velt-follow-overlay-text-color);font-size:12px;display:flex;justify-content:center;align-items:center;gap:calc((1.2rem + 0px) * var(--velt-base-rem-unit));padding:calc((.9rem + 0px) * var(--velt-base-rem-unit)) calc((1.1rem + 0px) * var(--velt-base-rem-unit));border-radius:90px;margin-bottom:calc((2rem + 0px) * var(--velt-base-rem-unit));box-shadow:0 8px 16px -8px #0f0f0f1a;border:1px solid var(--legacy-velt-follow-overlay-border-color)}.follow-overlay-container .follow-dialog .follow-btn{background-color:var(--legacy-velt-follow-overlay-btn-color);padding:8px 12px;border-radius:90px;display:inline-flex;justify-content:center;align-items:center;border:none;font-weight:600;font-size:14px;cursor:pointer;pointer-events:all}.follow-overlay-container .follow-dialog .follow-btn:hover{transition:background-color .5s;background-color:var(--legacy-velt-follow-overlay-btn-hover-color)}.follow-overlay-container.no-pointer{pointer-events:none}
2
2
  `],encapsulation:3,changeDetection:0});let t=i;return t})();export{te as a};
@@ -0,0 +1,2 @@
1
+ import{f as P,j as ae}from"./chunk-WAIRKNL2.js";import{D as de}from"./chunk-W3PIDHPP.js";import{He as b,Kg as M,M as R,V as Z,Xa as ne,Xe as ge,Ya as se,Ze as ue,_i as U,a as E,aa as ee,ac as oe,b as I,ba as C,c as J,ca as te,de as p,di as z,ea as v,g as Y,i as T,k as L,l as Q,oj as he,qd as ce,qj as x,r as $,sa as re,ui as le,v as k,wa as ie,xg as A}from"./chunk-7CAYUDV6.js";var H=class{_totalWeight=0;_averageItemSize;_defaultItemSize;constructor(n=50){this._defaultItemSize=n,this._averageItemSize=n}getAverageItemSize(){return this._averageItemSize}addSample(n,o){let e=this._totalWeight+n.end-n.start;if(e){let t=(o+this._averageItemSize*this._totalWeight)/e;t&&(this._averageItemSize=t,this._totalWeight=e)}}reset(){this._averageItemSize=this._defaultItemSize,this._totalWeight=0}},V=class{scrolledIndexChange=new T(()=>{});_viewport=null;_minBufferPx;_maxBufferPx;_averager;_lastScrollOffset;_lastRenderedContentSize;_lastRenderedContentOffset;_removalFailures=0;constructor(n,o,e=new H){this._minBufferPx=n,this._maxBufferPx=o,this._averager=e}attach(n){this._averager.reset(),this._viewport=n,this._renderContentForCurrentOffset()}detach(){this._viewport=null}onContentScrolled(){this._viewport&&this._updateRenderedContentAfterScroll()}onDataLengthChanged(){this._viewport&&(this._renderContentForCurrentOffset(),this._checkRenderedContentSize())}onContentRendered(){this._viewport&&this._checkRenderedContentSize()}onRenderedOffsetChanged(){this._viewport&&this._checkRenderedContentOffset()}scrollToIndex(){}updateBufferSize(n,o){if(o<n)throw Error("CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx");this._minBufferPx=n,this._maxBufferPx=o}_updateRenderedContentAfterScroll(){let n=this._viewport,o=n.measureScrollOffset(),e=o-this._lastScrollOffset,t=Math.abs(e),r=n.getRenderedRange(),i=0;if(e<0){let h=r.start*this._averager.getAverageItemSize()-this._lastRenderedContentOffset;i=Math.round(h*Math.max(0,Math.min(1,t/(o+t)))),e=e-i,t=Math.abs(e)}let a=this._lastScrollOffset-this._lastRenderedContentOffset,c=this._lastRenderedContentOffset+this._lastRenderedContentSize-(this._lastScrollOffset+n.getViewportSize()),g=t+this._minBufferPx-(e<0?a:c);if(g>0)if(t>=n.getViewportSize())this._renderContentForCurrentOffset();else{let u=Math.max(0,Math.ceil((g-this._minBufferPx+this._maxBufferPx)/this._averager.getAverageItemSize())),h=(e<0?c:a)-this._minBufferPx+t,d=Math.floor(h/this._averager.getAverageItemSize()/(this._removalFailures+1)),f=Math.min(r.end-r.start,Math.max(0,d)),l=this._expandRange(r,e<0?u:0,e>0?u:0);e<0?l.end=Math.max(l.start+1,l.end-f):l.start=Math.min(l.end-1,l.start+f);let S,D;if(e<0){let O=n.measureRangeSize({start:l.end,end:r.end});O<=h?(S=this._lastRenderedContentOffset+this._lastRenderedContentSize-O,this._removalFailures=0):(l.end=r.end,S=this._lastRenderedContentOffset+this._lastRenderedContentSize,this._removalFailures++),D="to-end"}else{let O=n.measureRangeSize({start:r.start,end:l.start});O<=h?(S=this._lastRenderedContentOffset+O,this._removalFailures=0):(l.start=r.start,S=this._lastRenderedContentOffset,this._removalFailures++),D="to-start"}n.setRenderedRange(l),n.setRenderedContentOffset(S+i,D)}else i&&n.setRenderedContentOffset(this._lastRenderedContentOffset+i);this._lastScrollOffset=o}_checkRenderedContentSize(){let n=this._viewport;this._lastRenderedContentSize=n.measureRenderedContentSize(),this._averager.addSample(n.getRenderedRange(),this._lastRenderedContentSize),this._updateTotalContentSize(this._lastRenderedContentSize)}_checkRenderedContentOffset(){let n=this._viewport;this._lastRenderedContentOffset=n.getOffsetToRenderedContentStart()}_renderContentForCurrentOffset(){let n=this._viewport,o=n.measureScrollOffset();this._lastScrollOffset=o,this._removalFailures=0;let e=this._averager.getAverageItemSize(),t=Math.min(n.getDataLength()-1,Math.floor(o/e)),r=Math.ceil(this._maxBufferPx/e),i=this._expandRange(this._getVisibleRangeForIndex(t),r,r);n.setRenderedRange(i),n.setRenderedContentOffset(e*i.start)}_getVisibleRangeForIndex(n){let o=this._viewport,e={start:n,end:n+Math.ceil(o.getViewportSize()/this._averager.getAverageItemSize())},t=e.end-o.getDataLength();return t>0&&(e.start=Math.max(0,e.start-t)),e}_expandRange(n,o,e){let t=this._viewport,r=Math.max(0,n.start-o),i=Math.min(t.getDataLength(),n.end+e);return{start:r,end:i}}_updateTotalContentSize(n){let o=this._viewport,e=o.getRenderedRange(),t=n+(o.getDataLength()-(e.end-e.start))*this._averager.getAverageItemSize();o.setTotalContentSize(t)}};function Ce(s){return s._scrollStrategy}var Pe=(()=>{class s{get minBufferPx(){return this._minBufferPx}set minBufferPx(o){this._minBufferPx=P(o)}_minBufferPx=100;get maxBufferPx(){return this._maxBufferPx}set maxBufferPx(o){this._maxBufferPx=P(o)}_maxBufferPx=200;_scrollStrategy=new V(this.minBufferPx,this.maxBufferPx);ngOnChanges(){this._scrollStrategy.updateBufferSize(this.minBufferPx,this.maxBufferPx)}static \u0275fac=function(e){return new(e||s)};static \u0275dir=se({type:s,selectors:[["cdk-virtual-scroll-viewport","autosize",""]],inputs:{minBufferPx:"minBufferPx",maxBufferPx:"maxBufferPx"},features:[oe([{provide:ae,useFactory:Ce,deps:[ee(()=>s)]}]),ie]})}return s})(),ze=(()=>{class s{static \u0275fac=function(e){return new(e||s)};static \u0275mod=ne({type:s});static \u0275inj=te({})}return s})();var Ae=["removed","added","contextBefore","contextAfter","occurrence"];function q(s){if(s==null)return{value:null,reason:null,droppedKeys:[]};let n=typeof s=="object"?Object.getPrototypeOf(s):void 0;if(n!==Object.prototype&&n!==null)return{value:null,reason:"it is not a plain object",droppedKeys:[]};let o=s;for(let i of["removed","added","contextBefore","contextAfter"])if(typeof o[i]!="string")return{value:null,reason:`"${i}" must be a string`,droppedKeys:[]};let e=o.occurrence;if(typeof e!="number"||!Number.isInteger(e)||e<1)return{value:null,reason:'"occurrence" must be an integer of 1 or more',droppedKeys:[]};let t={removed:o.removed,added:o.added,contextBefore:o.contextBefore,contextAfter:o.contextAfter,occurrence:e};if(t.removed.length+t.added.length>8192)return{value:null,reason:'"removed" and "added" together are longer than 8192 characters',droppedKeys:[]};let r=Object.keys(o).filter(i=>!Ae.includes(i));return{value:t,reason:null,droppedKeys:r}}function xe(s,n,o){if(!n)return 0;let e=0,t=0;for(;;){let r=s.indexOf(n,t);if(r<0||r>=o)return e;e++,t=r+1}}var _e=s=>s>=55296&&s<=56319,Re=s=>s>=56320&&s<=57343,w=(s,n)=>n>0&&n<s.length&&_e(s.charCodeAt(n-1))&&Re(s.charCodeAt(n)),we=/[\p{L}\p{N}_]/u,_=s=>!!s&&we.test(s),m=s=>s.replace(/\u00a0/g," ");function fe(s,n){let o=m(s),e=m(n),t=Math.min(o.length,e.length),r=0;for(;r<t&&o.charCodeAt(r)===e.charCodeAt(r);)r++;let i=0;for(;i<t-r&&o.charCodeAt(o.length-1-i)===e.charCodeAt(e.length-1-i);)i++;let a=o.length-r-i,c=e.length-r-i;if(a>0&&c>0){for(;r>0&&_(o[r-1])&&(_(o[r])||_(e[r]));)r--;for(;i<t-r&&o.charCodeAt(o.length-1-i)===e.charCodeAt(e.length-1-i);)i++;for(;i>0&&_(o[o.length-i])&&(_(o[o.length-i-1])||_(e[e.length-i-1]));)i--}else if(a+c>0){let g=a>0?o:e,u=a+c,h=f=>_(g[f])&&!_(g[f-1]),d=r;for(let f=r;f>0&&g[f-1]===g[f+u-1];)f--,h(f)&&(d=f);!h(r)&&d!==r&&(i+=r-d,r=d)}for(;r>0&&(w(o,r)||w(e,r));)r--;for(;i>0&&(w(o,o.length-i)||w(e,e.length-i));)i--;return{prefix:r,suffix:i}}function G(s,n,o,e){if(n<0||o<n||o>s.length)return null;let t=s.slice(n,o);if(m(t)===m(e)||t.length+e.length>8192)return null;let r=Math.max(0,n-32);w(s,r)&&r++;let i=Math.min(s.length,o+32);w(s,i)&&i--;let a=s.slice(r,n),c=s.slice(o,i),g=a+t+c,u=1+xe(s,g,r);return{removed:t,added:e,contextBefore:a,contextAfter:c,occurrence:u}}function Se(s,n,o){return m(n).includes(m(s.contextBefore+s.removed+s.contextAfter))&&m(o).includes(m(s.contextBefore+s.added+s.contextAfter))}function N(s){return{removed:m(s.removed),added:m(s.added),contextBefore:m(s.contextBefore),contextAfter:m(s.contextAfter),occurrence:s.occurrence}}function me(s,n){if(m(s)===m(n))return null;let{prefix:o,suffix:e}=fe(s,n);return G(s,o,s.length-e,n.slice(o,n.length-e))}function He(s,n){if(m(s)===m(n))return null;let{prefix:o,suffix:e}=fe(s,n);return{removed:s.slice(o,s.length-e),start:o,end:n.length-e}}var j=(()=>{let n=class n{constructor(e){this.loggingService=e,this.enabledSignal=re(!1),this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0;try{this.enabled$=ce(this.enabledSignal).pipe(R())}catch(t){this.loggingService.catch("Error in SuggestionModeService constructor: ",t),this.enabled$=new T}}enable(e){try{this.onTargetEditStart=e?.onTargetEditStart??null,this.onTargetEditCommit=e?.onTargetEditCommit??null,this.autoCommit=e?.autoCommit!==!1,this.enabledSignal.set(!0)}catch(t){this.loggingService.catch("Error in SuggestionModeService enable: ",t)}}disable(){try{this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0,this.enabledSignal.set(!1)}catch(e){this.loggingService.catch("Error in SuggestionModeService disable: ",e)}}isEnabled(){try{return this.enabledSignal()}catch(e){return this.loggingService.catch("Error in SuggestionModeService isEnabled: ",e),!1}}getOnTargetEditStart(){try{return this.onTargetEditStart}catch(e){return this.loggingService.catch("Error in SuggestionModeService getOnTargetEditStart: ",e),null}}getOnTargetEditCommit(){try{return this.onTargetEditCommit}catch(e){return this.loggingService.catch("Error in SuggestionModeService getOnTargetEditCommit: ",e),null}}isAutoCommitEnabled(){try{return this.autoCommit}catch(e){return this.loggingService.catch("Error in SuggestionModeService isAutoCommitEnabled: ",e),!1}}};n.\u0275fac=function(t){return new(t||n)(v(x))},n.\u0275prov=C({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var B=(()=>{let n=class n{constructor(e){this.loggingService=e,this.snapshots=new Map}captureFromGetter(e,t){try{if(!e||typeof t!="function")return!1;let r;try{r=t()}catch(i){return A()&&this.loggingService.catch(`[velt] Suggestion target "${e}" getter threw: `,i),!1}return this.captureValue(e,r)}catch(r){return this.loggingService.catch("Error in SuggestionSnapshotService captureFromGetter: ",r),!1}}captureValue(e,t){try{if(!e)return!1;let r;try{r=structuredClone(t)}catch(i){return A()&&this.loggingService.catch(`[velt] Suggestion target "${e}" snapshot failed (value not cloneable). Cause: structuredClone rejected the value (cyclic refs, DOM nodes, or functions are common culprits). Fix: ensure your getter returns plain JSON-serializable data.`,i),!1}return this.snapshots.set(e,r),!0}catch(r){return this.loggingService.catch("Error in SuggestionSnapshotService captureValue: ",r),!1}}getSnapshot(e){try{return this.snapshots.has(e)?this.snapshots.get(e):void 0}catch(t){this.loggingService.catch("Error in SuggestionSnapshotService getSnapshot: ",t);return}}hasSnapshot(e){try{return this.snapshots.has(e)}catch(t){return this.loggingService.catch("Error in SuggestionSnapshotService hasSnapshot: ",t),!1}}clearSnapshot(e){try{this.snapshots.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionSnapshotService clearSnapshot: ",t)}}clearAllSnapshots(){try{this.snapshots.clear()}catch(e){this.loggingService.catch("Error in SuggestionSnapshotService clearAllSnapshots: ",e)}}};n.\u0275fac=function(t){return new(t||n)(v(x))},n.\u0275prov=C({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var ye=(()=>{let n=class n{constructor(e,t,r){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.registry=new Map,this.warnedUnstableIds=new Set,this.latestEdit=new Map,this.editSeq=0,this.actionsService=null,this.typedEditSource=null}registerTarget(e,t,r){try{if(!e||typeof t!="function")return;this.warnIfUnstableId(e);let i=this.registry.get(e)??{};i.getter=t,i.setter=typeof r?.setter=="function"?r.setter:void 0,i.restoreOnCommit=r?.restoreOnCommit,this.registry.set(e,i)}catch(i){this.loggingService.catch("Error in SuggestionTargetRegistryService registerTarget: ",i)}}unregisterTarget(e){try{let t=this.registry.get(e);if(!t)return;delete t.getter,delete t.setter,delete t.restoreOnCommit,this.latestEdit.delete(e),t.node||this.registry.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService unregisterTarget: ",t)}}getSetter(e){try{return this.registry.get(e)?.setter}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getSetter: ",t);return}}callSetter(e,t,r){return this.runSetter(e,t,r)!==null}runSetter(e,t,r){let i=this.registry.get(e)?.setter;if(!i)return null;let a=c=>this.loggingService.catch("Error in SuggestionTargetRegistryService: the target setter threw",c,{targetId:e,reason:r.reason});try{let c=i(t,E({targetId:e},r));if(c&&typeof c.then=="function")return Promise.resolve(c).catch(a)}catch(c){a(c)}return Promise.resolve()}getGetter(e){try{return this.registry.get(e)?.getter}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getGetter: ",t);return}}setActionsService(e){try{this.actionsService=e}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService setActionsService: ",t)}}getNode(e){try{if(!e)return;let t=this.registry.get(e)?.node;if(t&&t.isConnected)return t;let r=this.queryAll(e);if(r.length===0)return;r.length>1&&this.warnDuplicateId(e,r.length);let i=r[0],a=this.registry.get(e)??{};return a.node=i,this.registry.set(e,a),i}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getNode: ",t);return}}setTypedEditSource(e){this.typedEditSource=e}getTypedEdits(e){try{return this.typedEditSource?.(e)??[]}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService getTypedEdits: ",t),[]}}getFallbackValue(e){try{let t=this.getNode(e);if(!t)return{hasValue:!1};let r=t.textContent??"";return r.length>0?{hasValue:!0,value:r}:{hasValue:!1}}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService getFallbackValue: ",t),{hasValue:!1}}}isRegistered(e){try{return this.registry.get(e)?.getter?!0:!!this.getNode(e)}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService isRegistered: ",t),!1}}countTaggedElements(e){try{let t=e??this.rootEl??document.body;return t?t.querySelectorAll(`[${b.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).length:0}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService countTaggedElements: ",t),0}}startObserving(e=document.body){try{if(this.observer)return;this.rootEl=e,this.scanAndRefresh(e),this.observer=new MutationObserver(()=>{try{this.scanAndRefresh(this.rootEl??document.body)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService observer callback: ",t)}}),this.observer.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[b.ATTRIBUTES.VELT_SUGGESTION_TARGET]}),this.installDelegatedListeners(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService startObserving: ",t)}}stopObserving(){try{this.observer?.disconnect(),this.observer=void 0,this.rootEl&&this.removeDelegatedListeners(this.rootEl),this.rootEl=void 0}catch(e){this.loggingService.catch("Error in SuggestionTargetRegistryService stopObserving: ",e)}}clear(){try{this.registry.clear(),this.latestEdit.clear(),this.warnedUnstableIds.clear()}catch(e){this.loggingService.catch("Error in SuggestionTargetRegistryService clear: ",e)}}installDelegatedListeners(e){try{this.boundFocusIn=t=>this.handleFocusIn(t),this.boundChange=t=>this.handleChange(t),this.boundFocusOut=t=>this.handleFocusOut(t),e.addEventListener("focusin",this.boundFocusIn,!0),e.addEventListener("change",this.boundChange,!0),e.addEventListener("focusout",this.boundFocusOut,!0)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService installDelegatedListeners: ",t)}}removeDelegatedListeners(e){try{this.boundFocusIn&&e.removeEventListener("focusin",this.boundFocusIn,!0),this.boundChange&&e.removeEventListener("change",this.boundChange,!0),this.boundFocusOut&&e.removeEventListener("focusout",this.boundFocusOut,!0),this.boundFocusIn=void 0,this.boundChange=void 0,this.boundFocusOut=void 0}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService removeDelegatedListeners: ",t)}}handleFocusIn(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t)return;this.captureSnapshotForTarget(t.targetId,t.element);let r=this.snapshotService.getSnapshot(t.targetId),i={targetId:t.targetId,oldValue:r,newValue:r,element:t.element},a=this.modeService.getOnTargetEditStart();if(a)try{a(i)}catch(c){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditStart customer callback threw: ",c)}this.actionsService?.triggerAction(p.TARGET_EDIT_START,{details:i,timestamp:Date.now()})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleFocusIn: ",t)}}handleChange(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t||!this.isAtomicCommitTarget(e.target))return;this.processCommit(t.targetId,t.element)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleChange: ",t)}}handleFocusOut(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t||this.isAtomicCommitTarget(e.target))return;this.processCommit(t.targetId,t.element)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleFocusOut: ",t)}}isAtomicCommitTarget(e){try{if(e instanceof HTMLSelectElement)return!0;if(e instanceof HTMLInputElement){let t=(e.type||"").toLowerCase();return t==="checkbox"||t==="radio"}return!1}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService isAtomicCommitTarget: ",t),!1}}processCommit(e,t){try{let r=this.snapshotService.getSnapshot(e),i=this.readElementValue(e,t);if(M(r,i))return;let a=this.splitTypedEdits(t,r,i),c=this.restoreWhenCommitted(e,r,a?a.length:1);if(a){a.forEach((g,u)=>this.commitEdit(e,t,r,g.newValue,g.textChange,!0,c?.(u)));return}this.commitEdit(e,t,r,i,void 0,!1,c?.(0))}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService processCommit: ",r)}}restoreWhenCommitted(e,t,r){let i=this.registry.get(e);if(!i?.setter||i.restoreOnCommit===!1){this.latestEdit.delete(e);return}let a=++this.editSeq;this.latestEdit.set(e,a);let c=new Set;return g=>u=>{try{if(!u||c.size===r||(c.add(g),c.size<r||this.latestEdit.get(e)!==a))return;this.latestEdit.delete(e);let h=this.runSetter(e,t,{reason:"restore"}),d=()=>{this.findTaggedAncestor(document.activeElement)?.targetId===e&&this.snapshotService.captureValue(e,t)};d(),h?.then(d,()=>{})}catch(h){this.loggingService.catch("Error in SuggestionTargetRegistryService restoreWhenCommitted: ",h)}}}splitTypedEdits(e,t,r){try{if(typeof t!="string"||typeof r!="string")return null;let i=this.getTypedEdits(e);if(i.length<2)return null;let a=u=>u.replace(/\u00a0/g," ");if(i.some(u=>a(u.base)!==a(t)))return null;let c=t;for(let u of[...i].sort((h,d)=>d.start-h.start))c=c.slice(0,u.start)+u.added+c.slice(u.end);if(a(c)!==a(r))return null;let g=[];for(let u of i){let h=G(t,u.start,u.end,u.added);if(!h)return null;g.push({newValue:t.slice(0,u.start)+a(u.added)+t.slice(u.end),textChange:N(h)})}return g}catch(i){return this.loggingService.catch("Error in SuggestionTargetRegistryService splitTypedEdits: ",i),null}}commitEdit(e,t,r,i,a,c=!1,g){try{let u={targetId:e,oldValue:r,newValue:i,element:t},h=this.modeService.getOnTargetEditCommit(),d=null;if(h){let l=null;try{l=h(u)}catch(S){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditCommit customer callback threw: ",S)}l&&(d=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:l.summary,summaryHtml:l.summaryHtml,metadata:l.metadata,textChange:l.textChange??a}),g&&d.then(g))}else this.modeService.isAutoCommitEnabled()&&(d=this.invokeAutoCommit({targetId:e,newValue:i,textChange:a,snapshot:c?{value:r}:void 0}),g&&d.then(g));let f=l=>Y(this,null,function*(){if(d&&(yield d))return null;let S=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:l?.summary,summaryHtml:l?.summaryHtml,metadata:l?.metadata,textChange:l?.textChange??a});return g&&S.then(g),S});this.actionsService?.triggerAction(p.TARGET_EDIT_COMMIT,{details:u,commitSuggestion:f,timestamp:Date.now()})}catch(u){this.loggingService.catch("Error in SuggestionTargetRegistryService commitEdit: ",u)}}invokeAutoCommit(r){var i=r,{snapshot:e}=i,t=J(i,["snapshot"]);try{return e&&this.snapshotService.captureValue(t.targetId,e.value),this.actionsService?this.actionsService.commitSuggestion(t).catch(a=>(A()&&this.loggingService.catch(`[velt] auto-commit for "${t.targetId}" rejected: `,a),null)):(A()&&this.loggingService.log("[velt] auto-commit skipped: actions service not wired. SuggestionActionsService constructor should call registry.setActionsService(this)."),Promise.resolve(null))}catch(a){return this.loggingService.catch("Error in SuggestionTargetRegistryService invokeAutoCommit: ",a),Promise.resolve(null)}}captureSnapshotForTarget(e,t){try{let r=this.registry.get(e);if(r?.getter){this.snapshotService.captureFromGetter(e,r.getter);return}let i=this.readElementValue(e,t);this.snapshotService.captureValue(e,i)}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService captureSnapshotForTarget: ",r)}}readElementValue(e,t){try{let r=this.registry.get(e);if(r?.getter)try{return r.getter()}catch{return}if(t instanceof HTMLInputElement){let i=(t.type||"").toLowerCase();return i==="checkbox"||i==="radio"?t.checked:i==="number"||i==="range"?Number.isNaN(t.valueAsNumber)?t.value:t.valueAsNumber:t.value}return t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?t.value:(t instanceof HTMLElement&&t.isContentEditable,t.textContent??"")}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService readElementValue: ",r);return}}findTaggedAncestor(e){try{if(!(e instanceof Element))return null;let t=e.closest(`[${b.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`);if(!t)return null;let r=t.getAttribute(b.ATTRIBUTES.VELT_SUGGESTION_TARGET);return r?{element:t,targetId:r}:null}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService findTaggedAncestor: ",t),null}}queryAll(e){try{let t=window.CSS?.escape?window.CSS.escape(e):e.replace(/"/g,'\\"');return Array.from(document.querySelectorAll(`[${b.ATTRIBUTES.VELT_SUGGESTION_TARGET}="${t}"]`))}catch{return[]}}scanAndRefresh(e){try{e.querySelectorAll(`[${b.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).forEach(r=>{let i=r.getAttribute(b.ATTRIBUTES.VELT_SUGGESTION_TARGET);if(!i)return;let a=this.registry.get(i)??{};(!a.node||!a.node.isConnected)&&(a.node=r,this.registry.set(i,a))})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService scanAndRefresh: ",t)}}warnIfUnstableId(e){try{if(!A()||this.warnedUnstableIds.has(e))return;let t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(e),r=/\d{10,}/.test(e);(t||r)&&(this.warnedUnstableIds.add(e),this.loggingService.catch(`[velt] Target id "${e}" appears unstable. Cause: contains a UUID or timestamp shape \u2014 these typically change across re-renders. Fix: use a stable customer-owned id (the same one you use in your state). Docs: velt.dev/docs/suggestions/target-ids`,new Error("UNSTABLE_TARGET_ID")))}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService warnIfUnstableId: ",t)}}warnDuplicateId(e,t){try{if(!A())return;this.loggingService.catch(`[velt] Duplicate target id "${e}" \u2014 ${t} elements share this id. Cause: the same ${b.ATTRIBUTES.VELT_SUGGESTION_TARGET} appears on multiple DOM nodes. Fix: ensure each suggestable element has a unique id. Velt is using the first registered element. Docs: velt.dev/docs/suggestions/target-ids`,new Error("DUPLICATE_TARGET_ID"))}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService warnDuplicateId: ",r)}}};n.\u0275fac=function(t){return new(t||n)(v(x),v(j),v(B))},n.\u0275prov=C({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var Ie=new Set(["apiKey","documentId","clientDocumentId","organizationId","clientOrganizationId","folderId","veltFolderId","parentVeltFolderId","documentMetadata","sdkVersion","pageInfo"]),ht=(()=>{let n=class n{constructor(e,t,r,i,a,c){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.targetRegistry=i,this.serviceBook=a,this.commonDbService=c,this.actionSubjects=new Map,this.appliedValues=new Map,this.observingActive=!1,this.commentService=null,this.inlineSuggestionsEnabled$=new Q(!0);try{this.targetRegistry.setActionsService(this),this.serviceBook.observe(U).subscribe(g=>{this.commentService=g})}catch(g){this.loggingService.catch("Error in SuggestionActionsService constructor: ",g)}}enableSuggestionMode(e){try{this.modeService.enable(e),this.startObservingIfNeeded(),this.warnIfNoTaggedElements()}catch(t){this.loggingService.catch("Error in SuggestionActionsService enableSuggestionMode: ",t)}}disableSuggestionMode(){try{this.modeService.disable(),this.stopObservingIfNeeded()}catch(e){this.loggingService.catch("Error in SuggestionActionsService disableSuggestionMode: ",e)}}isSuggestionModeEnabled(){try{return this.modeService.isEnabled()}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled: ",e),!1}}enableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value||this.inlineSuggestionsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in SuggestionActionsService enableInlineSuggestions: ",e)}}disableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value&&this.inlineSuggestionsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in SuggestionActionsService disableInlineSuggestions: ",e)}}isInlineSuggestionsEnabled$(){return this.inlineSuggestionsEnabled$.pipe(R())}isSuggestionModeEnabled$(){try{return this.modeService.enabled$}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled$: ",e),new T}}registerTarget(e){try{if(!e?.targetId||typeof e?.getter!="function")return;this.targetRegistry.registerTarget(e.targetId,e.getter,{setter:e.setter,restoreOnCommit:e.restoreOnCommit})}catch(t){this.loggingService.catch("Error in SuggestionActionsService registerTarget: ",t)}}unregisterTarget(e){try{this.targetRegistry.unregisterTarget(e)}catch(t){this.loggingService.catch("Error in SuggestionActionsService unregisterTarget: ",t)}}startSuggestion(e){try{let t=this.targetRegistry.getGetter(e);if(t){this.snapshotService.captureFromGetter(e,t);return}let r=this.targetRegistry.getFallbackValue(e);r.hasValue?this.snapshotService.captureValue(e,r.value):this.loggingService.warn(`[velt] startSuggestion: target "${e}" not registered. Cause: no getter via registerTarget() and no textContent fallback. Fix: tag the element with data-velt-suggestion-target and register a getter via registerTarget(). Docs: velt.dev/docs/suggestions/targets`)}catch(t){this.loggingService.catch("Error in SuggestionActionsService startSuggestion: ",t)}}commitSuggestion(e){return new Promise((t,r)=>{try{if(!e?.targetId){r(new Error("INVALID_CONFIG"));return}if(!this.modeService.isEnabled()){this.loggingService.warn("[velt] commitSuggestion called while suggestion mode is disabled. Cause: enableSuggestionMode() has not been called (or disableSuggestionMode() was called). Fix: call enableSuggestionMode() before commit, or branch on isSuggestionModeEnabled() in your onSave handler. Docs: velt.dev/docs/suggestions/mode"),r(new Error("MODE_NOT_SUGGESTING"));return}if(!this.targetRegistry.isRegistered(e.targetId)){this.loggingService.warn(`[velt] commitSuggestion: target "${e.targetId}" not registered. Cause: no element has data-velt-suggestion-target="${e.targetId}" and no registerTarget() call provided a getter. Fix: tag the element or register a getter at app boot. Docs: velt.dev/docs/suggestions/targets`),r(new Error("TARGET_NOT_REGISTERED"));return}if(!this.snapshotService.hasSnapshot(e.targetId)){let l=this.targetRegistry.getGetter(e.targetId);if(l){if(!this.snapshotService.captureFromGetter(e.targetId,l)){r(new Error("SNAPSHOT_FAILED"));return}}else{let S=this.targetRegistry.getFallbackValue(e.targetId);if(S.hasValue)this.snapshotService.captureValue(e.targetId,S.value);else{this.loggingService.warn(`[velt] commitSuggestion: target "${e.targetId}" requires registerTarget() for complex values. Cause: complex objects need a getter so the SDK can deep-clone the snapshot. Fix: call velt.getSuggestionElement().registerTarget("${e.targetId}", () => yourState.${e.targetId}) at app boot. Docs: velt.dev/docs/suggestions/getter`),r(new Error("NO_GETTER_FOR_COMPLEX"));return}}}let g=this.snapshotService.getSnapshot(e.targetId),u=e.newValue;if(M(g,u)){this.loggingService.warn(`[velt] commitSuggestion: no change detected for target "${e.targetId}". Cause: oldValue and newValue are deeply equal. Fix: only call commitSuggestion when the customer actually changed the value. Docs: velt.dev/docs/suggestions/edge-cases`),r(new Error("NO_CHANGE_TO_SUGGEST"));return}let h=new ge;h.type="suggestion",h.suggestion={status:"pending",targetId:e.targetId,targetType:"custom",oldValue:g,newValue:u,summary:e.summary??null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},this.setCustomerMetadata(h.suggestion,e.metadata),this.setTextChange(h.suggestion,e.targetId,e.textChange,g,u);let d=Ne(e.summary,e.summaryHtml,g,u),f=new ue;if(f.commentText=d.commentText,f.commentHtml=d.commentHtml,h.comments=[f],!this.commentService){this.loggingService.catch('SuggestionActionsService.commitSuggestion: comment chunk not loaded \u2014 call Snippyly.preloadComment() first or include "comment" in featureAllowList.',new Error("comment chunk unavailable")),r(new Error("comment chunk not loaded"));return}this.commentService.addComment(void 0,void 0,void 0,void 0,!1,[],void 0,void 0,void 0,void 0,void 0,void 0,void 0,l=>{try{this.snapshotService.clearSnapshot(e.targetId),this.projectAndTrigger(p.SUGGESTION_CREATED,l.annotation),t({id:l.annotation.annotationId})}catch(S){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion callback: ",S),r(S)}},void 0,void 0,h,void 0,void 0,!0,void 0,void 0,"internal",void 0)}catch(i){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion: ",i),r(i)}})}getSuggestions(e){try{let t=this.commentService?.getCommentAnnotationsOnCurrentOrganizationAndDocument()??[],r=[];for(let i of t){if(!i.suggestion)continue;let a=this.projectAnnotationToSuggestion(i);a&&this.matchesFilter(a,e)&&r.push(a)}return r}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions: ",t),[]}}getSuggestions$(e){try{return this.serviceBook.observe(U).pipe(Z(t=>t?t.getCommentAnnotationsOnCurrentOrganizationAndDocument$():$([]))).pipe(k(t=>{let r=[];for(let i of t??[]){if(!i.suggestion)continue;let a=this.projectAnnotationToSuggestion(i);a&&this.matchesFilter(a,e)&&r.push(a)}return r}),R(z))}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions$: ",t),new T}}getPendingSuggestion(e){try{if(!e)return null;let t=this.getSuggestions({targetId:e,status:"pending"});return t.length===0?null:t.sort((r,i)=>(i.createdAt??0)-(r.createdAt??0))[0]}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion: ",t),null}}getPendingSuggestion$(e){try{return e?this.getSuggestions$({targetId:e,status:"pending"}).pipe(k(t=>t.length===0?null:t.sort((r,i)=>(i.createdAt??0)-(r.createdAt??0))[0]),R(z)):new T}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion$: ",t),new T}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new L),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in SuggestionActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new L),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in SuggestionActionsService onAction: ",t),$(null)}}projectAndTrigger(e,t){try{if(!t||!t.suggestion)return;let r=this.projectAnnotationToSuggestion(t);if(!r)return;let i=this.timestamp;switch(e){case p.SUGGESTION_CREATED:{let a={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_CREATED,a);break}case p.SUGGESTION_APPROVED:{let a={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_APPROVED,a);break}case p.SUGGESTION_REJECTED:{let a={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_REJECTED,a);break}case p.SUGGESTION_STALE:{let a={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_STALE,a);break}}}catch(r){this.loggingService.catch("Error in SuggestionActionsService projectAndTrigger: ",r)}}setCustomerMetadata(e,t){let r=this.cloneCustomerMetadata(t);r&&(e.metadata=r)}setTextChange(e,t,r,i,a){try{let c=q(r);c.reason?this.loggingService.warn(`[velt] commitSuggestion: textChange was not saved. Cause: ${c.reason}. Fix: pass { removed, added, contextBefore, contextAfter, occurrence }. Docs: velt.dev/docs/suggestions`):c.droppedKeys.length&&this.loggingService.warn(`[velt] commitSuggestion: textChange keys ${c.droppedKeys.join(", ")} were not saved. Cause: they are not textChange keys. Fix: put your own data in metadata. Docs: velt.dev/docs/suggestions`);let g=c.value??this.computeTextChange(t,i,a);g&&(e.textChange=g)}catch(c){this.loggingService.catch("Error in SuggestionActionsService setTextChange: ",c)}}computeTextChange(e,t,r){if(typeof t!="string"||typeof r!="string")return null;let i=this.targetRegistry.getNode(e);if(!(i instanceof HTMLElement)||!i.isConnected||!i.isContentEditable||i.closest(".ProseMirror"))return null;for(let c of this.targetRegistry.getTypedEdits(i)??[]){let g=G(c.base,c.start,c.end,c.added);if(g&&Se(g,t,r))return N(g)}let a=me(t,r);return a&&N(a)}getTextChange(e){return q(e.textChange).value}cloneCustomerMetadata(e){if(e==null)return;let t=typeof e=="object"?Object.getPrototypeOf(e):void 0;if(t!==Object.prototype&&t!==null){this.loggingService.warn('[velt] commitSuggestion: metadata was not saved. Cause: it is not a plain object. Fix: pass a plain JSON object, e.g. { kind: "replacement" }. Docs: velt.dev/docs/suggestions');return}try{let r=le(e);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{this.loggingService.warn("[velt] commitSuggestion: metadata was not saved. Cause: it cannot be serialized as JSON (BigInt or a circular reference). Fix: pass JSON-safe values only. Docs: velt.dev/docs/suggestions");return}}getCustomerMetadata(e){let t=e.suggestion?.metadata;if(t&&typeof t=="object"&&!Array.isArray(t))return E({},t);let r={},i=e.metadata;if(i&&typeof i=="object")for(let a of Object.keys(i))Ie.has(a)||Object.defineProperty(r,a,{value:i[a],enumerable:!0,writable:!0,configurable:!0});return r}setAppliedValues(e,t){this.appliedValues.set(e,t)}projectAnnotationToSuggestion(e){try{let t=e.suggestion;if(!t)return;let r={annotationId:e.annotationId,targetId:t.targetId,targetType:t.targetType,oldValue:t.oldValue,newValue:t.newValue,summary:t.summary,metadata:this.getCustomerMetadata(e),textChange:this.getTextChange(t),driftDetected:!!t.driftDetected,createdBy:e.from,createdAt:e.createdAt??0};switch(t.status){case"pending":return I(E({},r),{status:"pending",rejectReason:null,resolvedBy:null,resolvedAt:null});case"accepted":case"apply_failed":{let i=t.status==="accepted"?this.appliedValues.get(e.annotationId):void 0;return I(E(E({},r),i??{}),{status:t.status,rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp})}case"rejected":return I(E({},r),{status:"rejected",rejectReason:t.rejectReason??null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp});case"stale":return I(E({},r),{status:"stale",rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt});default:return}}catch(t){this.loggingService.catch("Error in SuggestionActionsService projectAnnotationToSuggestion: ",t);return}}startObservingIfNeeded(){try{if(this.observingActive)return;this.observingActive=!0,this.targetRegistry.startObserving()}catch(e){this.loggingService.catch("Error in SuggestionActionsService startObservingIfNeeded: ",e)}}stopObservingIfNeeded(){try{if(!this.observingActive)return;this.observingActive=!1,this.targetRegistry.stopObserving()}catch(e){this.loggingService.catch("Error in SuggestionActionsService stopObservingIfNeeded: ",e)}}warnIfNoTaggedElements(){try{this.targetRegistry.countTaggedElements()===0&&this.loggingService.warn('[velt] No suggestable elements found on this page. Cause: no DOM elements have a data-velt-suggestion-target attribute. Fix: tag at least one element with data-velt-suggestion-target="your.id" before enabling suggestion mode. Docs: velt.dev/docs/suggestions/getting-started')}catch(e){this.loggingService.catch("Error in SuggestionActionsService warnIfNoTaggedElements: ",e)}}get timestamp(){return this.commonDbService.getServerTimestamp()}matchesFilter(e,t){try{return t?!(t.targetId&&e.targetId!==t.targetId||t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(e.status)):!0}catch(r){return this.loggingService.catch("Error in SuggestionActionsService matchesFilter: ",r),!1}}};n.\u0275fac=function(t){return new(t||n)(v(x),v(j),v(B),v(ye),v(he),v(de))},n.\u0275prov=C({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();function Te(s){try{return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}catch{return""}}function y(s){try{if(s==null)return"";if(typeof s=="string")return s;if(typeof s=="object")try{return JSON.stringify(s)}catch{return String(s)}return String(s)}catch{return""}}function Ee(s){try{if(s===null||typeof s!="object"||Array.isArray(s))return!1;let n=Object.getPrototypeOf(s);return n===Object.prototype||n===null}catch{return!1}}function be(s,n){try{let o=s==null,e=n==null;if(o&&!e)return[{op:"add",newText:y(n)}];if(!o&&e)return[{op:"remove",oldText:y(s)}];if(Ee(s)&&Ee(n)){let t=s,r=n,i=[...Object.keys(t),...Object.keys(r).filter(c=>!(c in t))],a=[];for(let c of i){let g=c in t,u=c in r;g&&u?M(t[c],r[c])||a.push({op:"replace",oldText:`${c}: ${y(t[c])}`,newText:`${c}: ${y(r[c])}`}):g?a.push({op:"remove",oldText:`${c}: ${y(t[c])}`}):a.push({op:"add",newText:`${c}: ${y(r[c])}`})}if(a.length>0)return a}return[{op:"replace",oldText:y(s),newText:y(n)}]}catch{return[{op:"replace",oldText:y(s),newText:y(n)}]}}function Me(s,n){try{return be(s,n).map(o=>o.op==="add"?`Add: "${o.newText??""}"`:o.op==="remove"?`Remove: "${o.oldText??""}"`:`Replace: "${o.oldText??""}" with "${o.newText??""}"`).join(`
2
+ `)}catch{return'Replace: "" with ""'}}var K="color:#e0492b;font-style:italic;",W="color:#0f8a4d;font-style:italic;";function Ge(s,n){try{let o=be(s,n),e=t=>Te(t??"");if(o.length===1){let t=o[0],r=(i,a,c)=>`<div class="velt-suggestion-default-line">${i} <span class="velt-suggestion-default-${c}" dir="auto" style="${c==="old"?K:W}">&ldquo;${e(a)}&rdquo;</span></div>`;return t.op==="add"?r("Add",t.newText,"new"):t.op==="remove"?r("Remove",t.oldText,"old"):r("Replace",t.oldText,"old")+r("with",t.newText,"new")}return o.map(t=>t.op==="add"?`<div>Add: <span style="${W}">&ldquo;${e(t.newText)}&rdquo;</span></div>`:t.op==="remove"?`<div>Remove: <span style="${K}">&ldquo;${e(t.oldText)}&rdquo;</span></div>`:`<div>Replace: <span style="${K}">&ldquo;${e(t.oldText)}&rdquo;</span> with <span style="${W}">&ldquo;${e(t.newText)}&rdquo;</span></div>`).join("")}catch{return"<div>Replace:</div><div>with</div>"}}function Ne(s,n,o,e){try{let t=s||Me(o,e),r;return n?r=n:s?r=`<p>${Te(s)}</p>`:r=Ge(o,e),{commentText:t,commentHtml:r}}catch{return{commentText:"",commentHtml:""}}}export{Pe as a,ze as b,q as c,He as d,j as e,ye as f,ht as g};
@@ -1 +1 @@
1
- import{He as h,Vg as a,Yd as c}from"./chunk-XRSE2VTK.js";var T=(t,n)=>{try{let e=d(t),r=[],o=[];return e.forEach(i=>{i?.parentElement?.closest(h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT)?i?.parentElement?.normalize():i?.data&&o.push(i)}),o.forEach(i=>{let s=l(i,n);s&&r.push(s)}),r}catch(e){return c.catch("Error in highlighter highlightRange: ",e),[]}},d=t=>{try{if(t.collapsed)return[];let n=t.commonAncestorContainer;if(t.commonAncestorContainer.nodeType!==Node.ELEMENT_NODE&&(n=t.commonAncestorContainer.parentElement),!n)return[];let e=[],r=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),o,i=!1;for(;o=r.nextNode();)if(t.intersectsNode(o)){if(a(o))continue;let s=o?.length;if(t.startContainer===o&&t.startOffset>=s||t.endContainer===o&&t.endOffset===0)continue;t.startContainer===o&&t.startOffset>0&&(o.splitText(t.startOffset),i=!0),t.endContainer===o&&t.endOffset<s&&o.splitText(t.endOffset),e.push(o)}return i&&e.shift(),e}catch(n){return c.catch("Error in highlighter getTextNodesInRange: ",n),[]}},l=(t,n)=>{try{let e=document.createElement(n||h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT),r=t.splitText(0);return r.parentNode?.replaceChild(e,r),e.appendChild(r),e.__veltPageTextNode=t,e}catch(e){return c.catch("Error in highlighter highlightNode: ",e),null}},u=(t,n)=>{try{if(!t)return;let e=n??(t.textContent?document.createTextNode(t.textContent):null),r=t.__veltPageTextNode;if(r){if(r.parentNode!==t.parentNode){t.remove();return}if(e?.nodeType===Node.TEXT_NODE){r.data||(r.data=e.data),t.remove();return}}e?t.replaceWith(e):t.remove()}catch(e){c.catch("Error in highlighter unwrapHighlightElement: ",e)}};export{T as a,u as b};
1
+ import{He as h,Vg as a,Yd as c}from"./chunk-7CAYUDV6.js";var T=(t,n)=>{try{let e=d(t),r=[],o=[];return e.forEach(i=>{i?.parentElement?.closest(h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT)?i?.parentElement?.normalize():i?.data&&o.push(i)}),o.forEach(i=>{let s=l(i,n);s&&r.push(s)}),r}catch(e){return c.catch("Error in highlighter highlightRange: ",e),[]}},d=t=>{try{if(t.collapsed)return[];let n=t.commonAncestorContainer;if(t.commonAncestorContainer.nodeType!==Node.ELEMENT_NODE&&(n=t.commonAncestorContainer.parentElement),!n)return[];let e=[],r=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),o,i=!1;for(;o=r.nextNode();)if(t.intersectsNode(o)){if(a(o))continue;let s=o?.length;if(t.startContainer===o&&t.startOffset>=s||t.endContainer===o&&t.endOffset===0)continue;t.startContainer===o&&t.startOffset>0&&(o.splitText(t.startOffset),i=!0),t.endContainer===o&&t.endOffset<s&&o.splitText(t.endOffset),e.push(o)}return i&&e.shift(),e}catch(n){return c.catch("Error in highlighter getTextNodesInRange: ",n),[]}},l=(t,n)=>{try{let e=document.createElement(n||h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT),r=t.splitText(0);return r.parentNode?.replaceChild(e,r),e.appendChild(r),e.__veltPageTextNode=t,e}catch(e){return c.catch("Error in highlighter highlightNode: ",e),null}},u=(t,n)=>{try{if(!t)return;let e=n??(t.textContent?document.createTextNode(t.textContent):null),r=t.__veltPageTextNode;if(r){if(r.parentNode!==t.parentNode){t.remove();return}if(e?.nodeType===Node.TEXT_NODE){r.data||(r.data=e.data),t.remove();return}}e?t.replaceWith(e):t.remove()}catch(e){c.catch("Error in highlighter unwrapHighlightElement: ",e)}};export{T as a,u as b};
@@ -1 +1 @@
1
- import{Ra as c,Za as o,zk as s}from"./chunk-XRSE2VTK.js";var n=(()=>{let r=class r{constructor(t){this.domService=t}transform(t){try{return this.domService.sanitizeHtml(t)}catch{return t}}};r.\u0275fac=function(i){return new(i||r)(c(s,16))},r.\u0275pipe=o({name:"sanitizeHtml",type:r,pure:!0});let e=r;return e})();export{n as a};
1
+ import{Ra as c,Za as o,zk as s}from"./chunk-7CAYUDV6.js";var n=(()=>{let r=class r{constructor(t){this.domService=t}transform(t){try{return this.domService.sanitizeHtml(t)}catch{return t}}};r.\u0275fac=function(i){return new(i||r)(c(s,16))},r.\u0275pipe=o({name:"sanitizeHtml",type:r,pure:!0});let e=r;return e})();export{n as a};