@veltdev/sdk-staging 6.0.0-beta.16 → 6.0.0-beta.17
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.
- package/app/client/snippyly.model.d.ts +10 -0
- package/{chunk-54BT4NQJ.js → chunk-2XFMMSIA.js} +1 -1
- package/{chunk-KYEMQS6S.js → chunk-35J3HFXX.js} +1 -1
- package/{chunk-6QX764ZI.js → chunk-46SLBZHY.js} +1 -1
- package/{chunk-RD2BRSWO.js → chunk-7KKEGN3R.js} +1 -1
- package/{chunk-5I3MKJ2F.js → chunk-7YVQR4BL.js} +1 -1
- package/{chunk-HNT7HKW3.js → chunk-ATMZKPBX.js} +1 -1
- package/{chunk-62RN7JJN.js → chunk-B4IA4XDT.js} +1 -1
- package/{chunk-EYPJC34Q.js → chunk-BYJ7FNFA.js} +1 -1
- package/{chunk-6K2VWE4K.js → chunk-DJYRZD7H.js} +1 -1
- package/{chunk-O4F37U67.js → chunk-FXUDI3M6.js} +25 -25
- package/{chunk-TMYAQS7C.js → chunk-G35OSTOG.js} +1 -1
- package/{chunk-B7JPRLBQ.js → chunk-GBHISGGX.js} +1 -1
- package/{chunk-MZ2HKBWF.js → chunk-GGPJ6IKC.js} +1 -1
- package/{chunk-JAOM3JHX.js → chunk-GRHEZULW.js} +1 -1
- package/{chunk-ELEMLDFM.js → chunk-HCYE7VHY.js} +1 -1
- package/{chunk-OK5VRMUL.js → chunk-MMLFNU6G.js} +1 -1
- package/{chunk-POME7PZR.js → chunk-MNSD5X74.js} +1 -1
- package/{chunk-WJFVURTP.js → chunk-MWSODQ6X.js} +1 -1
- package/{chunk-APPJN3VX.js → chunk-NTNPNLFT.js} +1 -1
- package/{chunk-LHTLQZLP.js → chunk-O7ZAC2ZS.js} +1 -1
- package/{chunk-5EO5WTC7.js → chunk-OEREM5JH.js} +1 -1
- package/{chunk-HPRUJRZF.js → chunk-R7O6MRU7.js} +1 -1
- package/{chunk-6OW5GJ3E.js → chunk-RFCFKIUM.js} +1 -1
- package/{chunk-XYR7TNZL.js → chunk-ROAAPWB6.js} +1 -1
- package/{chunk-K5BJ5DAO.js → chunk-RU3S5WM7.js} +1 -1
- package/{chunk-S4APJ64C.js → chunk-SJ45VMIG.js} +1 -1
- package/{chunk-NLVNX52N.js → chunk-SZKZ3DG3.js} +1 -1
- package/{chunk-OEYWDDK3.js → chunk-TH6YKCXO.js} +1 -1
- package/{chunk-HLPJRWIY.js → chunk-TYMRWTZD.js} +1 -1
- package/{chunk-5NMVUDFG.js → chunk-WD2ZEHH2.js} +1 -1
- package/{chunk-CZWARF5M.js → chunk-WDA4SVMN.js} +1 -1
- package/{chunk-MRAZ6ENQ.js → chunk-XA2U66CN.js} +1 -1
- package/{chunk-IY3WJ7XZ.js → chunk-XK65RTYQ.js} +1 -1
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +1 -1
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as x,c as R,d as f,e as F,f as k}from"./chunk-
|
|
1
|
+
import{b as x,c as R,d as f,e as F,f as k}from"./chunk-G35OSTOG.js";import{$ as v,Ee as I,Fe as C,Of as w,Ve as S,Wd as u,Yd as y,be as A,ca as d,di as L,ei as O,g,ji as D,ki as P,mi as j,vh as E,wi as N}from"./chunk-FXUDI3M6.js";var z=l=>{try{let n={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return P.sanitize(l,n)}catch(n){return u.catch("Error in File utils sanitizeSvg: ",n),""}},U=l=>{try{return l.name.split(".").slice(0,-1).join(".")}catch(n){u.catch("Error in File utils getFileName: ",n);return}},T=l=>{try{return/(?:\.([^.]+))?$/.exec(l?.name)[1]}catch(n){u.catch("Error in File utils getFileExtension: ",n);return}},M=(l,n)=>{try{let h=l.slice(0,-1,l.type);return new File([h],n+"."+T(l),{type:l.type})}catch(h){u.catch("Error in File utils updateFile: ",h);return}};var b={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var _=(()=>{let n=class n{getStorageInstance(t){return t?f(void 0,t):f()}ref(t,e){return F(t,e)}uploadBytesResumable(t,e,o){return k(t,e,o)}getDownloadURL(t){return R(t)}deleteObject(t){return x(t)}};n.\u0275fac=function(e){return new(e||n)},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();var ae=(()=>{let n=class n{constructor(t,e,o,a,c,s){this.authService=t,this.configService=e,this.coreActionsService=o,this.loggingService=a,this.attachmentResolverService=c,this.storageAdapter=s,this.storage=this.storageAdapter.getStorageInstance();try{this.configService.getApiKey$().subscribe(r=>{this.apiKey=r}),this.authService.getFirebaseConfig$().subscribe(r=>{if(r&&r.firebaseOptions?.storageBucket){this.storage=this.storageAdapter.getStorageInstance(r?.firebaseOptions?.storageBucket);let i=this.configService.getProxyConfig();i?.storageHost&&(this.storage.host=i.storageHost)}},r=>{this.loggingService.catch("Error in StorageService constructor: ",r)})}catch(r){this.loggingService.catch("Error in StorageService constructor:",r)}}createAttachment({path:t,file:e}){try{let o=new C;o.name=e.name;let a=M(e,`${o.attachmentId}_${U(e)}`),c=`${this.apiKey}/${t}/${a?.name}`;return o.bucketPath=c,o.size=e.size,o.type=T(e),o?.type&&(o.mimeType=b[o?.type]),o}catch(o){return this.loggingService.catch("Error in StorageService createAttachment: ",o),null}}sanitizeSvgFile(t){return g(this,null,function*(){if(t.type===b.svg)try{let e=yield t.text(),o=z(e);return new File([o],t.name,{type:t.type})}catch(e){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",e),t}return t})}uploadAttachmentToStorage(c){return g(this,arguments,function*({attachment:t,file:e,resolve:o,reject:a}){try{let s=this.storageAdapter.ref(this.storage,t.bucketPath),r=this.storageAdapter.uploadBytesResumable(s,e,{cacheControl:"public,max-age=3600"});r.on("state_changed",i=>{let m=i.bytesTransferred/i.totalBytes*100},i=>{a(i)},()=>{this.storageAdapter.getDownloadURL(r.snapshot.ref).then(i=>{t.url=i,o(t)})})}catch(s){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",s),a(s)}})}uploadToResolver(r){return g(this,arguments,function*({file:t,attachment:e,metadata:o,resolve:a,reject:c,scope:s}){try{o.attachmentId=e.attachmentId;let i={attachmentId:e.attachmentId,name:e.name,file:t,metadata:o,mimeType:e.mimeType},m=w();this.coreActionsService.triggerAction(A.ATTACHMENT_RESOLVER,{event:E.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:S.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:i,eventType:y.ATTACHMENT_ADD}});let p=yield this.attachmentResolverService.saveAttachment({attachment:i,eventType:y.ATTACHMENT_ADD},m,s);p&&p.data?.url?(e.url=p.data?.url,a(e)):c(new Error("Failed to upload attachment to resolver"))}catch(i){this.loggingService.catch("Error in StorageService uploadToResolver: ",i),c(i)}})}uploadFile({path:t,file:e,useAttachmentResolver:o,metadata:a,attachmentScope:c}){return new Promise((s,r)=>g(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let i=yield this.sanitizeSvgFile(e),m=this.createAttachment({path:t,file:i});if(!m)throw new Error("Attachment not created");o?this.uploadToResolver({file:i,attachment:m,metadata:a,resolve:s,reject:r,scope:c}):this.uploadAttachmentToStorage({attachment:m,file:i,resolve:s,reject:r})}catch(i){this.loggingService.catch("Error in StorageService uploadFile:",i),r(i)}}))}uploadChunk(t,e,o,a){return new Promise((c,s)=>{try{if(a?.useAttachmentResolver){let r=this.createAttachment({path:t,file:e});if(!r){s(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:e,attachment:r,metadata:a.metadata,resolve:i=>c(i.url),reject:s,scope:a.attachmentScope});return}if(this.apiKey){let r=`${this.apiKey}/${t}/${e.name}`,i=this.storageAdapter.ref(this.storage,r),m=this.storageAdapter.uploadBytesResumable(i,e,{cacheControl:"public,max-age=3600"});m.on("state_changed",p=>{let H=p.bytesTransferred/p.totalBytes*100},p=>{s(p)},()=>{this.storageAdapter.getDownloadURL(m.snapshot.ref).then(p=>{c(p)}).catch(p=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${o}:`,p),s(p)})})}else{let r=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",r),s(r)}}catch(r){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${o}: `,r),s(r)}})}downloadAttachment(t){try{if(t.url){let e=new XMLHttpRequest;e.responseType="blob",e.onload=()=>{let o=e.response,a=document.createElement("a"),c=window.URL.createObjectURL(o);a.setAttribute("type","hidden"),a.setAttribute(I.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=c,t?.name&&(a.download=t?.name),document.body.appendChild(a);let s=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(s),window.URL.revokeObjectURL(c),a.remove()},e.onerror=()=>{window.open(t.url,"_blank")},e.open("GET",t.url),e.send()}}catch(e){this.loggingService.catch("Error in StorageService downloadAttachment: ",e)}}deleteAttachment({attachment:t,metadata:e,useAttachmentResolver:o,attachmentScope:a}){return new Promise((c,s)=>{if(o){let r=w();this.coreActionsService.triggerAction(A.ATTACHMENT_RESOLVER,{event:E.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:S.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t.attachmentId,metadata:e}}),this.attachmentResolverService.deleteAttachment({attachmentId:t.attachmentId,metadata:e},r,a).then(()=>{c(null)}).catch(i=>{s(i)})}else{let r=this.storageAdapter.ref(this.storage,t.bucketPath);this.storageAdapter.deleteObject(r).then(()=>{c(null)}).catch(i=>{c(null)})}})}deleteFileFromPath(t){return new Promise((e,o)=>{let a=this.storageAdapter.ref(this.storage,t);this.storageAdapter.deleteObject(a).then(()=>{e(null)}).catch(c=>{o(c)})})}};n.\u0275fac=function(e){return new(e||n)(d(j),d(O),d(D),d(L),d(N),d(_))},n.\u0275prov=v({token:n,factory:n.\u0275fac,providedIn:"root"});let l=n;return l})();export{ae as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as qt}from"./chunk-IY3WJ7XZ.js";import{a as Kt}from"./chunk-62RN7JJN.js";import{$ as K,$e as Q,$f as Z,Af as gt,Bf as z,Cf as At,Ci as mt,Dd as Nt,De as P,Df as ft,E as F,Ei as at,Fi as Wt,G as V,Gi as kt,Hi as Jt,J as k,Kh as Ft,L as J,M as lt,Mf as Ut,Mh as Pt,Nd as It,Nf as Tt,O as St,Qf as Et,T as I,Vf as $t,W as vt,Wf as dt,_e as q,a as D,ae as Ot,ai as it,b as T,bi as zt,ca as m,ci as et,da as pt,di as Bt,g as E,gi as xt,ih as Rt,ii as Ht,ki as jt,l as O,li as ot,mi as Vt,ne as yt,ni as Lt,p as G,ph as ht,pi as _t,q as ct,r as C,rh as X,ri as ut,si as Yt,tf as bt,ti as st,uh as L,v as N,vh as tt,w as W,xf as Dt,xh as wt,xi as Gt,yf as Ct,yi as rt,zh as Mt,zi as nt}from"./chunk-O4F37U67.js";var Qt=(()=>{let A=class A{constructor(t,i,e,o,s,a,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=a,this.serviceBook=r,this.serviceBook.set(Mt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let a of s)i.add(a)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(Ft)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return E(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield $t(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};A.\u0275fac=function(i){return new(i||A)(m(nt),m(et),m(rt),m(ot),m(st),m(at),m(it))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let H=A;return H})();var Bi=(()=>{let A=class A{constructor(t,i,e,o,s,a,r,n,c,l,g,f,d,h,p,$,M,S,U,R,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=a,this.commentUtilsService=r,this.commentAnnotationsResolverService=n,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=h,this.notificationUtilsService=p,this.usersService=$,this.functions=M,this.userPermissionService=S,this.coreActionsService=U,this.serviceBook=R,this.realtimeAdapter=w,this.endpointsService=pt(xt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new O(null),this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.settingsInitialConfig$=new O([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(wt,this),this.serviceBook.observe(Pt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(F(v=>!!v),k(1)).subscribe(v=>{if(v){this.db=v;try{let u=this.configService.getProxyConfig(),b=this.endpointsService.getNotificationsDbUrl();Dt(b)?this.notificationsDb=null:(u?.v1DbHost&&b&&(b=Ct(b,u.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(b),u?.v1DbHost&&b&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(u){this.loggingService.catch("Error initializing notifications DB, using default: ",u),this.notificationsDb=v}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},v=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",v)}),this.authService.getUser$().subscribe(v=>{v?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(u=>{this.notificationsByDocumentIdSubscription[u]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let u=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(b=>{let x=u?.[b]?.notifications;x?.length&&x.forEach(y=>{this.notificationUtilsService.mergeLocationWithNotification({notification:y},v)?.notification})}),this.notificationsByDocumentIdMap$.next(u)}})}catch(v){this.loggingService.catch("Error in NotificationService constructor: ",v)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return E(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=z(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let n=r?.values?.find(c=>c.id===r.default);s[r.id]=n||r?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(s).forEach(r=>{a[r]=s[r].id}),yield this.updateSettingsConfigToDb(a)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=z(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(F(i=>i===!0),I(()=>W([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(F(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>ct(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(N(s=>{s?.data?.notificationsConfig&&!Z(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(N(i=>{})):C(void 0)))),vt(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(lt(),N(([t,i])=>{let e=t?.map(n=>n.documentId),o=i?.map(n=>n.documentId),s=e?.filter(n=>!o?.includes(n)),a=o?.map(n=>({documentId:n,timestamp:i?.find(c=>c.documentId===n)?.timestamp})).filter(n=>!e?.includes(n.documentId)),r=o?.map(n=>{let c=i?.find(l=>l.documentId===n)?.timestamp;return{documentId:n,timestamp:c}}).filter(n=>{let c=t?.find(l=>l.documentId===n.documentId)?.timestamp;return c&&n.timestamp&&c!==n.timestamp});a?.length&&this.fetchNotificationsForDocumentIds(a),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(n=>{this.removeNotificationsForDocumentId(n)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(N(e=>{let o=null,s=this.configService.getApiKey(),a=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&a&&(o=new mt({apiKey:s,organizationId:a})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let a=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;a.setDate(a.getDate()-r);let n=a.getTime(),c=[Vt(ut("timestamp",">=",n),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(_t("timestamp","desc")),c.push(Lt(t)));let l=e?.userId??"";return ct(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===bt.PERMISSION_DENIED?C(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(N(f=>f?.data),N(f=>{let d=[];return Object.keys(f||{}).forEach(h=>{let p=this.commonDbService.shouldUseFirestore()?f[h]?.timestamp??0:f[h],$=this.commonDbService.shouldUseFirestore()?f[h]?.deletedNotification??!1:!1;if($&&$.id&&$?.timestamp===p){let M=$.id,S=f[h]?.metadata?.documentId,U=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),R=U?.[S]??{documentMetadata:null,notifications:[]},w=R.notifications??[],v=w?.findIndex(u=>u.id===M);v!==-1&&(w.splice(v,1),this.notificationsByDocumentIdMap$.next(T(D({},U),{[S]:T(D({},R),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(M)&&this.notificationResolverService.deleteNotification(M,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:h,timestamp:p})}),d}),V(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),C([]))))))}return C(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),C([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}else{let a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}s.forEach(a=>{a.notification=this.getClientNotificationObject(a)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}a.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],n=new Map(r.map(c=>[c.notificationId,c]));a.forEach(c=>{n.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(n.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return E(this,null,function*(){try{if(t?.length){let e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let s=this.getStartAtTimestamp(),a={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(a[S.documentId]=U)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let S=[];if(t.forEach(u=>{this.docService.getDocumentMetadata(u.documentId)||S.push(u.documentId)}),S.length){let u=this.authService.getUser(),b=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let x=yield ht({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:u?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:S},getSdkProxy:b,userId:u?.userId??""});if(x?.data?.length){let y={};x.data.forEach(j=>{j?.documentId&&(y[j.documentId]=j)}),this.docService.setAllDocumentMetadata(D(D({},this.docService.getAllDocumentMetadataMap()),y))}}catch(x){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",x)}}let U=[],R=[];t.forEach(u=>{let b=this.docService.getDocumentMetadata(u.documentId);b?.clientDocumentId?U.push({userId:this.authService.getUser()?.userId??"",resource:{id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=Tt();this.coreActionsService.triggerAction(Ot.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:w,methodName:q.GET_NOTIFICATIONS,source:"internal",payload:{requests:U}});let v=yield this.userPermissionService?.onResourceAccessRequired({requests:U,uniqueId:w,methodName:q.GET_NOTIFICATIONS});v?.success&&v?.data?.length?v.data.forEach(u=>{!u.hasAccess&&u.resourceId&&(t=t.filter(b=>b.documentId!==At(u.resourceId)))}):t=[]}catch(S){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",S),t=[]}if(!t.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let r=this.userPermissionService?.getPermissionsCache()?.filter(S=>S.type===Q.CONTEXT),n={organizationId:o,documentIds:t.filter(S=>!!S.documentId&&!!S.timestamp).map(S=>({documentId:S.documentId,timestamp:S.timestamp??0})),timestamp:s,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:r,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},c=yield this.notificationUtilsService.handleNotificationEncryption({data:n}),l=yield e({veltData:c}),g=l?.data?.data?.veltData||{},f=l?.data?.data?.veltAdditionalData||{},d="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),h=yield dt(g,d),{userNotifications:p=[],userNotificationIdsInDocNotifications:$=[],permissionResults:M=[]}=yield dt(f,d);if(this.userPermissionService?.getIsContextEnabled()){let S=[...this.userPermissionService?.getPermissionsCache()??[],...M??[]];this.userPermissionService?.setPermissionsCache(S)}if(h&&typeof h=="object"){let S=this.usersService.userDataProviderAvailable(),U=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),R=this.notificationResolverService.notificationDataProviderAvailable(),w=[],v=[],u=[];Object.keys(h).forEach((y,j)=>{let Y=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(Y){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],Y))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:Y}))}let _=h[y].notifications||[];_.forEach(B=>{$.includes(B.notificationId)&&!p.find(Zt=>Zt.notificationId===B.notificationId)&&p.push(JSON.parse(JSON.stringify(B))),B.notification=this.getClientNotificationObject(B)}),this.setNotificationForDocumentIdInCache(y,Y,_),S&&(w.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldAwait:!0,forceResolve:!0})),w.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldAwait:!0,forceResolve:!0}))),U&&(v.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldNotificationResolverAwait:!0})),u.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldNotificationResolverAwait:!0})))});let b=JSON.parse(JSON.stringify(p));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...p]),(R||S||U)&&(()=>{let y=Promise.resolve();if(R&&(y=y.then(()=>Promise.allSettled(u)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"notification"),this.resolveAndMergeUserNotifications(b,"notification")})),S&&(y=y.then(()=>Promise.allSettled(w)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"user"),this.resolveAndMergeUserNotifications(b,"user")})),U){let j=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",j)})}return y})().catch(y=>{this.loggingService.catch("Error in NotificationService resolveChain: ",y)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(a=>a.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",a=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),a||(a=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),n=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let h=d?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=a||h.metadata.organizationMetadata,h.metadata.documentMetadata=i||h.metadata.documentMetadata),c&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},c)?.notification),h):null})?.filter(d=>!!d)||[],g=new Map(n.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,h)=>(h.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(D({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>C(t).pipe(F(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((n,c)=>(n[c.notificationId]=c,n),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,n)=>n.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return W([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),C({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=n=>n?.id??n?.notificationId,a=new Set;o.forEach(n=>{let c=s(n);c!=null&&a.add(c)});let r=[...o];return e.forEach(n=>{let c=s(n);c!=null&&a.has(c)||(c!=null&&a.add(c),r.push(n))}),r.sort((n,c)=>(c?.timestamp||0)-(n?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(D({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(T(D({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),J(),F(t=>!!t),V(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),G))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:z(t),isCollection:!1,useCollectionGroup:!1}}).pipe(V(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),G))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(N(i=>i?.organizationId??""),J(),lt(),F(([i])=>!!i),V(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),G))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let a=Number(o[s]);i[s]=Number.isFinite(a)?a:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(D({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(D({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return E(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let n=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(n);c?c.push(r):s.set(n,[r])}let a=[];for(let[r,n]of s){let c=n.reduce((g,f,d)=>{let h=f?.notificationId??f?.id??`__cross_org_${d}`;return g[h]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),a.push(...Object.values(l??{}))}return a}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return E(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},a=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!a.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:a}),n=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(n?.pendingPermissionQueries)?n.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(n,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:a,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return E(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return E(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),a=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(a);if(i.fetchGeneration!==this.crossOrgGeneration)return;let n=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=n:c=this.mergeCrossOrgForYou(n,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return E(this,null,function*(){let i=this.authService.getUser(),e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:D({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,a=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),n=r?o.organizationIds.filter(d=>!!d).map(d=>ft(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>ft(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(n,l));else{let d=a.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(n);d=d.filter($=>p.has($))}d=Array.from(new Set(d)),f.organizationIds=d;let h={};d.forEach(p=>{h[p]=this.crossOrgSeenTimestamps[p]??this.getStartAtTimestamp()}),f.orgTimestamps=h}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,a=o?i.filter(r=>{let n=r?.id??r?.notificationId,c=n!=null&&e.has(n);return c&&(s=!0),!c}):i.map(r=>{let n=r?.id??r?.notificationId;return n!=null&&e.has(n)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(a)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=gt(t)),i&&typeof i=="object"){let s=Et(i);e=gt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(F(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(N(a=>(s.featureAllowed=a,s))):C(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(s).pipe(I(a=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,a.documentPaths=r,a)))),I(a=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(F(i=>!!i),N(i=>T(D({},t),{config:i})),I(i=>this.authService.getUser$().pipe(N(e=>T(D({},i),{user:e})))),I(i=>Ut(i.config,i.user,yt.NOTIFICATION)?C(T(D({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(T(D({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(F(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(V(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),C(null))),N(s=>{let a=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&a.push(l)}),a.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(a),this.rawNotificationsByIdMap$.next(r);let n=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&n.push(l)}),this.processedNotifications$.next(n),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=z(t?.email));let o;t?.userId&&(o=z(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let n=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(n=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:n,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,n)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[n]?.views?.[t?.userSnippylyId],s.set(n,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let a=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&a){let n=null;a?.email&&(n=z(a?.email));let c=null;a?.userId&&(c=z(a?.userId));let l=!1,g=!0;(n&&r.notifyUsers?.[n]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=T(D(D({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||s?.notificationSourceData&&(d=s?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(a){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",a);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(a=>a.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return W([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=Array.isArray(i)?i:[],o=null;return t&&(o=[],t.forEach(s=>{s.notifications.forEach(a=>{o?.push(a)})})),e.length?t?this.mergeCrossOrgForYou(o||[],e):null:t?o.sort((s,a)=>a.timestamp-s.timestamp):null}))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let a=this.docService.getLocation();a&&(t.location=a?.location,t.locationId=a?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),n=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(n))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(a=>{a.id&&s.set(a.id,a)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(a=>{a.id&&!s.has(a.id)&&s.set(a.id,a)}),Array.from(s.values()).sort((a,r)=>(r.timestamp||0)-(a.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),St()):C(null)),J(Rt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,a=e.replace(s,(r,n)=>(n==="actionUser"||n==="recipientUser")&&o[n]?i?.email&&o[n].email===i?.email||i?.userId&&o[n]?.userId===i?.userId?"You":o[n].name||o[n].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[n]?o[n]:r);return this.domService.sanitizeHtml(a)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return E(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let a=0;a<t.length;a+=50){let n=t.slice(a,a+50).filter(g=>g?.id),c=n.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);n.forEach((g,f)=>{let d=l[f];if(!d.some(p=>p.notificationId===g.id))i=i.filter(p=>p.notificationId!==g.id);else{let p=i.find(M=>M.notificationId===g.id),$=d.find(M=>M.notificationId===g.id);p&&$?.views&&(p.views=$.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(a=>{let r=a.metadata?.documentId;if(r&&o?.[r]){let n=o?.[r]?.notifications||[],c=n.find(l=>l.id===a.id);c&&(c.isUnread=!1),o[r].notifications=n}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!Z(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return E(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(N(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),C({forYou:null,all:null})}}setNotificationAsRead(e){return E(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=z(o?.userId),{metadata:a}=t;if(a){let{apiKey:r,organizationId:n,documentId:c}=a;if(r&&n&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:n,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:n,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:n}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:n}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:n},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return E(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return E(this,null,function*(){try{let i=this.authService.getUser(),e=z(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),a=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,n={apiKey:this.configService.getApiKey(),organizationId:a,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:n}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};A.\u0275fac=function(i){return new(i||A)(m(Nt),m(zt),m(ot),m(Bt),m(Jt),m(Wt),m(nt),m(st),m(at),m(Yt),m(Gt),m(jt),m(Kt),m(et),m(Qt),m(rt),m(It),m(qt),m(Ht),m(it),m(kt))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let H=A;return H})();export{Qt as a,Bi as b};
|
|
1
|
+
import{a as qt}from"./chunk-XK65RTYQ.js";import{a as Kt}from"./chunk-B4IA4XDT.js";import{$ as K,$e as q,Ah as Mt,Ai as nt,Bf as gt,Cf as z,Df as At,Di as mt,E as F,Ed as Nt,Ee as P,Ef as ft,Fi as at,G as V,Gi as Wt,Hi as kt,Ii as Jt,J as k,L as J,Lh as Ft,M as lt,Nf as Ut,Nh as Pt,O as St,Od as It,Of as Tt,Rf as Et,T as I,W as vt,Wf as $t,Xf as dt,a as D,af as Q,ag as Z,b as T,be as Ot,bi as it,ca as m,ci as zt,da as pt,di as et,ei as Bt,g as E,hi as xt,jh as Rt,ji as Ht,l as O,li as jt,mi as ot,ni as Vt,oe as yt,oi as Lt,p as G,q as ct,qh as ht,qi as _t,r as C,sh as X,si as ut,ti as Yt,uf as bt,ui as st,v as N,vh as L,w as W,wh as tt,yf as Dt,yh as wt,yi as Gt,zf as Ct,zi as rt}from"./chunk-FXUDI3M6.js";var Qt=(()=>{let A=class A{constructor(t,i,e,o,s,a,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=a,this.serviceBook=r,this.serviceBook.set(Mt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let a of s)i.add(a)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(Ft)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return E(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield $t(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};A.\u0275fac=function(i){return new(i||A)(m(nt),m(et),m(rt),m(ot),m(st),m(at),m(it))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let H=A;return H})();var Bi=(()=>{let A=class A{constructor(t,i,e,o,s,a,r,n,c,l,g,f,d,h,p,$,M,S,U,R,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=a,this.commentUtilsService=r,this.commentAnnotationsResolverService=n,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=h,this.notificationUtilsService=p,this.usersService=$,this.functions=M,this.userPermissionService=S,this.coreActionsService=U,this.serviceBook=R,this.realtimeAdapter=w,this.endpointsService=pt(xt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new O(null),this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.settingsInitialConfig$=new O([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(wt,this),this.serviceBook.observe(Pt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(F(v=>!!v),k(1)).subscribe(v=>{if(v){this.db=v;try{let u=this.configService.getProxyConfig(),b=this.endpointsService.getNotificationsDbUrl();Dt(b)?this.notificationsDb=null:(u?.v1DbHost&&b&&(b=Ct(b,u.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(b),u?.v1DbHost&&b&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(u){this.loggingService.catch("Error initializing notifications DB, using default: ",u),this.notificationsDb=v}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},v=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",v)}),this.authService.getUser$().subscribe(v=>{v?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(u=>{this.notificationsByDocumentIdSubscription[u]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let u=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(b=>{let x=u?.[b]?.notifications;x?.length&&x.forEach(y=>{this.notificationUtilsService.mergeLocationWithNotification({notification:y},v)?.notification})}),this.notificationsByDocumentIdMap$.next(u)}})}catch(v){this.loggingService.catch("Error in NotificationService constructor: ",v)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return E(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=z(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let n=r?.values?.find(c=>c.id===r.default);s[r.id]=n||r?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(s).forEach(r=>{a[r]=s[r].id}),yield this.updateSettingsConfigToDb(a)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=z(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(F(i=>i===!0),I(()=>W([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(F(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>ct(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(N(s=>{s?.data?.notificationsConfig&&!Z(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(N(i=>{})):C(void 0)))),vt(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(lt(),N(([t,i])=>{let e=t?.map(n=>n.documentId),o=i?.map(n=>n.documentId),s=e?.filter(n=>!o?.includes(n)),a=o?.map(n=>({documentId:n,timestamp:i?.find(c=>c.documentId===n)?.timestamp})).filter(n=>!e?.includes(n.documentId)),r=o?.map(n=>{let c=i?.find(l=>l.documentId===n)?.timestamp;return{documentId:n,timestamp:c}}).filter(n=>{let c=t?.find(l=>l.documentId===n.documentId)?.timestamp;return c&&n.timestamp&&c!==n.timestamp});a?.length&&this.fetchNotificationsForDocumentIds(a),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(n=>{this.removeNotificationsForDocumentId(n)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(N(e=>{let o=null,s=this.configService.getApiKey(),a=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&a&&(o=new mt({apiKey:s,organizationId:a})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let a=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;a.setDate(a.getDate()-r);let n=a.getTime(),c=[Vt(ut("timestamp",">=",n),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(_t("timestamp","desc")),c.push(Lt(t)));let l=e?.userId??"";return ct(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===bt.PERMISSION_DENIED?C(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(N(f=>f?.data),N(f=>{let d=[];return Object.keys(f||{}).forEach(h=>{let p=this.commonDbService.shouldUseFirestore()?f[h]?.timestamp??0:f[h],$=this.commonDbService.shouldUseFirestore()?f[h]?.deletedNotification??!1:!1;if($&&$.id&&$?.timestamp===p){let M=$.id,S=f[h]?.metadata?.documentId,U=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),R=U?.[S]??{documentMetadata:null,notifications:[]},w=R.notifications??[],v=w?.findIndex(u=>u.id===M);v!==-1&&(w.splice(v,1),this.notificationsByDocumentIdMap$.next(T(D({},U),{[S]:T(D({},R),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(M)&&this.notificationResolverService.deleteNotification(M,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:h,timestamp:p})}),d}),V(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),C([]))))))}return C(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),C([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}else{let a=t[e]?.notifications?.reduce((n,c)=>(n[c.notificationId]=c,n),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:a});s=Object.values(r??{})}s.forEach(a=>{a.notification=this.getClientNotificationObject(a)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});a=Object.values(c??{})}a.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],n=new Map(r.map(c=>[c.notificationId,c]));a.forEach(c=>{n.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(n.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return E(this,null,function*(){try{if(t?.length){let e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let s=this.getStartAtTimestamp(),a={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(a[S.documentId]=U)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let S=[];if(t.forEach(u=>{this.docService.getDocumentMetadata(u.documentId)||S.push(u.documentId)}),S.length){let u=this.authService.getUser(),b=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let x=yield ht({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:u?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:S},getSdkProxy:b,userId:u?.userId??""});if(x?.data?.length){let y={};x.data.forEach(j=>{j?.documentId&&(y[j.documentId]=j)}),this.docService.setAllDocumentMetadata(D(D({},this.docService.getAllDocumentMetadataMap()),y))}}catch(x){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",x)}}let U=[],R=[];t.forEach(u=>{let b=this.docService.getDocumentMetadata(u.documentId);b?.clientDocumentId?U.push({userId:this.authService.getUser()?.userId??"",resource:{id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=Tt();this.coreActionsService.triggerAction(Ot.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:w,methodName:q.GET_NOTIFICATIONS,source:"internal",payload:{requests:U}});let v=yield this.userPermissionService?.onResourceAccessRequired({requests:U,uniqueId:w,methodName:q.GET_NOTIFICATIONS});v?.success&&v?.data?.length?v.data.forEach(u=>{!u.hasAccess&&u.resourceId&&(t=t.filter(b=>b.documentId!==At(u.resourceId)))}):t=[]}catch(S){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",S),t=[]}if(!t.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let r=this.userPermissionService?.getPermissionsCache()?.filter(S=>S.type===Q.CONTEXT),n={organizationId:o,documentIds:t.filter(S=>!!S.documentId&&!!S.timestamp).map(S=>({documentId:S.documentId,timestamp:S.timestamp??0})),timestamp:s,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:r,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},c=yield this.notificationUtilsService.handleNotificationEncryption({data:n}),l=yield e({veltData:c}),g=l?.data?.data?.veltData||{},f=l?.data?.data?.veltAdditionalData||{},d="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),h=yield dt(g,d),{userNotifications:p=[],userNotificationIdsInDocNotifications:$=[],permissionResults:M=[]}=yield dt(f,d);if(this.userPermissionService?.getIsContextEnabled()){let S=[...this.userPermissionService?.getPermissionsCache()??[],...M??[]];this.userPermissionService?.setPermissionsCache(S)}if(h&&typeof h=="object"){let S=this.usersService.userDataProviderAvailable(),U=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),R=this.notificationResolverService.notificationDataProviderAvailable(),w=[],v=[],u=[];Object.keys(h).forEach((y,j)=>{let Y=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(Y){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],Y))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:Y}))}let _=h[y].notifications||[];_.forEach(B=>{$.includes(B.notificationId)&&!p.find(Zt=>Zt.notificationId===B.notificationId)&&p.push(JSON.parse(JSON.stringify(B))),B.notification=this.getClientNotificationObject(B)}),this.setNotificationForDocumentIdInCache(y,Y,_),S&&(w.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldAwait:!0,forceResolve:!0})),w.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldAwait:!0,forceResolve:!0}))),U&&(v.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:_,shouldNotificationResolverAwait:!0})),u.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldNotificationResolverAwait:!0})))});let b=JSON.parse(JSON.stringify(p));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...p]),(R||S||U)&&(()=>{let y=Promise.resolve();if(R&&(y=y.then(()=>Promise.allSettled(u)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"notification"),this.resolveAndMergeUserNotifications(b,"notification")})),S&&(y=y.then(()=>Promise.allSettled(w)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"user"),this.resolveAndMergeUserNotifications(b,"user")})),U){let j=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",j)})}return y})().catch(y=>{this.loggingService.catch("Error in NotificationService resolveChain: ",y)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(a=>a.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",a=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),a||(a=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),n=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let h=d?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=a||h.metadata.organizationMetadata,h.metadata.documentMetadata=i||h.metadata.documentMetadata),c&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},c)?.notification),h):null})?.filter(d=>!!d)||[],g=new Map(n.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,h)=>(h.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(D({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>C(t).pipe(F(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((n,c)=>(n[c.notificationId]=c,n),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,n)=>n.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return W([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),C({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=n=>n?.id??n?.notificationId,a=new Set;o.forEach(n=>{let c=s(n);c!=null&&a.add(c)});let r=[...o];return e.forEach(n=>{let c=s(n);c!=null&&a.has(c)||(c!=null&&a.add(c),r.push(n))}),r.sort((n,c)=>(c?.timestamp||0)-(n?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(D({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(T(D({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),J(),F(t=>!!t),V(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),G))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:z(t),isCollection:!1,useCollectionGroup:!1}}).pipe(V(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),G))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(N(i=>i?.organizationId??""),J(),lt(),F(([i])=>!!i),V(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),G))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let a=Number(o[s]);i[s]=Number.isFinite(a)?a:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(D({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(D({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return E(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let n=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(n);c?c.push(r):s.set(n,[r])}let a=[];for(let[r,n]of s){let c=n.reduce((g,f,d)=>{let h=f?.notificationId??f?.id??`__cross_org_${d}`;return g[h]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),a.push(...Object.values(l??{}))}return a}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return E(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},a=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!a.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:a}),n=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(n?.pendingPermissionQueries)?n.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(n,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:a,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return E(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return E(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),a=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(a);if(i.fetchGeneration!==this.crossOrgGeneration)return;let n=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=n:c=this.mergeCrossOrgForYou(n,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return E(this,null,function*(){let i=this.authService.getUser(),e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:D({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,a=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),n=r?o.organizationIds.filter(d=>!!d).map(d=>ft(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>ft(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(n,l));else{let d=a.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(n);d=d.filter($=>p.has($))}d=Array.from(new Set(d)),f.organizationIds=d;let h={};d.forEach(p=>{h[p]=this.crossOrgSeenTimestamps[p]??this.getStartAtTimestamp()}),f.orgTimestamps=h}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,a=o?i.filter(r=>{let n=r?.id??r?.notificationId,c=n!=null&&e.has(n);return c&&(s=!0),!c}):i.map(r=>{let n=r?.id??r?.notificationId;return n!=null&&e.has(n)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(a)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=gt(t)),i&&typeof i=="object"){let s=Et(i);e=gt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(F(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(N(a=>(s.featureAllowed=a,s))):C(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(s).pipe(I(a=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,a.documentPaths=r,a)))),I(a=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(F(i=>!!i),N(i=>T(D({},t),{config:i})),I(i=>this.authService.getUser$().pipe(N(e=>T(D({},i),{user:e})))),I(i=>Ut(i.config,i.user,yt.NOTIFICATION)?C(T(D({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(T(D({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(F(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(V(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),C(null))),N(s=>{let a=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&a.push(l)}),a.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(a),this.rawNotificationsByIdMap$.next(r);let n=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&n.push(l)}),this.processedNotifications$.next(n),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=z(t?.email));let o;t?.userId&&(o=z(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let n=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(n=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:n,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,n)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[n]?.views?.[t?.userSnippylyId],s.set(n,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let a=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&a){let n=null;a?.email&&(n=z(a?.email));let c=null;a?.userId&&(c=z(a?.userId));let l=!1,g=!0;(n&&r.notifyUsers?.[n]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=T(D(D({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||s?.notificationSourceData&&(d=s?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(a){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",a);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(a=>a.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return W([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=Array.isArray(i)?i:[],o=null;return t&&(o=[],t.forEach(s=>{s.notifications.forEach(a=>{o?.push(a)})})),e.length?t?this.mergeCrossOrgForYou(o||[],e):null:t?o.sort((s,a)=>a.timestamp-s.timestamp):null}))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let a=this.docService.getLocation();a&&(t.location=a?.location,t.locationId=a?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),n=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(n))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(a=>{a.id&&s.set(a.id,a)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(a=>{a.id&&!s.has(a.id)&&s.set(a.id,a)}),Array.from(s.values()).sort((a,r)=>(r.timestamp||0)-(a.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),St()):C(null)),J(Rt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,a=e.replace(s,(r,n)=>(n==="actionUser"||n==="recipientUser")&&o[n]?i?.email&&o[n].email===i?.email||i?.userId&&o[n]?.userId===i?.userId?"You":o[n].name||o[n].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[n]?o[n]:r);return this.domService.sanitizeHtml(a)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return E(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let a=0;a<t.length;a+=50){let n=t.slice(a,a+50).filter(g=>g?.id),c=n.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);n.forEach((g,f)=>{let d=l[f];if(!d.some(p=>p.notificationId===g.id))i=i.filter(p=>p.notificationId!==g.id);else{let p=i.find(M=>M.notificationId===g.id),$=d.find(M=>M.notificationId===g.id);p&&$?.views&&(p.views=$.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(a=>{let r=a.metadata?.documentId;if(r&&o?.[r]){let n=o?.[r]?.notifications||[],c=n.find(l=>l.id===a.id);c&&(c.isUnread=!1),o[r].notifications=n}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!Z(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return E(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(N(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),C({forYou:null,all:null})}}setNotificationAsRead(e){return E(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=z(o?.userId),{metadata:a}=t;if(a){let{apiKey:r,organizationId:n,documentId:c}=a;if(r&&n&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:n,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:n,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:n}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:n}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:n},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return E(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return E(this,null,function*(){try{let i=this.authService.getUser(),e=z(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),a=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,n={apiKey:this.configService.getApiKey(),organizationId:a,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:n}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};A.\u0275fac=function(i){return new(i||A)(m(Nt),m(zt),m(ot),m(Bt),m(Jt),m(Wt),m(nt),m(st),m(at),m(Yt),m(Gt),m(jt),m(Kt),m(et),m(Qt),m(rt),m(It),m(qt),m(Ht),m(it),m(kt))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let H=A;return H})();export{Qt as a,Bi as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Pa as s,
|
|
1
|
+
import{Pa as s,Xa as a,Xc as c,li as n}from"./chunk-FXUDI3M6.js";var f=(()=>{let i=class i{constructor(t,r){this.domService=t,this.sanitizer=r}transform(t,r=!0){try{let o=r?this.domService.sanitizeHtml(t):t;return this.sanitizer.bypassSecurityTrustHtml(o)}catch{return t}}};i.\u0275fac=function(r){return new(r||i)(s(n,16),s(c,16))},i.\u0275pipe=a({name:"safeHtml",type:i,pure:!0});let e=i;return e})();export{f as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m}from"./chunk-
|
|
1
|
+
import{a as m}from"./chunk-SJ45VMIG.js";import{Pa as c,Xa as f}from"./chunk-FXUDI3M6.js";var l=(()=>{let t=class t{constructor(r){this.translateService=r}transform(r,...i){try{let n=(new Date().getTime()-new Date(r).getTime())/1e3;if(n<1)return this.translateService.translate("now");let s={y:31536e3,mo:2592e3,w:604800,d:86400,h:3600,m:60,s:1};for(let a in s){let o=Math.floor(n/s[a]);if(o>0)return`${o}${this.translateService.translate(a)}`}return r}catch{return r}}};t.\u0275fac=function(i){return new(i||t)(c(m,16))},t.\u0275pipe=f({name:"timeAgo",type:t,pure:!0});let e=t;return e})();export{l as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ca as re}from"./chunk-K5BJ5DAO.js";import{$ as G,$e as I,Cf as _,De as W,Df as N,Ef as D,Hi as ee,L as w,Nd as x,Nf as k,Ze as U,_e as R,a as f,ae as v,b as y,ca as P,ci as J,da as K,di as B,g,gi as q,ih as M,ii as H,l as T,lh as $,li as X,mh as L,oh as j,ph as b,rh as z,sf as S,tf as l,uh as E,v as V,vh as F,xi as Y,yi as Z,zi as Q}from"./chunk-O4F37U67.js";var p="public",pe=(()=>{let O=class O{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=K(q),this.currentUserPermissions$=new T(null),this.permissionsCache$=new T(null),this.permissionProvider$=new T(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(h){this.loggingService.catch("Error in UserPermissionService constructor:",h)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(W.DEFAULT_VELT_CONTEXT))return!0;let s=this.contactService.getUserAccessFieldsByUserId(e);return s?r.every(i=>s.includes(i)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}organizationDetails(e){return g(this,null,function*(){try{let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(i&&i?.errorCode)return{errorCode:l.PERMISSION_DENIED,error:!0};if(i&&!i?.metadata)return{errorCode:l.DOES_NOT_EXIST,error:!0};let t=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},t),i?.metadata??{}));let o,c=i?.metadata?.veltFolderId;if(c)try{o=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:c,organizationId:r}}))?.folderIamConfig?.accessType}catch(a){this.loggingService.catch("Error fetching folder accessType for document:",a)}return o||(o=i?.docIamConfig?.accessType),{error:!1,accessType:o}}catch(i){return this.loggingService.catch("Error in UserPermissionService documentDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return g(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=yield this.validateResources(i),[o,c]=yield this.fetchUserPermissionsFromDB(i),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(i,t,o,c);if(Object.keys(n).length>0){if(!e)this.setCurrentUserPermissions(n);else if(this.permissionsCacheGeneration===r){let d=this.buildPermissionsCacheKey(e);d!==null&&this.requestKeyedPermissionsCache.set(d,JSON.parse(JSON.stringify(n)))}}return n}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return g(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?N(o):void 0}}let i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?N(i):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??""})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,h)=>i.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!h||u?.organizationId===h)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===l.PERMISSION_DENIED&&r&&t(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return g(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],i=[],t,o={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let u=n.status==="fulfilled"?n.value.errorCode??l.SOMETHING_WENT_WRONG:l.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:u};switch(d.type){case"organization":if(t=m,u===l.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":i.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,u={};return this.processRegularUserPermissions(u,s,t,o,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,i),this.processContextPermissions(u),u}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,i,t,o,c,a,n,d,h,u){for(let m of r)for(let C of m)C?.user?.userId&&(e[C.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,C,c,d,u)}),{documents:this.buildDocumentPermissions(i,C,a,h,u),organization:{[t]:this.buildOrganizationPermission(o,C,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,h=(s?.length??0)>0,u=(i?.length??0)>0;if(!d&&!h&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(t.errorCode,"organization"),errorCode:t.errorCode})),h){e[n].folders||(e[n].folders={});for(let m of s)e[n].folders[m.id]||(e[n].folders[m.id]=f({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:o[m.id]??a??p}))}if(u){e[n].documents||(e[n].documents={});for(let m of i)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:c[m.id]??a??p}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case l.DOES_NOT_EXIST:return`${r} does not exist`;case l.PERMISSION_DENIED:return`User does not have access to ${r}`;case l.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildDocumentPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?S.VIEWER:S.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??S.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===S.VIEWER||t?.[o]?.organization?.[e]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===S.VIEWER||t?.[o]?.folders?.[r]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===S.VIEWER||t?.[o]?.documents?.[s]?.errorCode===l.PERMISSION_DENIED)&&(i=!1)),i}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(w(M))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=N(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[D(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(V(e=>this.refactorPermissionsWithServerIds(e)),w(M))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return g(this,null,function*(){let e=k();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},t),{hasAccess:!1})):r.push(y(f({},t),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return g(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(i){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=k();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&j({input:s}).forEach(h=>{let u=JSON.stringify(h.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:t,userId:r})})}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return g(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return g(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),i=r?.resolveTimeout??6e4,t=yield $(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},i=r.endpointConfig?.url?.trim();if(i)return L(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(i){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:f({retryConfig:this.getPermissionProviderRetryConfig()},s?.access&&{currentContext:s})},getSdkProxy:t,userId:r})})}onResourceAccessRequired(o){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(e.forEach(n=>{let d=a?.find(h=>h.resourceId===n.resource.id&&h.type===n.resource.type&&h.userId===n.userId&&h.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};O.\u0275fac=function(r){return new(r||O)(P(X),P(Y),P(J),P(ee),P(Z),P(Q),P(H),P(x),P(B),P(re))},O.\u0275prov=G({token:O,factory:O.\u0275fac,providedIn:"root"});let A=O;return A})();export{pe as a};
|
|
1
|
+
import{ca as re}from"./chunk-RU3S5WM7.js";import{$ as G,$e as R,Ai as Q,Df as _,Ee as W,Ef as N,Ff as D,Ii as ee,L as w,Od as x,Of as k,_e as U,a as f,af as I,b as y,be as v,ca as P,da as K,di as J,ei as B,g,hi as q,jh as M,ji as H,l as T,mh as $,mi as X,nh as L,ph as j,qh as b,sh as z,tf as S,uf as l,v as V,vh as E,wh as F,yi as Y,zi as Z}from"./chunk-FXUDI3M6.js";var p="public",pe=(()=>{let O=class O{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=K(q),this.currentUserPermissions$=new T(null),this.permissionsCache$=new T(null),this.permissionProvider$=new T(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(h){this.loggingService.catch("Error in UserPermissionService constructor:",h)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(W.DEFAULT_VELT_CONTEXT))return!0;let s=this.contactService.getUserAccessFieldsByUserId(e);return s?r.every(i=>s.includes(i)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}organizationDetails(e){return g(this,null,function*(){try{let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(i&&i?.errorCode)return{errorCode:l.PERMISSION_DENIED,error:!0};if(i&&!i?.metadata)return{errorCode:l.DOES_NOT_EXIST,error:!0};let t=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},t),i?.metadata??{}));let o,c=i?.metadata?.veltFolderId;if(c)try{o=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:c,organizationId:r}}))?.folderIamConfig?.accessType}catch(a){this.loggingService.catch("Error fetching folder accessType for document:",a)}return o||(o=i?.docIamConfig?.accessType),{error:!1,accessType:o}}catch(i){return this.loggingService.catch("Error in UserPermissionService documentDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return g(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=yield this.validateResources(i),[o,c]=yield this.fetchUserPermissionsFromDB(i),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(i,t,o,c);if(Object.keys(n).length>0){if(!e)this.setCurrentUserPermissions(n);else if(this.permissionsCacheGeneration===r){let d=this.buildPermissionsCacheKey(e);d!==null&&this.requestKeyedPermissionsCache.set(d,JSON.parse(JSON.stringify(n)))}}return n}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return g(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?N(o):void 0}}let i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?N(i):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??""})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,h)=>i.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!h||u?.organizationId===h)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===l.PERMISSION_DENIED&&r&&t(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return g(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],i=[],t,o={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let u=n.status==="fulfilled"?n.value.errorCode??l.SOMETHING_WENT_WRONG:l.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:u};switch(d.type){case"organization":if(t=m,u===l.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":i.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,u={};return this.processRegularUserPermissions(u,s,t,o,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,i),this.processContextPermissions(u),u}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,i,t,o,c,a,n,d,h,u){for(let m of r)for(let C of m)C?.user?.userId&&(e[C.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,C,c,d,u)}),{documents:this.buildDocumentPermissions(i,C,a,h,u),organization:{[t]:this.buildOrganizationPermission(o,C,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,h=(s?.length??0)>0,u=(i?.length??0)>0;if(!d&&!h&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(t.errorCode,"organization"),errorCode:t.errorCode})),h){e[n].folders||(e[n].folders={});for(let m of s)e[n].folders[m.id]||(e[n].folders[m.id]=f({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:o[m.id]??a??p}))}if(u){e[n].documents||(e[n].documents={});for(let m of i)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:c[m.id]??a??p}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case l.DOES_NOT_EXIST:return`${r} does not exist`;case l.PERMISSION_DENIED:return`User does not have access to ${r}`;case l.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildDocumentPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?S.VIEWER:S.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??S.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===S.VIEWER||t?.[o]?.organization?.[e]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===S.VIEWER||t?.[o]?.folders?.[r]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===S.VIEWER||t?.[o]?.documents?.[s]?.errorCode===l.PERMISSION_DENIED)&&(i=!1)),i}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(w(M))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=N(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[D(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(V(e=>this.refactorPermissionsWithServerIds(e)),w(M))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return g(this,null,function*(){let e=k();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},t),{hasAccess:!1})):r.push(y(f({},t),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return g(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(i){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=k();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&j({input:s}).forEach(h=>{let u=JSON.stringify(h.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:t,userId:r})})}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return g(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return g(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),i=r?.resolveTimeout??6e4,t=yield $(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},i=r.endpointConfig?.url?.trim();if(i)return L(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(i){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:f({retryConfig:this.getPermissionProviderRetryConfig()},s?.access&&{currentContext:s})},getSdkProxy:t,userId:r})})}onResourceAccessRequired(o){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(e.forEach(n=>{let d=a?.find(h=>h.resourceId===n.resource.id&&h.type===n.resource.type&&h.userId===n.userId&&h.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};O.\u0275fac=function(r){return new(r||O)(P(X),P(Y),P(J),P(ee),P(Z),P(Q),P(H),P(x),P(B),P(re))},O.\u0275prov=G({token:O,factory:O.\u0275fac,providedIn:"root"});let A=O;return A})();export{pe as a};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@veltdev/sdk-staging",
|
|
3
|
-
"version": "6.0.0-beta.
|
|
3
|
+
"version": "6.0.0-beta.17",
|
|
4
4
|
"description": "Velt is an SDK to add collaborative features to your product within minutes. Example: Comments like Figma, Frame.io, Google docs or sheets, Recording like Loom, Huddles like Slack and much more.",
|
|
5
5
|
"homepage": "https://velt.dev",
|
|
6
6
|
"keywords": [
|