@veltdev/sdk-dev 6.0.17-beta.1 → 6.0.18-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/app/models/data/comment-resolver.data.model.d.ts +23 -0
  2. package/app/models/element/comment-element.model.d.ts +2 -2
  3. package/{chunk-F5REFWTQ.js → chunk-2IJ3Z5ZV.js} +1 -1
  4. package/{chunk-5H4ODM5U.js → chunk-2NGUPIJA.js} +1 -1
  5. package/{chunk-D24LAR5L.js → chunk-3IPAYZ7Y.js} +1 -1
  6. package/{chunk-FFTR7QJM.js → chunk-4I63DKJ7.js} +1 -1
  7. package/{chunk-KHL24R7O.js → chunk-4YYL5LBM.js} +1 -1
  8. package/{chunk-44HAZKIE.js → chunk-6TEVC4VB.js} +1 -1
  9. package/{chunk-BB2UXAYE.js → chunk-6YDKDS43.js} +1 -1
  10. package/chunk-76EHFLIO.js +1 -0
  11. package/{chunk-AWSU4IMS.js → chunk-BDVYEZ5H.js} +1 -1
  12. package/{chunk-DFQFM4NV.js → chunk-BKZUXK5Q.js} +1 -1
  13. package/{chunk-ZPO5AK7X.js → chunk-BOHOH3YV.js} +1 -1
  14. package/{chunk-RGBU7P5H.js → chunk-D6IQX3MS.js} +1 -1
  15. package/chunk-DR75AZG3.js +1 -0
  16. package/{chunk-HEFEC6O6.js → chunk-EVKWK3QF.js} +1 -1
  17. package/{chunk-MVVXZ2D6.js → chunk-FL7TUF6U.js} +1 -1
  18. package/{chunk-2BXOD5Z7.js → chunk-GXA7WFCW.js} +1 -1
  19. package/{chunk-FEA5HRMI.js → chunk-HKOM6NRJ.js} +1 -1
  20. package/{chunk-XZD6KKXD.js → chunk-JFPFA27E.js} +1 -1
  21. package/{chunk-VECW5ME3.js → chunk-JPR7TB3V.js} +1 -1
  22. package/chunk-LFLSU76Z.js +1 -0
  23. package/{chunk-LEIUFK3K.js → chunk-MIPUERB4.js} +1 -1
  24. package/chunk-MV36YVGA.js +174 -0
  25. package/{chunk-NSGBIR4C.js → chunk-NXVDUKNP.js} +1 -1
  26. package/{chunk-ND3RYLBW.js → chunk-P3UR2XTS.js} +1 -1
  27. package/{chunk-QZ5UHEP2.js → chunk-PKCY7NTA.js} +1 -1
  28. package/chunk-RBD735AI.js +1 -0
  29. package/{chunk-IUD3QEEM.js → chunk-T7KP622G.js} +1 -1
  30. package/{chunk-CYAQOX2W.js → chunk-TQYZX2M7.js} +1 -1
  31. package/{chunk-FPEVLQAP.js → chunk-TT7PKTGG.js} +1 -1
  32. package/{chunk-UCURXRPI.js → chunk-TZAGYSHE.js} +1 -1
  33. package/{chunk-BTNNHMUJ.js → chunk-UV3WG5EA.js} +1 -1
  34. package/{chunk-OLHFUO6O.js → chunk-VXHKBDMP.js} +1 -1
  35. package/chunk-WN7NM6YW.js +1 -0
  36. package/{chunk-6P3LPEPY.js → chunk-XMTWJMU7.js} +1 -1
  37. package/{chunk-SKNIB72F.js → chunk-YFUTJBEE.js} +1 -1
  38. package/package.json +1 -1
  39. package/velt-activity-log.js +1 -1
  40. package/velt-area.js +1 -1
  41. package/velt-arrow.js +1 -1
  42. package/velt-comment.js +6 -6
  43. package/velt-crdt.js +1 -1
  44. package/velt-cursor.js +1 -1
  45. package/velt-huddle.js +1 -1
  46. package/velt-live-state-sync.js +1 -1
  47. package/velt-notification.js +1 -1
  48. package/velt-portable.js +1 -1
  49. package/velt-presence.js +1 -1
  50. package/velt-reaction.js +1 -1
  51. package/velt-recorder.js +1 -1
  52. package/velt-rewriter.js +1 -1
  53. package/velt-selection.js +1 -1
  54. package/velt-tag.js +1 -1
  55. package/velt-user-invite.js +1 -1
  56. package/velt-user-request.js +1 -1
  57. package/velt-video-player.js +1 -1
  58. package/velt-views.js +1 -1
  59. package/velt.js +3 -3
  60. package/chunk-5ZUX3AU3.js +0 -1
  61. package/chunk-A52PJCIA.js +0 -1
  62. package/chunk-B3U3OLF6.js +0 -1
  63. package/chunk-EPQLN2EE.js +0 -1
  64. package/chunk-SMANT45B.js +0 -1
  65. package/chunk-TAGMM5ED.js +0 -174
@@ -0,0 +1 @@
1
+ import{$d as ae,$e as ht,$f as Qt,$h as X,Ag as ft,Ai as Ue,Aj as xi,B as vi,Bi as Dt,Bj as Nt,Cg as St,Ci as zi,Cj as Wi,D as fi,Dj as _t,E as Ie,Ei as ve,Ej as Hi,Fj as Pt,G as lt,Gi as Ot,Gj as Gi,He as h,Hg as he,I as Si,J as Ii,Je as w,Ji as Ct,Jj as $t,K as $e,Ke as Je,Kg as et,Kj as tt,Le as Ke,Li as pt,M as q,Mj as H,N as Ei,O as Ai,Oe as Ri,Of as Ui,Oj as qi,Pi as ue,Pj as Ae,Qd as ze,Qf as Oe,Qg as Yt,Ri as ki,Uf as ut,V as se,Xe as Ti,Y as dt,Yd as Jt,Yf as we,Zd as N,Ze as yi,Zf as Xe,_d as Y,_e as ce,_f as Ce,a as S,af as j,ag as Be,ah as ke,ai as te,b as L,ba as F,bf as ye,bg as Ee,bh as It,bj as ji,c as at,cf as x,ch as Et,ci as G,df as Qe,di as J,ea as T,ee as E,ef as Ye,ei as Ni,fa as Le,ff as W,fj as Ne,g as A,gf as Ze,gi as _i,gj as oe,h as ui,hf as re,hi as Pi,hj as B,i as Te,if as Di,ii as At,ij as _e,jf as le,k as gi,kf as Oi,ki as be,l as P,lf as ne,mg as gt,mi as Rt,mj as xe,ne as Kt,ng as mt,ni as je,of as Ci,oi as Tt,p as ct,pf as pi,pi as Zt,qi as yt,r as $,ri as $i,sg as b,si as Li,tf as de,ti as Fi,tj as bt,uf as De,v as k,vg as vt,vi as wi,w as Ve,wi as Bi,x as mi,xe as Fe,xi as Mi,yf as bi,yi as Vi,yj as ge,zi as v,zj as Ut}from"./chunk-MV36YVGA.js";function Ji(I,c){let z=gt(I?.annotationData);if(z&&c&&typeof c=="object"){c.visibility=z;let t=Object.values(I?.annotationData?.subscribedUsers||{}).map(i=>i?.user?.userId).filter(i=>!!i),e=mt(I?.annotationData,t);e.length&&(c.deniedForYouUsers=[...new Set([...c.deniedForYouUsers??[],...e])])}}var We={presence:{channelFeature:"presence",materialize:"map"},allPresence:{channelFeature:"presence",materialize:"map"},userNotificationIndex:{channelFeature:"notificationIndex",materialize:"doc",crossOrg:!0},allUserNotifications:{channelFeature:"notification",materialize:"map"},allComments:{channelFeature:"comment",materialize:"map"},allReactions:{channelFeature:"reaction",materialize:"map"},allLastActivityTimestamp:{channelFeature:"lastActivityTimestamp",materialize:"map"},allLastNotificationTimestamp:{channelFeature:"lastNotificationTimestamp",materialize:"map"},allDocumentViews:{channelFeature:"documentViews",materialize:"map"},allCrdtSyncPresence:{channelFeature:"crdtSyncPresence",materialize:"map"},allCrdtPresence:{channelFeature:"crdtPresence",materialize:"map"},crdtSyncPresence:{channelFeature:"crdtSyncPresence",materialize:"map"},crdtPresence:{channelFeature:"crdtPresence",materialize:"map"}},ln="allComments",dn="allReactions",hn="allLastActivityTimestamp",un="allDocumentViews",gn="allLastNotificationTimestamp",Xt={docNotification:{scope:"doc"},userNotification:{scope:"user"},comment:{scope:"doc"}};function Ki(I){return I in Xt}var ei={userNotificationViews:[{op:"markNotificationRead",scope:"user",verb:"update",sendsNoRowBody:!0}],docNotificationViews:[{op:"updateNotification",scope:"user",verb:"update",payloadFields:["views"]}],userNotification:[{op:"deleteNotification",scope:"user",verb:"delete"}],comment:[{op:"addComment",scope:"doc",verb:"set",formatData:!0,notificationData:!0},{op:"editComment",scope:"doc",verb:"update",formatData:!0},{op:"deleteComment",scope:"doc",verb:"delete",notificationData:!0}],reaction:[{op:"addReaction",scope:"doc",verb:"set",formatData:!0},{op:"editReaction",scope:"doc",verb:"update",formatData:!0},{op:"deleteReaction",scope:"doc",verb:"delete"}],documentViews:[{op:"recordDocumentView",scope:"doc",verb:"update",sendsNoRowBody:!0}]},Tr=[...Object.keys(We),...Object.keys(ei)];function Qi(I){return Tr.includes(I)}function Lt(I){return I in We}function it(I,c){return ei[I]?.find(z=>z.verb===c)}function Yi(I){return(ei[I]?.length??0)>0}var yr={comment:"comment",reaction:"reaction",documentViews:"documentViews",userNotificationViews:"notification",docNotificationViews:"notification",userNotification:"notification",crdtSyncPresence:"crdtSyncPresence",crdtPresence:"crdtPresence"};function rt(I){return We[I]?.channelFeature??yr[I]??I}var Dr=new Set(["crdtSyncPresence","allCrdtSyncPresence","crdtPresence","allCrdtPresence"]);function ti(I){return Dr.has(I)}var Or=new Set(["presence","crdtSyncPresence","crdtPresence"]);function ii(I){return Or.has(I)}function Zi(I,c){let z=We[I],t=rt(I),e=_t(t);if(!e||!c.apiKey)return null;let i=String(c.apiKey);switch(e.scope){case"doc":{if(!c.organizationId||!c.documentId)return null;let r=ti(I);return r&&(c.instanceId===void 0||c.instanceId===null||c.instanceId==="")?null:S({scope:"doc",feature:t,apiKey:i,organizationId:String(c.organizationId),documentId:String(c.documentId)},r?{instanceId:String(c.instanceId)}:{})}case"user":return!c.userIdHash||z&&!z.crossOrg&&!c.organizationId?null:L(S({scope:"user",feature:t,apiKey:i},!z?.crossOrg&&c.organizationId?{organizationId:String(c.organizationId)}:{}),{userIdHash:String(c.userIdHash)});case"org":return c.organizationId?{scope:"org",feature:t,apiKey:i,organizationId:String(c.organizationId)}:null;default:return null}}function Xi(I){if(!I||typeof I!="object")return!1;let c=I;return c.ok?!1:c.code==="unimplemented"?!0:c.code==="invalid-argument"&&/^unsupported operation\b/i.test(String(c.message??""))}function Cr({existing:I,folderId:c,veltFolderId:z}){return I?.clientDocumentId&&!I?.errorCode?I?.folderId&&(I?.folderId!==c||I?.veltFolderId!==z)?{allow:!1,refusal:"folder-mismatch"}:I?.folderId===c?{allow:!0,folderId:c,veltFolderId:z}:{allow:!1,refusal:"not-in-folder"}:{allow:!0,folderId:c,veltFolderId:z}}function Ft(I,c,z){return I==="folder-mismatch"?`Folder id mismatch for document ${c??""}`:`Document ${c??""} is not in the folder ${z??""}`}function ri({folderId:I,clientOrganizationId:c}){return{folderId:I,clientOrganizationId:c,parentFolderId:"root"}}function ni(I){let c=new Ci;return I.clientMetadata&&(c=S(S({},I.clientMetadata),c)),c.apiKey=I.apiKey,c.documentId=I.documentId,c.clientDocumentId=I.clientDocumentId,c.organizationId=I.organizationId,c.clientOrganizationId=I.clientOrganizationId,c.pageInfo=I.pageInfo,c?.pageInfo?.deviceInfo&&delete c?.pageInfo?.deviceInfo,c}function oi({folderId:I,veltFolderId:c}){return!!(I&&c)}function si({metadata:I,folderId:c,veltFolderId:z,existing:t,cached:e}){let i=!0,r;if(c&&z){let n=Cr({existing:t,folderId:c,veltFolderId:z});n.allow?(I.folderId=n.folderId,I.veltFolderId=n.veltFolderId):(i=!1,r=n.refusal)}if(e){let n={};Object.entries(I).forEach(([s,a])=>{n[s]=a}),he(n,e)&&(i=!1)}return r?{metadata:I,write:i,refusal:r}:{metadata:I,write:i}}var wt=class{};function Bt(I){return{from:I?.from,visibilityConfig:I?.visibilityConfig,context:{accessFields:I?.context?.accessFields}}}function Mt(I,c,z){return A(this,null,function*(){let t=yield z.getDeniedForYouUsers({extraData:c});return t=z.applyNotificationVisibility({annotation:I,extraData:c,deniedForYouUsers:t}),t})}var me=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.commentAnnotationDataProvider$=new P(null),this.commentAnnotationById$=new P({}),this.fieldsToRemove=[],this.additionalFields=[],this.additionalSaveEvents=[],this.contextTextHeldByResolver=new Set,this.contextTextHandedOver=new Set,this.getCommentAnnotationById=r=>{try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.value?.[r]:void 0}catch(n){this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationById:",n);return}};try{this.loggingService.log("CommentAnnotationsResolverService initialized"),this.commentAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove),r.config?.additionalFields&&(this.additionalFields=r.config.additionalFields||[]),this.additionalSaveEvents=(r.config?.additionalSaveEvents||[]).map(n=>n?.event).filter(n=>!!n))})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService constructor:",r)}}resolverHoldsContextText(t){try{return!!t&&this.contextTextHeldByResolver.has(t)}catch(e){return this.loggingService.catch("Error in CommentAnnotationsResolverService resolverHoldsContextText:",e),!1}}recordContextTextHeld(t,{onlyAdd:e,handedOver:i=!1}){try{Object.entries(t??{}).forEach(([r,n])=>{je(n?.context)!==void 0?(this.contextTextHeldByResolver.add(r),i&&this.contextTextHandedOver.add(r)):!e&&!this.contextTextHandedOver.has(r)&&this.contextTextHeldByResolver.delete(r)})}catch(r){this.loggingService.catch("Error in CommentAnnotationsResolverService recordContextTextHeld:",r)}}getProvider(){try{let t=this.commentAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.contextTextHeldByResolver.clear(),this.contextTextHandedOver.clear(),this.commentAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in CommentAnnotationsResolverService ngOnDestroy:",t)}}resolveCommentAnnotations(r){return A(this,arguments,function*({request:t,uniqueId:e,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: resolveCommentAnnotations","color: green;"),!this.commentAnnotationDataProviderAvailable())return{};let n,s=!1,a=!1,o=()=>{n&&(clearTimeout(n),n=void 0,a=!0)};return new Promise((l,u)=>{n=setTimeout(()=>{if(!a){s=!0,o();let D=e||b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Comment annotation resolution timeout"),request:t}}),u(new Error("Comment annotation resolution timeout"))}},this.commentAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return o(),l({});let f={},d=[...new Set(t.commentAnnotationIds||[])],m=L(S({},t),{commentAnnotationIds:d});A(this,null,function*(){try{if(d.length>0||t.documentIds?.length||t.folderId){let D=e||b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:D,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:m}});let U=G(()=>g?.config?.getConfig?.url?J(g.config.getConfig.url,g.config.getConfig.headers,m,!0,g.config.getConfig.credentials):g?.get?.(m)||Promise.resolve(void 0),"getCommentAnnotations",this.retryGetConfig).then(y=>s?{}:(o(),y&&y.statusCode!==200?(this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),this.loggingService.catch(y?.message??"Error in CommentAnnotationsResolverService resolveCommentAnnotations:"),{}):y?.data)).catch(y=>{throw o(),y});try{f=(yield U)||{},this.recordContextTextHeld(f,{onlyAdd:!1}),this.analyticsService.trackEvent(v.Events.Resolver.COMMENT_RESOLVER_GET,{sourceMethod:"resolveCommentAnnotations",source:"sdk",commentAnnotationIds:d});let y={};Object.entries(f).forEach(([R,p])=>{let C=this.commentAnnotationById$.value?.[R];C?C&&JSON.stringify(C)!==JSON.stringify(p)&&(y[R]=p):y[R]=p}),Object.keys(y).length>0&&this.commentAnnotationById$.next(S(S({},this.commentAnnotationById$.getValue()),y)),this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:D,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),l(y)}catch(y){let R=e||b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:R,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:y,request:m}}),s||u(y),l(f)}}else o(),l({})}catch(D){o();let U=e||b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:D,request:m}}),u(D)}})})}catch(n){this.loggingService.catch("Error in CommentAnnotationsResolverService resolveCommentAnnotations:",n);let s=e||b();return this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:n,request:t}}),{}}})}saveCommentAnnotation(t,e){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: saveCommentAnnotation","color: green;");let i=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation save data provider not available");let r=e||b(),n=!!t.eventType&&Object.values(Y).includes(t.eventType);this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:j.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{request:t}});let s=JSON.parse(JSON.stringify(this.commentAnnotationById$.getValue()));this.commentAnnotationById$._value=S(S({},s),t.commentAnnotation);let a=this.getTargetComment(t.commentAnnotation,t.commentId),o=yield G(()=>{if(i?.config?.saveConfig?.url){let l={commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:a,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata};return J(i.config.saveConfig.url,i.config.saveConfig.headers,l,!1,i.config.saveConfig.credentials)}return i?.save?.({commentAnnotation:t.commentAnnotation,event:t.eventType,commentId:t.commentId,targetComment:a,metadata:Object.values(t.commentAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveCommentAnnotation",this.retrySaveConfig);return o&&o.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.commentAnnotationById$._value=s),this.loggingService.catch(o?.message??"Error in CommentAnnotationsResolverService saveCommentAnnotation:"),this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:j.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:o,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(n&&this.recordContextTextHeld(t.commentAnnotation,{onlyAdd:!0,handedOver:!0}),this.analyticsService.trackEvent(v.Events.Resolver.COMMENT_RESOLVER_SAVE,{sourceMethod:"saveCommentAnnotation",source:"sdk",commentAnnotationIds:Object.keys(t.commentAnnotation),eventType:t.eventType,commentId:t.commentId}),this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:j.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in CommentAnnotationsResolverService saveCommentAnnotation:",i);let r=e||b();return this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:j.SAVE_COMMENT_ANNOTATION,source:"internal",payload:{error:i,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}getTargetComment(t,e){if(!(!e||!t))for(let i of Object.values(t)){let r=i?.comments?.[e];if(r)return r}}deleteCommentAnnotation(t,e,i){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: deleteCommentAnnotation","color: green;");let r=this.getProvider();if(!this.commentAnnotationDataProviderAvailable())throw new Error("Comment annotation delete data provider not available");let n=this.commentAnnotationById$.getValue(),a=n?.[t]?.metadata??(e?te(e):void 0),o=a?S({apiKey:a.apiKey??null,documentId:a.documentId??null,organizationId:a.organizationId??null},a.folderId&&{folderId:a.folderId}):void 0,l=i||b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:j.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{commentAnnotationId:t.toString(),metadata:o}});let u=S({},n);delete u?.[t],this.commentAnnotationById$._value=u;let g=yield G(()=>{if(r?.config?.deleteConfig?.url){let f={commentAnnotationId:t.toString(),metadata:o,event:Y.COMMENT_ANNOTATION_DELETE};return J(r.config.deleteConfig.url,r.config.deleteConfig.headers,f,!1,r.config.deleteConfig.credentials)}return r?.delete?.({commentAnnotationId:t.toString(),metadata:o,event:Y.COMMENT_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteCommentAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.commentAnnotationById$._value=n),this.loggingService.catch(g?.message??"Error in CommentAnnotationsResolverService deleteCommentAnnotation:"),this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:j.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:g,commentAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.COMMENT_RESOLVER_DELETE,{sourceMethod:"deleteCommentAnnotation",source:"sdk",commentAnnotationId:t.toString()}),this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:j.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},commentAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){this.loggingService.warn("Error in CommentAnnotationsResolverService deleteCommentAnnotation:",r);let n=i||b(),s=e?te(e):void 0;return this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:j.DELETE_COMMENT_ANNOTATION,source:"internal",payload:{error:r,commentAnnotationId:t.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getCommentAnnotationsById$(){try{return this.commentAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling CommentAnnotationsResolverService FUNCTION: getCommentAnnotationsById$","color: green;"),this.commentAnnotationById$.asObservable()):$(void 0)}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getCommentAnnotationsById$:",t),$(void 0)}}getAnnotationById(t){try{return this.commentAnnotationDataProviderAvailable()?this.commentAnnotationById$.getValue()?.[t]:void 0}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService getAnnotationById:",e);return}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getAdditionalSaveEvents(){try{return this.additionalSaveEvents}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService getAdditionalSaveEvents:",t),this.additionalSaveEvents}}setCommentAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting comment annotation data provider");let e=t.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],r=[];if(i.forEach(({method:n,configKey:s})=>{let a=e?.[s]?.url,o=n in t&&typeof t[n]=="function";!a&&!o&&r.push(n)}),r.length>0){let n=`DataProviders.comment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${r.join(", ")}.`;this.loggingService.catch(n);return}else this.commentAnnotationDataProvider$.next(t)}}catch(e){this.loggingService.catch("Error in CommentAnnotationsResolverService setCommentAnnotationDataProvider:",e)}}commentAnnotationDataProviderAvailable(){try{return!!this.commentAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in CommentAnnotationsResolverService commentAnnotationDataProviderAvailable:",t),!1}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Ge=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.providers=new Map,this.retrySaveConfigs=new Map,this.retryDeleteConfigs=new Map,this.defaultRetryConfig={retryCount:0,retryDelay:0,revertOnFailure:!1};try{this.loggingService.log("AttachmentResolverService initialized")}catch(r){this.loggingService.catch("Error in AttachmentResolverService constructor:",r)}}getProvider(t){try{let e=t||"default";return this.providers.get(e)||void 0}catch(e){this.loggingService.catch("Error in AttachmentResolverService getProvider:",e);return}}getRetrySaveConfig(t){let e=t||"default";return this.retrySaveConfigs.get(e)||this.defaultRetryConfig}getRetryDeleteConfig(t){let e=t||"default";return this.retryDeleteConfigs.get(e)||this.defaultRetryConfig}makeAttachmentConfigBasedRequest(t,e,i,r,n){return A(this,null,function*(){try{let s=typeof e=="function"?yield e():e||{},a=new FormData;a.append("file",i);let o={attachment:{attachmentId:r.attachment.attachmentId,name:r.attachment.name,mimeType:r.attachment.mimeType},metadata:r.metadata,event:r.event};a.append("request",JSON.stringify(o));let l={};Object.entries(s).forEach(([f,d])=>{f.toLowerCase()!=="content-type"&&(l[f]=d)});let u=yield fetch(t,S({method:"POST",headers:l,body:a},n?{credentials:n}:{}));return u.ok?{data:(yield u.json())?.data??{},success:!0,statusCode:200}:(Jt.catch(`Error in makeAttachmentConfigBasedRequest: ${u.status} ${u.statusText}`),{data:{},success:!1,statusCode:u.status})}catch(s){return Jt.catch("Error in makeAttachmentConfigBasedRequest:",s),{data:{},success:!1,statusCode:500}}})}saveAttachment(t,e,i){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: saveAttachment","color: green;");let r=this.getProvider(i);if(!this.attachmentDataProviderAvailable(i))throw new Error("Attachment save data provider not available");let n=this.getRetrySaveConfig(i),s=e||b();this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:s,methodName:ye.SAVE_ATTACHMENT,source:"internal",payload:{request:t}});let a=yield G(()=>A(this,null,function*(){if(r?.config?.saveConfig?.url){let o=t.attachment,{file:l}=o,u=at(o,["file"]);return this.makeAttachmentConfigBasedRequest(r.config.saveConfig.url,r.config.saveConfig.headers,l,{attachment:u,event:t.eventType,metadata:t.attachment.metadata},r.config.saveConfig.credentials)}return r?.save?.({attachment:t.attachment,event:t.eventType,metadata:t.attachment.metadata})||Promise.resolve(void 0)}),"saveAttachment",n);if(a?.statusCode!==200){this.loggingService.catch(a?.message??"Error in AttachmentResolverService saveAttachment:"),this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:ye.SAVE_ATTACHMENT,source:"internal",payload:{error:a,request:t}});return}return this.analyticsService.trackEvent(v.Events.Resolver.ATTACHMENT_RESOLVER_SAVE,{sourceMethod:"saveAttachment",source:"sdk",attachmentId:t.attachment.attachmentId,eventType:t.eventType}),this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:s,methodName:ye.SAVE_ATTACHMENT,source:"internal",payload:{result:a,request:t}}),a}catch(r){this.loggingService.warn("Error in AttachmentResolverService saveAttachment:",r);let n=e||b();this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:ye.SAVE_ATTACHMENT,source:"internal",payload:{error:r,request:t}});return}})}deleteAttachment(n,s,a){return A(this,arguments,function*({attachmentId:t,metadata:e},i,r){try{this.loggingService.log("%c[WB] Calling AttachmentResolverService FUNCTION: deleteAttachment","color: green;");let o=this.getProvider(r);if(!this.attachmentDataProviderAvailable(r))throw new Error("Attachment delete data provider not available");let l=e?S({apiKey:e.apiKey??null,documentId:e.documentId??null,organizationId:e.organizationId??null},e.folderId&&{folderId:e.folderId}):void 0,u=this.getRetryDeleteConfig(r),g=i||b();this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:g,methodName:ye.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:t,metadata:l}});let f=yield G(()=>{if(o?.config?.deleteConfig?.url){let d={attachmentId:t,metadata:l,event:Y.ATTACHMENT_DELETE};return J(o.config.deleteConfig.url,o.config.deleteConfig.headers,d,!1,o.config.deleteConfig.credentials)}return o?.delete?.({attachmentId:t,metadata:l,event:Y.ATTACHMENT_DELETE})||Promise.resolve(void 0)},"deleteAttachment",u);return f?.statusCode!==200?(this.loggingService.catch(f?.message??"Error in AttachmentResolverService deleteAttachment:"),this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:g,methodName:ye.DELETE_ATTACHMENT,source:"internal",payload:{error:f,attachmentId:t,metadata:l}}),{revertOnFailure:u.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.ATTACHMENT_RESOLVER_DELETE,{sourceMethod:"deleteAttachment",source:"sdk",attachmentId:t}),this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:g,methodName:ye.DELETE_ATTACHMENT,source:"internal",payload:{result:{revertOnFailure:u.revertOnFailure,isSuccess:!0},attachmentId:t,metadata:l}}),{revertOnFailure:u.revertOnFailure,isSuccess:!0})}catch(o){this.loggingService.warn("Error in AttachmentResolverService deleteAttachment:",o);let l=this.getRetryDeleteConfig(r),u=i||b(),g=e?S({apiKey:e.apiKey??null,documentId:e.documentId??null,organizationId:e.organizationId??null},e.folderId&&{folderId:e.folderId}):void 0;return this.coreActionsService.triggerAction(E.ATTACHMENT_RESOLVER,{event:v.Events.Resolver.ATTACHMENT_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ye.DELETE_ATTACHMENT,source:"internal",payload:{error:o,attachmentId:t,metadata:g}}),{revertOnFailure:l.revertOnFailure,isSuccess:!0}}})}setAttachmentDataProvider(t,e="default"){try{if(t){this.loggingService.log(`Setting attachment data provider for scope: ${e}`);let i=t.config,r=[{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],n=[];if(r.forEach(({method:s,configKey:a})=>{let o=i?.[a]?.url,l=s in t&&typeof t[s]=="function";!o&&!l&&n.push(s)}),n.length>0){let s=`DataProviders.attachment is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${n.join(", ")}.`;this.loggingService.catch(s);return}else this.providers.set(e,t),t.config?.saveRetryConfig&&this.retrySaveConfigs.set(e,t.config.saveRetryConfig),t.config?.deleteRetryConfig&&this.retryDeleteConfigs.set(e,t.config.deleteRetryConfig)}}catch(i){this.loggingService.catch("Error in AttachmentResolverService setAttachmentDataProvider:",i)}}attachmentDataProviderAvailable(t){try{let e=t||"default";return this.providers.has(e)}catch(e){return this.loggingService.catch("Error in AttachmentResolverService attachmentDataProviderAvailable:",e),!1}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var zt=(()=>{let c=class c{constructor(t,e,i,r,n,s,a,o){this.loggingService=t,this.usersService=e,this.authService=i,this.functions=r,this.configService=n,this.commentAnnotationsResolverService=s,this.attachmentResolverService=a,this.coreActionsService=o,this.endpointsService=Le(xe),this.notificationActionTypeMap={[N.NEWLY_ADDED]:Y.COMMENT_ANNOTATION_ADD,[N.ADDED]:Y.COMMENT_ADD,[N.UPDATED]:Y.COMMENT_UPDATE,[N.DELETED]:Y.COMMENT_DELETE},this.additionalEventTypeMap={[N.STATUS_CHANGED]:ae.STATUS_CHANGE,[N.PRIORITY_CHANGED]:ae.PRIORITY_CHANGE,[N.ASSIGNED]:ae.ASSIGN,[N.ACCESS_MODE_CHANGED]:ae.ACCESS_MODE_CHANGE,[N.CUSTOM_LIST_CHANGED]:ae.CUSTOM_LIST_CHANGE,[N.APPROVED]:ae.APPROVE,[N.ACCEPTED]:ae.ACCEPT,[N.REJECTED]:ae.REJECT,[N.SUGGESTION_ACCEPTED]:ae.SUGGESTION_ACCEPT,[N.SUGGESTION_REJECTED]:ae.SUGGESTION_REJECT,[N.REACTION_ADDED]:ae.REACTION_ADD,[N.REACTION_DELETED]:ae.REACTION_DELETE,[N.SUBSCRIBED]:ae.SUBSCRIBE,[N.UNSUBSCRIBED]:ae.UNSUBSCRIBE}}setNotificationService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setNotificationService","color: green;"),this.notificationService=t}catch(e){this.loggingService.catch("Error in CommentUtilsService setNotificationService: ",e)}}setUserPermissionService(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: setUserPermissionService","color: green;"),this.userPermissionService=t}catch(e){this.loggingService.catch("Error in CommentUtilsService setUserPermissionService: ",e)}}getUserIdsToResolveFromComments(t){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: getUserIdsToResolveFromComments","color: green;");let e=new Set;for(let i of t){if(i?.from?.userId&&e.add(i?.from?.userId),i?.comments)for(let r of i?.comments){if(r?.from?.userId&&e.add(r?.from?.userId),r?.to)for(let n of r?.to)n?.userId&&e.add(n?.userId);if(r?.taggedUserContacts)for(let n of r?.taggedUserContacts)n?.userId&&e.add(n?.userId)}if(i?.assignedTo?.userId&&e.add(i?.assignedTo?.userId),i?.resolvedByUserId&&e.add(i?.resolvedByUserId),i?.suggestion?.resolvedBy?.userId&&e.add(i?.suggestion?.resolvedBy?.userId),i?.subscribedUsers)for(let r of Object.values(i?.subscribedUsers))r.user.userId&&e.add(r.user.userId);if(i?.unsubscribedUsers)for(let r of Object.values(i?.unsubscribedUsers))r.user.userId&&e.add(r.user.userId)}return Array.from(e)}catch(e){return this.loggingService.catch("Error in CommentUtilsService getUserIdsToResolveFromComments:",e),[]}}mergeCommentWithUser(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeCommentWithUser","color: green;"),t?.from?.userId){let e=this.usersService.getUserById(t?.from?.userId);e&&(t.from=e)}if(t?.suggestion?.resolvedBy?.userId){let e=this.usersService.getUserById(t?.suggestion?.resolvedBy?.userId);e&&(t.suggestion.resolvedBy=e)}if(t?.comments)for(let e of t?.comments){if(e?.from?.userId){let r=this.usersService.getUserById(e?.from?.userId);r&&(e.from=r)}e?.to&&(e.to=e?.to?.map(r=>{if(r?.userId){let n=this.usersService.getUserById(r?.userId);if(n)return S(S({},r),n)}return r})),e?.taggedUserContacts&&(e.taggedUserContacts=e?.taggedUserContacts?.map(r=>{if(r?.contact){let n=this.usersService.getUserById(r?.contact?.userId);n&&(r.contact=n,(n?.name||n?.email)&&(r.text=`@${n?.name||n?.email}`))}return r}));let i=e?.taggedUserContacts?.filter((r,n,s)=>s.findIndex(a=>a.text===r.text)===n)||[];i.sort((r,n)=>(n.text?.length||0)-(r.text?.length||0)),i.forEach(r=>{if(r?.text){let n=new RegExp(et(`{{${r.userId}}}`),"g");e.commentText?.includes(`@User ${r.userId}`)&&(n=new RegExp(et(`@User ${r.userId}`),"g")),e.commentText=e.commentText?.replaceAll(n,r.text),e.commentHtml=e.commentHtml?.replaceAll(n,r.text)}})}if(t?.assignedTo?.userId){let e=this.usersService.getUserById(t?.assignedTo?.userId);e&&(t.assignedTo=e)}if(t?.resolvedByUserId){let e=this.usersService.getUserById(t?.resolvedByUserId);e&&(t.resolvedByUser=e)}if(t?.subscribedUsers)for(let e of Object.values(t?.subscribedUsers)){let i=this.usersService.getUserById(e.user.userId);i&&t?.subscribedUsers?.id?.user&&(t.subscribedUsers.id.user=i)}if(t?.unsubscribedUsers)for(let e of Object.values(t?.unsubscribedUsers)){let i=this.usersService.getUserById(e.user.userId);i&&t?.unsubscribedUsers?.id?.user&&(t.unsubscribedUsers.id.user=i)}return t}catch(e){return this.loggingService.catch("Error in CommentUtilsService mergeCommentWithUser:",e),t}}formatCommentData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentData","color: green;"),t?.comments?.forEach(e=>{e?.commentText&&e?.commentText?.length>0&&(e.isCommentTextAvailable=!0)}),t?.viewedBy&&delete t.viewedBy,t?.unread!==void 0&&delete t.unread,t?.resolvedByUser!==void 0&&delete t.resolvedByUser,t?.comments&&t.comments.forEach(e=>{e?.reactionAnnotations&&delete e.reactionAnnotations}),this.usersService.userDataProviderAvailable()){if(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.assignedTo?.userId&&(t.assignedTo={userId:t.assignedTo.userId}),t?.subscribedUsers)for(let e of Object.keys(t?.subscribedUsers))t.subscribedUsers[e].user={userId:t?.subscribedUsers[e].user.userId};if(t?.unsubscribedUsers)for(let e of Object.keys(t?.unsubscribedUsers))t.unsubscribedUsers[e].user={userId:t?.unsubscribedUsers[e].user.userId};t?.suggestion?.resolvedBy?.userId&&(t.suggestion.resolvedBy={userId:t.suggestion.resolvedBy.userId})}return t?.comments&&(t.comments=t?.comments?.map(e=>this.formatCommentThreadData(e))),t}catch(e){return this.loggingService.catch("Error in CommentUtilsService formatCommentData:",e),t}}mergeStrippedDataWithCommentAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeStrippedDataWithCommentAnnotations","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let e=this.commentAnnotationsResolverService.getAnnotationById(t?.annotationId),i=this.attachmentResolverService.attachmentDataProviderAvailable(),r=this.commentAnnotationsResolverService.getFieldsToRemove();if(e){t?.comments?.forEach(s=>{let a=e?.comments?.[s?.commentId];if(a){s.commentHtml=a?.commentHtml,s.commentText=a?.commentText;let o=a?.attachments;i&&o&&s.attachments?.forEach(l=>{let u=l?.attachmentId;o?.[u]&&(l.name=o?.[u]?.name,l.url=o?.[u]?.url)})}}),e?.targetTextRange?.text&&t?.targetTextRange&&(t.targetTextRange.text=e?.targetTextRange?.text),r?.length>0&&r.forEach(s=>{e?.[s]&&(t[s]=e[s])});let n=je(e?.context);n!==void 0&&!r?.includes("context")&&Zt(t,n)}return t}catch(e){return this.loggingService.catch("Error in CommentUtilsService mergeStrippedDataWithCommentAnnotations:",e),t}}mergeLocationWithCommentAnnotations(t,e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: mergeLocationWithCommentAnnotations","color: green;");let i=t?.location?.id,r=t?.metadata?.documentId;if(!i||!r)return t;let n=e?.[r]?.[i];return n&&(t.location=n?.location),t}catch(i){return this.loggingService.catch("Error in CommentUtilsService mergeLocationWithCommentAnnotations:",i),t}}isCommentsDataChanged(t,e){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: isCommentsDataChanged","color: green;");let i=this.commentAnnotationsResolverService.getCommentAnnotationById(e);return i?!he(t,i):!0}catch(i){return this.loggingService.catch("Error in CommentUtilsService isCommentsDataChanged:",i),!0}}stripCommentsFromAnnotationData({comment:t}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentsFromAnnotationData","color: green;");let e=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable();if(!e)return t;let i=this.attachmentResolverService.attachmentDataProviderAvailable(),r=new yi;if(Object.assign(r,t),r.isCommentResolverUsed=e,i){let n=r.attachments?.map(s=>(s.isAttachmentResolverUsed=!0,delete s?.name,delete s?.url,s));r.attachments=n}return delete r?.commentHtml,delete r?.commentText,r}catch(e){return this.loggingService.catch("Error in CommentUtilsService stripCommentsFromAnnotationData:",e),t}}resolveTaggedUserEmails(t){return A(this,null,function*(){try{let e=new Set;if(t.comments?.forEach(i=>{i.taggedUserContacts?.forEach(r=>{r?.contact?.email&&!r?.userId&&e.add(r.contact.email)}),i.to?.forEach(r=>{r?.email&&!r?.userId&&e.add(r.email)})}),e.size>0){let i=b();this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:ce.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:Array.from(e)}});let r=yield this.usersService.resolveUserIdsByEmail({emails:Array.from(e),uniqueId:i});Object.keys(r).length>0&&t.comments?.forEach(n=>{n.taggedUserContacts?.forEach(s=>{if(s?.contact?.email&&!s?.userId){let a=r[s.contact.email];if(a){let o=s.text;if(o){let l=et(o),u=new RegExp(l,"g");n.commentText&&(n.commentText=n.commentText.replace(u,`{{${a}}}`)),n.commentHtml&&(n.commentHtml=n.commentHtml.replace(u,`{{${a}}}`))}s.userId=a,s.contact.userId=a,delete s.contact?.email,delete s.contact?.visibility,s.text=""}}}),n.to=n.to?.map(s=>{if(s?.email&&!s?.userId){let a=r[s.email];if(a)return delete s?.email,delete s?.visibility,L(S({},s),{userId:a})}return s})})}return t}catch(e){return this.loggingService.catch("Error in CommentUtilsService resolveTaggedUserEmails:",e),t}})}stripCommentAnnotationData(r){return A(this,arguments,function*({data:t,actionType:e,commentId:i}){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: stripCommentAnnotationData","color: green;"),t=yield this.resolveTaggedUserEmails(t),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let n=this.attachmentResolverService.attachmentDataProviderAvailable(),s=this.commentAnnotationsResolverService.getFieldsToRemove(),a=this.commentAnnotationsResolverService.getAdditionalFields(),o,l;e&&(o=this.notificationActionTypeMap?.[e],l=this.additionalEventTypeMap?.[e]);let u=this.commentAnnotationsResolverService.getAdditionalSaveEvents(),g=Array.isArray(u)?u:[],f={},d=null,m=!1;if(t&&t.annotationId){let Q=t.annotationId;if(f[Q]=S(S(S(S({annotationId:Q,metadata:te(t.metadata??{}),comments:{}},t?.from&&{from:t?.from}),t?.assignedTo&&{assignedTo:t?.assignedTo}),t?.resolvedByUserId&&{resolvedByUserId:t?.resolvedByUserId}),t?.targetTextRange?.text&&{targetTextRange:{text:t?.targetTextRange?.text}}),delete t?.targetTextRange?.text,s?.length>0&&s.forEach(M=>{t?.[M]&&(f[Q][M]=t[M],delete t[M])}),a?.length)for(let M of a)t?.[M]!==void 0&&(f[Q][M]=JSON.parse(JSON.stringify(t[M])));let V=je(t?.context);V!==void 0&&Zt(f[Q],V,{createContext:!0}),t.comments?.forEach(M=>{if(M.commentId){let pe;n&&(pe={},M.attachments?.forEach(st=>{pe[st.attachmentId]={attachmentId:st.attachmentId,name:st.name,url:st.url}})),f[Q].comments[M.commentId]=S(S(S(S(S(S({commentId:M.commentId},M?.commentHtml&&{commentHtml:M?.commentHtml}),M?.commentText&&{commentText:M?.commentText}),pe&&{attachments:pe}),M?.from&&{from:M?.from}),M?.to&&{to:M?.to}),M?.taggedUserContacts&&{taggedUserContacts:M?.taggedUserContacts})}}),m=this.isCommentsDataChanged(f[Q],Q);let ie=new Ti;Object.assign(ie,t),s?.length>0&&s.forEach(M=>{M in t||delete ie[M]}),ie.comments=t.comments?.map(M=>this.stripCommentsFromAnnotationData({comment:M}))||[],d=ie}let O=d?.comments?.find(Q=>Q.commentId===i);O?.isDraft&&(o=d?.comments?.length&&d?.comments?.length>0?Y.COMMENT_ADD:Y.COMMENT_ANNOTATION_ADD);let D=!!e&&!!this.notificationActionTypeMap?.[e],U=!!l&&!!d&&!D&&!O?.isDraft&&g.includes(l);U&&(o=l);let y=m&&(D||!!O?.isDraft),R=y||U,p=d?.annotationId,C=je(d?.context),_=C!==void 0&&!!p&&!y&&!!this.commentAnnotationsResolverService.getCommentAnnotationById(p)&&!this.commentAnnotationsResolverService.resolverHoldsContextText?.(p);return C!==void 0&&!_?Tt(d.context):_&&this.loggingService.log(`[PM-2026-09-29] legacy TipTap anchor kept in Velt for ${p} until a core comment save hands it to the resolver`),S({strippedData:R?f:null,originalData:d,eventType:o},_&&{veltCopyKeepsContextText:_})}catch(n){return this.loggingService.catch("Error in CommentAnnotationsResolverService stripCommentAnnotationData:",n),{strippedData:null,originalData:null}}})}formatCommentThreadData(t){try{if(this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: formatCommentThreadData","color: green;"),this.usersService.userDataProviderAvailable()){t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to&&(t.to=t?.to?.map(i=>i?.userId?{userId:i.userId}:i)),t?.taggedUserContacts&&(t.taggedUserContacts=t?.taggedUserContacts?.map(i=>i?.contact?.userId?L(S({},i),{contact:{userId:i.contact.userId}}):i));let e=t?.taggedUserContacts?.filter((i,r,n)=>n.findIndex(s=>s.text===i.text)===r)||[];e.sort((i,r)=>(r.text?.length||0)-(i.text?.length||0)),e.forEach(i=>{if(i?.text&&i?.contact?.userId){let r=new RegExp(et(i.text),"g");t.commentText=t.commentText?.replaceAll(r,n=>`{{${i.userId}}}`),t.commentHtml=t.commentHtml?.replaceAll(r,n=>`{{${i.userId}}}`)}}),e.forEach(i=>{i?.text&&i?.contact?.userId&&(i.text="")})}return t}catch(e){return this.loggingService.catch("Error in CommentUtilsService formatCommentThreadData:",e),t}}applyNotificationVisibility({annotation:t,extraData:e,deniedForYouUsers:i}){try{let r=gt(t);if(!r)return i??[];e&&typeof e=="object"&&(e.visibility=r);let n=Object.values(e?.annotationData?.subscribedUsers||{}).map(a=>a?.user?.userId).filter(a=>!!a),s=mt(t,n);return[...new Set([...i??[],...s])]}catch(r){return this.loggingService.catch("Error in CommentUtilsService applyNotificationVisibility:",r),i??[]}}getCommentNotificationDenialSteps(){return{getDeniedForYouUsers:t=>this.getDeniedForYouUsers(t),applyNotificationVisibility:t=>this.applyNotificationVisibility(t)}}isPermissionProviderUsed(){try{return!!this.userPermissionService?.isPermissionProviderAvailable()}catch(t){return this.loggingService.catch("Error in CommentUtilsService isPermissionProviderUsed:",t),!1}}getDeniedForYouUsers(e){return A(this,arguments,function*({extraData:t}){try{let i=Object.values(t?.annotationData?.subscribedUsers||{}).map(n=>n.user.userId)??[],r=[];if(this.userPermissionService?.isPermissionProviderAvailable()&&i.length){let n=t?.metadata?.clientDocumentId,s=t?.annotationData?.context?.access&&this.userPermissionService?.getIsContextEnabled()?t?.annotationData?.context?.access:null,a=[],o=t?.metadata?.folderId;i.forEach(g=>{if(a.push({userId:g,resource:S({id:n,type:De.DOCUMENT,source:de.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:s?{access:s}:void 0},o&&{parentFolderId:o})}),s){let f=JSON.stringify(s);a.push({userId:g,resource:{id:f,type:De.CONTEXT,source:de.SET_NOTIFICATIONS,organizationId:t?.metadata?.clientOrganizationId??"",context:{access:s}}})}});let l=b();this.coreActionsService.triggerAction(E.PERMISSION_PROVIDER,{event:v.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:de.SET_NOTIFICATIONS,uniqueId:l,timestamp:new Date().getTime(),source:"internal",payload:{requests:a}});let u=yield this.userPermissionService?.onResourceAccessRequired({requests:a,uniqueId:l,methodName:de.SET_NOTIFICATIONS});u?.success&&u?.data?.length&&u.data.forEach(g=>{g.hasAccess||r.push(g.userId)})}return r}catch(i){return this.loggingService.catch("Error in CommentUtilsService getDeniedForYouUsers:",i),[]}})}prepareCommentNotificationData(i){return A(this,arguments,function*({data:t,extraData:e}){if(!e)return;e=this.notificationService?.processNotificationData(e),e.annotationData=t;let r=e?.targetAnnotationData?.commentId;if(r){let n=t?.comments?.find(s=>s?.commentId===r);n&&(e.targetAnnotationData=n)}try{let n=yield this.stripCommentAnnotationData({data:e.annotationData,actionType:e?.actionType??N.NEWLY_ADDED});n?.originalData&&(e.annotationData=this.formatCommentData(n.originalData)),e?.targetAnnotationData&&(e.targetAnnotationData=this.formatCommentThreadData(this.stripCommentsFromAnnotationData({comment:e.targetAnnotationData})))}catch(n){this.loggingService.warn("Error in CommentUtilsService prepareCommentNotificationData:",n)}return this.stripCommentNotificationPayload(e)})}stripCommentNotificationPayload(t){if(!t||typeof t!="object")return t;try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let e=this.attachmentResolverService.attachmentDataProviderAvailable(),i=t.annotationData;if(i&&typeof i=="object"){let n=Array.isArray(i.comments)?i.comments.map(s=>this.stripCommentsFromAnnotationData({comment:s})):i.comments;t.annotationData=yt(L(S({},i),{comments:n}),{stripAttachmentFiles:e})}let r=t.targetAnnotationData;return r&&typeof r=="object"&&(t.targetAnnotationData=$i(this.stripCommentsFromAnnotationData({comment:r}),{stripAttachmentFiles:e})),this.deleteCommentTextBearingFields(t),t}catch(e){return this.loggingService.catch("Error in CommentUtilsService stripCommentNotificationPayload (failing closed):",e),this.failClosedCommentNotificationPayload(t)}}deleteCommentTextBearingFields(t){for(let e of Fi)delete t[e];for(let e of Object.keys(t))wi(e,t[e])&&delete t[e]}failClosedCommentNotificationPayload(t){try{let e=S({},t),i=e.annotationData;if(i&&typeof i=="object"){let n=i.subscribedUsers&&typeof i.subscribedUsers=="object"?Object.fromEntries(Object.entries(i.subscribedUsers).map(([s,a])=>[s,{user:Rt(a?.user,ut)}])):void 0;e.annotationData=S(S(S(S(S(S(S({},i.annotationId!==void 0?{annotationId:i.annotationId}:{}),i.metadata!==void 0?{metadata:i.metadata}:{}),i.from!==void 0?{from:Rt(i.from,ut)}:{}),i.assignedTo!==void 0?{assignedTo:Rt(i.assignedTo,ut)}:{}),n!==void 0?{subscribedUsers:n}:{}),Array.isArray(i.mentionedUserIds)?{mentionedUserIds:i.mentionedUserIds}:{}),Array.isArray(i.involvedUserIds)?{involvedUserIds:i.involvedUserIds}:{})}let r=e.targetAnnotationData;return r&&typeof r=="object"&&(e.targetAnnotationData=r.commentId!==void 0?{commentId:r.commentId}:{}),this.deleteCommentTextBearingFields(e),e}catch{return{notificationSource:t?.notificationSource,actionType:t?.actionType}}}handleCommentEncryption(s){return A(this,arguments,function*({data:t,firestorePath:e,extraData:i,eventType:r,metadata:n}){try{this.loggingService.log("%c[WB] Calling CommentUtilsService FUNCTION: handleCommentEncryption","color: green;");let a=St(this.authService.getFirebaseConfig()?.firebaseOptions),o=Ue(this.functions,be({url:this.endpointsService.getSetEncryptedDataUrl(a),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),l=Bt(t);i=yield this.prepareCommentNotificationData({data:t,extraData:i});let u=Ut.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),g=yield Mt(l,i,this.getCommentNotificationDenialSteps()),f={path:e??"",data:t??{},dbId:u??"",notificationData:i||void 0,notificationURL:this.endpointsService.getNotificationsDbUrl(),feature:"comment",eventType:r??"PATCH",sdkVersion:ke(),deniedForYouUsers:g,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),isCommentResolverUsed:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),isSettingsConfigByOrganization:this.notificationService?.getSettingsConfigByOrganization(),isCrossOrganizationEnabled:this.notificationService?.getCrossOrganizationConfig()?.enabled,metadata:n},d=yield ft(f,this.authService.getUser()?.userId??"");yield o({veltData:d})}catch(a){this.loggingService.catch("Error in CommentUtilsService handleCommentEncryption:",a)}})}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K),T(Ae),T(ze),T(_e),T(me),T(Ge),T(H))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Re=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.reactionAnnotationDataProvider$=new P(null),this.reactionAnnotationById$=new P({}),this.fieldsToRemove=[],this.getReactionAnnotationById=r=>{try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.value?.[r]:void 0}catch(n){this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationById:",n);return}};try{this.loggingService.log("ReactionAnnotationsResolverService initialized"),this.reactionAnnotationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove||[]))})}catch(r){this.loggingService.catch("Error in ReactionAnnotationsResolverService constructor:",r)}}getProvider(){try{let t=this.reactionAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.reactionAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in ReactionAnnotationsResolverService ngOnDestroy:",t)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}resolveReactionAnnotations(r){return A(this,arguments,function*({request:t,uniqueId:e,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: resolveReactionAnnotations","color: green;"),!this.reactionAnnotationDataProviderAvailable())return{};let n,s=!1,a=!1,o=()=>{n&&(clearTimeout(n),n=void 0,a=!0)};return new Promise((l,u)=>{n=setTimeout(()=>{if(!a){s=!0,o();let D=e||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Reaction annotation resolution timeout"),request:t}}),u(new Error("Reaction annotation resolution timeout"))}},this.reactionAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return o(),l({});let f={},d=[...new Set(t.reactionAnnotationIds||[])],m=L(S({},t),{reactionAnnotationIds:d});A(this,null,function*(){try{if(d.length>0||t.documentIds?.length||t.folderId){let D=e||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:D,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:m}});let U=G(()=>g?.config?.getConfig?.url?J(g.config.getConfig.url,g.config.getConfig.headers,m,!0,g.config.getConfig.credentials):g?.get?.(m)||Promise.resolve(void 0),"getReactionAnnotations",this.retryGetConfig).then(y=>s?{}:(o(),y&&y.statusCode!==200?(this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),this.loggingService.catch(y?.message??"Error in ReactionAnnotationsResolverService resolveReactionAnnotations:"),{}):y?.data)).catch(y=>{throw o(),y});try{f=(yield U)||{},this.analyticsService.trackEvent(v.Events.Resolver.REACTION_RESOLVER_GET,{sourceMethod:"resolveReactionAnnotations",source:"sdk",reactionAnnotationIds:d});let y={};Object.entries(f).forEach(([R,p])=>{let C=this.reactionAnnotationById$.value?.[R];C?C&&JSON.stringify(C)!==JSON.stringify(p)&&(y[R]=p):y[R]=p}),Object.keys(y).length>0&&this.reactionAnnotationById$.next(S(S({},this.reactionAnnotationById$.getValue()),y)),this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:D,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),l(y)}catch(y){let R=e||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:R,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:y,request:m}}),s||u(y),l(f)}}else o(),l({})}catch(D){o();let U=e||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:D,request:m}}),u(D)}})})}catch(n){this.loggingService.catch("Error in ReactionAnnotationsResolverService resolveReactionAnnotations:",n);let s=e||b();return this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:n,request:t}}),{}}})}saveReactionAnnotation(t,e){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: saveReactionAnnotation","color: green;");let i=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation save data provider not available");let r=e||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:x.SAVE_REACTION_ANNOTATION,source:"internal",payload:{request:t}});let n=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue()));this.reactionAnnotationById$._value=S(S({},n),t);let s={reactionAnnotation:t,event:Y.REACTION_ADD,metadata:Object.values(t??{})?.[0]?.metadata},a=yield G(()=>i?.config?.saveConfig?.url?J(i.config.saveConfig.url,i.config.saveConfig.headers,s,!1,i.config.saveConfig.credentials):i?.save?.(s)||Promise.resolve(void 0),"saveReactionAnnotation",this.retrySaveConfig);return a&&a.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.reactionAnnotationById$._value=n),this.loggingService.catch(a?.message??"Error in ReactionAnnotationsResolverService saveReactionAnnotation:"),this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:x.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:a,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.REACTION_RESOLVER_SAVE,{sourceMethod:"saveReactionAnnotation",source:"sdk",reactionAnnotationIds:Object.keys(t),eventType:s.event}),this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:x.SAVE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ReactionAnnotationsResolverService saveReactionAnnotation:",i);let r=e||b();return this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:x.SAVE_REACTION_ANNOTATION,source:"internal",payload:{error:i,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteReactionAnnotation(t,e,i){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: deleteReactionAnnotation","color: green;");let r=this.getProvider();if(!this.reactionAnnotationDataProviderAvailable())throw new Error("Reaction annotation delete data provider not available");let n=JSON.parse(JSON.stringify(this.reactionAnnotationById$.getValue())),s=e??n?.[t]?.metadata,a=s?te(s):void 0,o=a?S({apiKey:a.apiKey??null,documentId:a.documentId??null,organizationId:a.organizationId??null},a.folderId&&{folderId:a.folderId}):void 0,l=i||b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:x.DELETE_REACTION_ANNOTATION,source:"internal",payload:{reactionAnnotationId:t.toString(),metadata:o}});let u=S({},n);delete u?.[t],this.reactionAnnotationById$._value=u;let g=yield G(()=>{if(r?.config?.deleteConfig?.url){let f={reactionAnnotationId:t.toString(),metadata:o,event:Y.REACTION_DELETE};return J(r.config.deleteConfig.url,r.config.deleteConfig.headers,f,!1,r.config.deleteConfig.credentials)}return r?.delete?.({reactionAnnotationId:t.toString(),metadata:o,event:Y.REACTION_DELETE})||Promise.resolve(void 0)},"deleteReactionAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.reactionAnnotationById$._value=n),this.loggingService.catch(g?.message??"Error in ReactionAnnotationsResolverService deleteReactionAnnotation:"),this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:x.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:g,reactionAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.REACTION_RESOLVER_DELETE,{sourceMethod:"deleteReactionAnnotation",source:"sdk",reactionAnnotationId:t.toString()}),this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:x.DELETE_REACTION_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},reactionAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){this.loggingService.warn("Error in ReactionAnnotationsResolverService deleteReactionAnnotation:",r);let n=i||b(),s=e?te(e):void 0;return this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:x.DELETE_REACTION_ANNOTATION,source:"internal",payload:{error:r,reactionAnnotationId:t.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getReactionAnnotationsById$(){try{return this.reactionAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ReactionAnnotationsResolverService FUNCTION: getReactionAnnotationsById$","color: green;"),this.reactionAnnotationById$.asObservable()):$(void 0)}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService getReactionAnnotationsById$:",t),$(void 0)}}getAnnotationById(t){try{return this.reactionAnnotationDataProviderAvailable()?this.reactionAnnotationById$.getValue()?.[t]:void 0}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService getAnnotationById:",e);return}}setReactionAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting reaction annotation data provider");let e=t.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],r=[];if(i.forEach(({method:n,configKey:s})=>{let a=e?.[s]?.url,o=n in t&&typeof t[n]=="function";!a&&!o&&r.push(n)}),r.length>0){let n=`DataProviders.reaction is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${r.join(", ")}.`;this.loggingService.catch(n);return}else this.reactionAnnotationDataProvider$.next(t)}}catch(e){this.loggingService.catch("Error in ReactionAnnotationsResolverService setReactionAnnotationDataProvider:",e)}}reactionAnnotationDataProviderAvailable(){try{return!!this.reactionAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ReactionAnnotationsResolverService reactionAnnotationDataProviderAvailable:",t),!1}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var kt=(()=>{let c=class c{constructor(t,e,i,r,n,s){this.loggingService=t,this.usersService=e,this.authService=i,this.functions=r,this.configService=n,this.reactionAnnotationsResolverService=s,this.endpointsService=Le(xe)}getUserIdsToResolveFromReactions(t){try{let e=new Set;for(let i of t)if(i?.from?.userId&&e.add(i?.from?.userId),i?.reactions?.length)for(let r of i?.reactions)r?.from?.userId&&e.add(r?.from?.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",e),[]}}handleReactionEncryption(r){return A(this,arguments,function*({data:t,firestorePath:e,eventType:i}){try{let n=St(this.authService.getFirebaseConfig()?.firebaseOptions),s=Ue(this.functions,be({url:this.endpointsService.getSetEncryptedDataUrl(n),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),a=Ut.getFirestoreProdDbName(this.configService.getApiKey()??"",this.authService.getFirebaseConfig()?.firebaseOptions),o=this.authService.getUser()?.userId??"",l={path:e??"",data:t??{},dbId:a??"",feature:"reaction",eventType:i??"PATCH",sdkVersion:ke()},u=yield ft(l,o);yield s({veltData:u})}catch(n){this.loggingService.catch("Error in handleReactionEncryption:",n)}})}mergeReactionWithUser(t){try{if(this.usersService.userDataProviderAvailable()){if(t?.from?.userId){let e=this.usersService.getUserById(t?.from?.userId);e&&(t.from=e)}if(t?.reactions?.length){for(let e of t?.reactions)if(e?.from?.userId){let i=this.usersService.getUserById(e?.from?.userId);i&&(e.from=i)}}}return t}catch(e){return this.loggingService.catch("Error in ReactionUtilsService mergeReactionWithUser:",e),t}}formatReactionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t.reactions=t?.reactions?.map(e=>(this.usersService.userDataProviderAvailable()&&e?.from?.userId&&(e.from={userId:e.from.userId}),e)),t}catch(e){return this.loggingService.catch("Error in ReactionUtilsService formatReactionData:",e),t}}isReactionDataChanged(t,e){try{this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: isReactionDataChanged","color: green;");let i=this.reactionAnnotationsResolverService.getReactionAnnotationById(e);return i?!he(t,i):!0}catch(i){return this.loggingService.catch("Error in ReactionUtilsService isReactionDataChanged:",i),!0}}stripReactionAnnotationData(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: stripReactionAnnotationData","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return{originalData:t,strippedData:null};let e={},i=this.reactionAnnotationsResolverService.getFieldsToRemove();if(t&&t.annotationId){let r=t.annotationId;if(e[r]=S({annotationId:r,metadata:te(t.metadata??{}),icon:t.icon},t?.from&&{from:t?.from}),i?.length>0)for(let s of i)t?.[s]!==void 0&&(e[r][s]=t[s],delete t[s]);if(!this.isReactionDataChanged(e[r],r))return{strippedData:null,originalData:t};delete t?.icon,t.isReactionResolverUsed=!0}return{strippedData:e,originalData:t}}catch(e){return this.loggingService.catch("Error in ReactionUtilsService stripReactionAnnotationData:",e),{strippedData:null,originalData:null}}}mergeStrippedDataWithReactionAnnotations(t){try{if(this.loggingService.log("%c[WB] Calling ReactionUtilsService FUNCTION: mergeStrippedDataWithReactionAnnotations","color: green;"),!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())return t;let e=this.reactionAnnotationsResolverService.getReactionAnnotationById(t?.annotationId);if(e){e.icon&&(t.icon=e.icon);let i=this.reactionAnnotationsResolverService.getFieldsToRemove();if(i?.length>0)for(let r of i)e?.[r]!==void 0&&(t[r]=e[r])}return t}catch(e){return this.loggingService.catch("Error in ReactionUtilsService mergeStrippedDataWithReactionAnnotations:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K),T(Ae),T(ze),T(_e),T(Re))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Pe=(()=>{let c=class c{constructor(t,e,i,r){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.attachmentResolverService=r,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.recorderAnnotationDataProvider$=new P(null),this.recorderAnnotationById$=new P({}),this.additionalFields=[],this.fieldsToRemove=[],this.uploadChunks=!1,this.getRecorderAnnotationById=n=>{try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.value?.[n]:void 0}catch(s){this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationById:",s);return}};try{this.loggingService.log("RecorderAnnotationsResolverService initialized"),this.recorderAnnotationDataProvider$.subscribe(n=>{n&&(n.config?.resolveTimeout&&(this.resolveTimeout=n.config.resolveTimeout),n.config?.saveRetryConfig&&(this.retrySaveConfig=n.config.saveRetryConfig),n.config?.deleteRetryConfig&&(this.retryDeleteConfig=n.config.deleteRetryConfig),n.config?.getRetryConfig&&(this.retryGetConfig=n.config.getRetryConfig),n.config?.additionalFields&&(this.additionalFields=n.config.additionalFields||[]),n.config?.fieldsToRemove&&(this.fieldsToRemove=n.config.fieldsToRemove||[]),this.uploadChunks=n.uploadChunks??!1)})}catch(n){this.loggingService.catch("Error in RecorderAnnotationsResolverService constructor:",n)}}getProvider(){try{let t=this.recorderAnnotationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService getProvider:",t);return}}ngOnDestroy(){try{this.recorderAnnotationById$.next({})}catch(t){this.loggingService.catch("Error in RecorderAnnotationsResolverService ngOnDestroy:",t)}}resolveRecorderAnnotations(r){return A(this,arguments,function*({request:t,uniqueId:e,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: resolveRecorderAnnotations","color: green;"),!this.recorderAnnotationDataProviderAvailable())return{};let n,s=!1,a=!1,o=()=>{n&&(clearTimeout(n),n=void 0,a=!0)};return new Promise((l,u)=>{n=setTimeout(()=>{if(!a){s=!0,o();let D=e||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:new Error("Recorder annotation resolution timeout"),request:t}}),u(new Error("Recorder annotation resolution timeout"))}},this.recorderAnnotationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return o(),l({});let f={},d=[...new Set(t.recorderAnnotationIds||[])],m=L(S({},t),{recorderAnnotationIds:d});A(this,null,function*(){try{if(d.length>0||t.documentIds?.length){let D=e||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:D,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{request:m}});let U=G(()=>g?.config?.getConfig?.url?J(g.config.getConfig.url,g.config.getConfig.headers,m,!0,g.config.getConfig.credentials):g?.get?.(m)||Promise.resolve(void 0),"getRecorderAnnotations",this.retryGetConfig).then(y=>s?{}:(o(),y&&y.statusCode!==200?(this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),this.loggingService.catch(y?.message??"Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:"),{}):y?.data)).catch(y=>{throw o(),y});try{f=(yield U)||{},this.analyticsService.trackEvent(v.Events.Resolver.RECORDER_RESOLVER_GET,{sourceMethod:"resolveRecorderAnnotations",source:"sdk",recorderAnnotationIds:d});let y={};Object.entries(f).forEach(([R,p])=>{let C=this.recorderAnnotationById$.value?.[R];C?C&&JSON.stringify(C)!==JSON.stringify(p)&&(y[R]=p):y[R]=p}),Object.keys(y).length>0&&this.recorderAnnotationById$.next(S(S({},this.recorderAnnotationById$.getValue()),y)),this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:D,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{result:y,request:m}}),l(y)}catch(y){let R=e||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:R,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:y,request:m}}),s||u(y),l(f)}}else o(),l({})}catch(D){o();let U=e||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:D,request:m}}),u(D)}})})}catch(n){this.loggingService.catch("Error in RecorderAnnotationsResolverService resolveRecorderAnnotations:",n);let s=e||b();return this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:i,source:"internal",payload:{error:n,request:t}}),{}}})}saveRecorderAnnotation(t,e){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: saveRecorderAnnotation","color: green;");let i=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation save data provider not available");let r=e||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:W.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{request:t}});let n=JSON.parse(JSON.stringify(this.recorderAnnotationById$.getValue()));this.recorderAnnotationById$._value=S(S({},n),t.recorderAnnotation);let s=yield G(()=>{if(i?.config?.saveConfig?.url){let a={recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata};return J(i.config.saveConfig.url,i.config.saveConfig.headers,a,!1,i.config.saveConfig.credentials)}return i?.save?.({recorderAnnotation:t.recorderAnnotation,event:t.eventType,metadata:Object.values(t.recorderAnnotation??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveRecorderAnnotation",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.recorderAnnotationById$._value=n),this.loggingService.catch(s?.message??"Error in RecorderAnnotationsResolverService saveRecorderAnnotation:"),this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:W.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:s,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.RECORDER_RESOLVER_SAVE,{sourceMethod:"saveRecorderAnnotation",source:"sdk",recorderAnnotationIds:Object.keys(t.recorderAnnotation),eventType:t.eventType}),this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:W.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in RecorderAnnotationsResolverService saveRecorderAnnotation:",i);let r=e||b();return this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:W.SAVE_RECORDER_ANNOTATION,source:"internal",payload:{error:i,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0}}})}deleteRecorderAnnotation(t,e,i){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: deleteRecorderAnnotation","color: green;");let r=this.getProvider();if(!this.recorderAnnotationDataProviderAvailable())throw new Error("Recorder annotation delete data provider not available");let n=this.recorderAnnotationById$.getValue(),a=n?.[t]?.metadata??(e?te(e):void 0),o=a?S({apiKey:a.apiKey??null,documentId:a.documentId??null,organizationId:a.organizationId??null},a.folderId&&{folderId:a.folderId}):void 0,l=i||b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:W.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{recorderAnnotationId:t.toString(),metadata:o}});let u=S({},n);delete u?.[t],this.recorderAnnotationById$._value=u;let g=yield G(()=>{if(r?.config?.deleteConfig?.url){let f={recorderAnnotationId:t.toString(),metadata:o,event:Y.RECORDER_ANNOTATION_DELETE};return J(r.config.deleteConfig.url,r.config.deleteConfig.headers,f,!1,r.config.deleteConfig.credentials)}return r?.delete?.({recorderAnnotationId:t.toString(),metadata:o,event:Y.RECORDER_ANNOTATION_DELETE})||Promise.resolve(void 0)},"deleteRecorderAnnotation",this.retryDeleteConfig);return g&&g.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.recorderAnnotationById$._value=n),this.loggingService.catch(g?.message??"Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:"),this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:W.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:g,recorderAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.RECORDER_RESOLVER_DELETE,{sourceMethod:"deleteRecorderAnnotation",source:"sdk",recorderAnnotationId:t.toString()}),this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:l,methodName:W.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},recorderAnnotationId:t.toString(),metadata:o}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){this.loggingService.warn("Error in RecorderAnnotationsResolverService deleteRecorderAnnotation:",r);let n=i||b(),s=e?te(e):void 0;return this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:W.DELETE_RECORDER_ANNOTATION,source:"internal",payload:{error:r,recorderAnnotationId:t.toString(),metadata:s}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getRecorderAnnotationsById$(){try{return this.recorderAnnotationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling RecorderAnnotationsResolverService FUNCTION: getRecorderAnnotationsById$","color: green;"),this.recorderAnnotationById$.asObservable()):$(void 0)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getRecorderAnnotationsById$:",t),$(void 0)}}getAnnotationById(t){try{return this.recorderAnnotationDataProviderAvailable()?this.recorderAnnotationById$.getValue()?.[t]:void 0}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService getAnnotationById:",e);return}}getAdditionalFields(){try{return this.additionalFields}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getAdditionalFields:",t),this.additionalFields}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService getFieldsToRemove:",t),this.fieldsToRemove}}shouldUploadChunks(){return this.uploadChunks}shouldUploadFullRecording(){return this.recorderAnnotationDataProviderAvailable()&&!this.uploadChunks}setRecorderAnnotationDataProvider(t){try{if(t){this.loggingService.log("Setting recorder annotation data provider");let e=t.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"},{method:"delete",configKey:"deleteConfig"}],r=[];if(i.forEach(({method:n,configKey:s})=>{let a=e?.[s]?.url,o=n in t&&typeof t[n]=="function";!a&&!o&&r.push(n)}),r.length>0){let n=`DataProviders.recorder is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${r.join(", ")}.`;this.loggingService.catch(n);return}else t.storage&&this.attachmentResolverService.setAttachmentDataProvider(t.storage,"recorder"),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")||this.loggingService.catch("Recording resolver is configured without storage resolver. Recording files (chunks, thumbnails) will be stored on Velt's infrastructure. Configure storage resolver for full self-hosting.",void 0,void 0,!0),this.recorderAnnotationDataProvider$.next(t)}}catch(e){this.loggingService.catch("Error in RecorderAnnotationsResolverService setRecorderAnnotationDataProvider:",e)}}recorderAnnotationDataProviderAvailable(){try{return!!this.recorderAnnotationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in RecorderAnnotationsResolverService recorderAnnotationDataProviderAvailable:",t),!1}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe),T(Ge))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var xt=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retrySaveConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.activityDataProvider$=new P(null),this.activityById$=new P({}),this.fieldsToRemove=[],this.getActivityById=r=>{try{return this.activityDataProviderAvailable()?this.activityById$.value?.[r]:void 0}catch(n){this.loggingService.catch("Error in ActivityResolverService getActivityById:",n);return}};try{this.loggingService.log("ActivityResolverService initialized"),this.activityDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.saveRetryConfig&&(this.retrySaveConfig=r.config.saveRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig),r.config?.fieldsToRemove&&(this.fieldsToRemove=r.config.fieldsToRemove))})}catch(r){this.loggingService.catch("Error in ActivityResolverService constructor:",r)}}getProvider(){try{let t=this.activityDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in ActivityResolverService getProvider:",t);return}}ngOnDestroy(){try{this.activityById$.next({})}catch(t){this.loggingService.catch("Error in ActivityResolverService ngOnDestroy:",t)}}resolveActivities(r){return A(this,arguments,function*({request:t,uniqueId:e,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: resolveActivities","color: green;"),!this.activityDataProviderAvailable())return{};let n,s=!1,a=!1,o=()=>{n&&(clearTimeout(n),n=void 0,a=!0)};return new Promise((l,u)=>{n=setTimeout(()=>{if(!a){s=!0,o();let D=e||b();this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:new Error("Activity resolution timeout"),request:t}}),u(new Error("Activity resolution timeout"))}},this.activityDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return o(),l({});let f={},d=[...new Set(t.activityIds||[])],m=L(S({},t),{activityIds:d});A(this,null,function*(){try{if(d.length>0||t.documentIds?.length){let D=e||b();this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:D,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{request:m}});let U=G(()=>g?.config?.getConfig?.url?J(g.config.getConfig.url,g.config.getConfig.headers,m,!0,g.config.getConfig.credentials):g?.get?.(m)||Promise.resolve(void 0),"resolveActivities",this.retryGetConfig).then(y=>s?{}:(o(),y&&y.statusCode!==200?(this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:D,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:y,request:m}}),this.loggingService.catch(y?.message??"Error in ActivityResolverService resolveActivities:"),{}):y?.data)).catch(y=>{throw o(),y});try{f=(yield U)||{},this.analyticsService.trackEvent(v.Events.Resolver.ACTIVITY_RESOLVER_GET,{sourceMethod:"resolveActivities",source:"sdk",activityIds:d});let y={};Object.entries(f).forEach(([R,p])=>{let C=this.activityById$.value?.[R];C?C&&JSON.stringify(C)!==JSON.stringify(p)&&(y[R]=p):y[R]=p}),Object.keys(y).length>0&&this.activityById$.next(S(S({},this.activityById$.getValue()),y)),this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:D,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{result:y,request:m}}),l(y)}catch(y){let R=e||b();this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:R,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:y,request:m}}),s||u(y),l(f)}}else o(),l({})}catch(D){o();let U=e||b();this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:U,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:D,request:m}}),u(D)}})})}catch(n){this.loggingService.catch("Error in ActivityResolverService resolveActivities:",n);let s=e||b();return this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:le.RESOLVE_ACTIVITIES,moduleName:i,source:"internal",payload:{error:n,request:t}}),{}}})}saveActivity(t,e){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: saveActivity","color: green;");let i=this.getProvider();if(!this.activityDataProviderAvailable())throw new Error("Activity save data provider not available");let r=e||b();this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_SAVE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:le.SAVE_ACTIVITY,source:"internal",payload:{request:t}});let n=JSON.parse(JSON.stringify(this.activityById$.getValue()));this.activityById$._value=S(S({},n),t.activity);let s=yield G(()=>{if(i?.config?.saveConfig?.url){let a={activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata};return J(i.config.saveConfig.url,i.config.saveConfig.headers,a,!1,i.config.saveConfig.credentials)}return i?.save?.({activity:t.activity,event:t.event,metadata:Object.values(t.activity??{})?.[0]?.metadata})||Promise.resolve(void 0)},"saveActivity",this.retrySaveConfig);return s&&s.statusCode!==200?(this.retrySaveConfig.revertOnFailure&&(this.activityById$._value=n),this.loggingService.catch(s?.message??"Error in ActivityResolverService saveActivity:"),this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:le.SAVE_ACTIVITY,source:"internal",payload:{error:s,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.ACTIVITY_RESOLVER_SAVE,{sourceMethod:"saveActivity",source:"sdk",activityIds:Object.keys(t.activity),event:t.event}),this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_SAVE_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:le.SAVE_ACTIVITY,source:"internal",payload:{result:{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0},request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!0})}catch(i){this.loggingService.warn("Error in ActivityResolverService saveActivity:",i);let r=e||b();return this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_SAVE_ERROR,timestamp:new Date().getTime(),uniqueId:r,methodName:le.SAVE_ACTIVITY,source:"internal",payload:{error:i,request:t}}),{revertOnFailure:this.retrySaveConfig.revertOnFailure,isSuccess:!1}}})}getActivitiesById$(){try{return this.activityDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling ActivityResolverService FUNCTION: getActivitiesById$","color: green;"),this.activityById$.asObservable()):$(void 0)}catch(t){return this.loggingService.catch("Error in ActivityResolverService getActivitiesById$:",t),$(void 0)}}getFieldsToRemove(){try{return this.fieldsToRemove}catch(t){return this.loggingService.catch("Error in ActivityResolverService getFieldsToRemove:",t),this.fieldsToRemove}}setActivityDataProvider(t){try{if(t){this.loggingService.log("Setting activity data provider");let e=t.config,i=[{method:"get",configKey:"getConfig"},{method:"save",configKey:"saveConfig"}],r=[];if(i.forEach(({method:n,configKey:s})=>{let a=e?.[s]?.url,o=n in t&&typeof t[n]=="function";!a&&!o&&r.push(n)}),r.length>0){let n=`DataProviders.activity is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${r.join(", ")}.`;this.loggingService.catch(n);return}else this.activityDataProvider$.next(t)}}catch(e){this.loggingService.catch("Error in ActivityResolverService setActivityDataProvider:",e)}}activityDataProviderAvailable(){try{return!!this.activityDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable:",t),!1}}activityDataProviderAvailable$(){try{return this.activityDataProvider$.pipe(k(t=>!!t),q())}catch(t){return this.loggingService.catch("Error in ActivityResolverService activityDataProviderAvailable$:",t),$(!1)}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Wt=(()=>{let c=class c{constructor(t,e,i,r,n,s,a,o,l){this.loggingService=t,this.usersService=e,this.commentUtilsService=i,this.reactionUtilsService=r,this.commentAnnotationsResolverService=n,this.reactionAnnotationsResolverService=s,this.recorderAnnotationsResolverService=a,this.activityResolverService=o,this.serviceBook=l}getActivityDisplayMessage(t){try{switch(t.featureType){case"comment":return this.getCommentDisplayMessage(t);case"recorder":return this.getRecorderDisplayMessage(t);case"reaction":return this.getReactionDisplayMessage(t);case"crdt":return this.getCrdtDisplayMessage(t);case"custom":return t.displayMessageTemplate&&t.displayMessageTemplateData?this.resolveTemplate(t.displayMessageTemplate,t.displayMessageTemplateData):"";default:return""}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getActivityDisplayMessage:",e),""}}resolveTemplate(t,e){try{return t.replace(/\{\{([\w.]+)\}\}/g,(i,r)=>{let n=r.split(".").reduce((s,a)=>{if(s!=null&&typeof s=="object")return s[a]},e);return n!=null?String(n):""})}catch(i){return this.loggingService.catch("Error in ActivityUtilsService resolveTemplate:",i),t}}buildActivityDataFromExtraData(t){try{let{feature:e,extraData:i}=t;if(!i?.actionType)return null;switch(e){case"comment":return this.buildCommentActivityData({commentAnnotation:i.annotationData,targetComment:i.targetAnnotationData,actionType:i.actionType,otherFields:i});case"recorder":return this.buildRecorderActivityData(i);case"reaction":return this.buildReactionActivityData(i);default:return null}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService buildActivityDataFromExtraData:",e),null}}stripActivityPII(t){return A(this,null,function*(){try{let e=JSON.parse(JSON.stringify(t));if(delete e.displayMessage,!this.usersService.userDataProviderAvailable())return{strippedActivity:e};e.actionUser?.userId&&(e.actionUser={userId:e.actionUser.userId}),e.changes&&this.stripUsersFromChanges(e.changes),e.displayMessageTemplateData&&this.stripUsersFromTemplateData(e.displayMessageTemplateData);let i=this.extractCommentChangesForResolver(e),r=this.extractFeatureEntityDataForResolver(e);yield this.stripFeatureSpecificPII(e);let n=this.extractActivityResolverData(e);return i&&(n?n.changes=S(S({},n.changes),i.changes):n=i),r&&(n?(r.entityData!==void 0&&(n.entityData=r.entityData),r.entityTargetData!==void 0&&(n.entityTargetData=r.entityTargetData)):n=r),n&&(e.isActivityResolverUsed=!0),{strippedActivity:e,activityResolverData:n}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService stripActivityPII:",e),{strippedActivity:t}}})}mergeActivityWithUser(t){try{if(!this.usersService.userDataProviderAvailable())return t;if(t=JSON.parse(JSON.stringify(t)),t.actionUser?.userId){let e=this.usersService.getUserById(t.actionUser.userId);e&&(t.actionUser=e)}return t.changes&&this.rehydrateUsersInChanges(t.changes),t.displayMessageTemplateData&&this.rehydrateUsersInTemplateData(t.displayMessageTemplateData),this.rehydrateFeatureSpecificUserData(t),t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithUser:",e),t}}mergeActivityWithFeatureData(t){try{switch(t.featureType){case"comment":return this.mergeActivityWithCommentAnnotationData(t);case"reaction":return this.mergeActivityWithReactionData(t);case"recorder":return this.mergeActivityWithRecorderData(t);default:return t}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithFeatureData:",e),t}}getUserIdsToResolveFromActivities(t){try{let e=new Set;for(let i of t){if(i.actionUser?.userId&&e.add(i.actionUser.userId),i.changes)for(let r of Object.values(i.changes))r&&(this.extractUserIdFromValue(r.from,e),this.extractUserIdFromValue(r.to,e));if(i.displayMessageTemplateData)for(let r of Object.values(i.displayMessageTemplateData))this.extractUserIdFromValue(r,e);this.extractFeatureSpecificUserIds(i,e)}return Array.from(e)}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getUserIdsToResolveFromActivities:",e),[]}}getEntityIdsToResolveFromActivities(t,e){try{let i=new Set;for(let r of t)if(!(e&&r.featureType!==e))switch(r.featureType){case"comment":case"reaction":case"recorder":r.targetEntityId&&i.add(r.targetEntityId);break}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ActivityUtilsService getEntityIdsToResolveFromActivities:",i),[]}}stripFeatureSpecificPII(t){return A(this,null,function*(){try{switch(t.featureType){case"comment":yield this.stripCommentPII(t);break;case"reaction":this.stripReactionPII(t);break;case"recorder":this.stripRecorderPII(t);break}}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripFeatureSpecificPII:",e)}})}extractActivityResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return;let e={id:t.id},i=!1,r=this.activityResolverService.getFieldsToRemove();for(let n of r)n in t&&t[n]!==void 0&&(e[n]=t[n],delete t[n],i=!0);return t.metadata&&(e.metadata=te(t.metadata)),i?e:void 0}catch(e){this.loggingService.catch("Error in ActivityUtilsService extractActivityResolverData:",e);return}}extractCommentChangesForResolver(t){try{return!this.activityResolverService.activityDataProviderAvailable()||t.featureType!=="comment"||!t.changes?.commentText?void 0:{id:t.id,changes:{commentText:t.changes.commentText},metadata:t.metadata?te(t.metadata):void 0}}catch(e){this.loggingService.catch("Error in ActivityUtilsService extractCommentChangesForResolver:",e);return}}extractFeatureEntityDataForResolver(t){try{if(!this.activityResolverService.activityDataProviderAvailable()||!t.entityData)return;let e=t.featureType==="recorder"&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),i=t.featureType==="reaction"&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable();if(!e&&!i)return;let r={id:t.id,metadata:t.metadata?te(t.metadata):void 0},n=JSON.parse(JSON.stringify(t.entityData));if(e){let s=this.serviceBook.get(ue)?.stripRecorderAnnotationData({data:n});if(s?.strippedData){let a=Object.keys(s.strippedData)[0];a&&(r.entityData=s.strippedData[a])}}if(i){let s=this.reactionUtilsService.stripReactionAnnotationData(n);if(s?.strippedData){let a=Object.keys(s.strippedData)[0];a&&(r.entityData=s.strippedData[a])}}return r.entityData?r:void 0}catch(e){this.loggingService.catch("Error in ActivityUtilsService extractFeatureEntityDataForResolver:",e);return}}mergeActivityWithResolverData(t){try{if(!this.activityResolverService.activityDataProviderAvailable())return t;let e=this.activityResolverService.getActivityById(t.id);if(!e)return t;e.changes&&(t.changes||(t.changes={}),Object.assign(t.changes,e.changes)),e.entityData!==void 0&&(t.entityData=e.entityData),e.entityTargetData!==void 0&&(t.entityTargetData=e.entityTargetData),e.displayMessageTemplateData&&(t.displayMessageTemplateData||(t.displayMessageTemplateData={}),Object.assign(t.displayMessageTemplateData,e.displayMessageTemplateData));let i=new Set(["id","metadata","changes","entityData","entityTargetData","displayMessageTemplateData"]);for(let[r,n]of Object.entries(e))!i.has(r)&&n!==void 0&&(t[r]=n);return t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithResolverData:",e),t}}rehydrateFeatureSpecificUserData(t){try{switch(t.featureType){case"comment":this.rehydrateCommentUserData(t);break;case"reaction":this.rehydrateReactionUserData(t);break;case"recorder":this.rehydrateRecorderUserData(t);break}}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateFeatureSpecificUserData:",e)}}getCommentDisplayMessage(t){try{let e=t.actionUser?.name??"Someone";switch(t.actionType){case w.ANNOTATION_ADD:return`${e} added a comment`;case w.COMMENT_ADD:return`${e} replied to a comment`;case w.COMMENT_UPDATE:return`${e} edited a comment`;case w.COMMENT_DELETE:return`${e} deleted a comment`;case w.ANNOTATION_DELETE:return`${e} deleted a comment thread`;case w.STATUS_CHANGE:{let i=t.changes?.status,r=i?.from?.name,n=i?.to?.name;return r&&n?`${e} changed status from ${r} to ${n}`:`${e} changed the status`}case w.PRIORITY_CHANGE:{let i=t.changes?.priority,r=i?.to;if(!r)return`${e} removed the priority`;let n=typeof r=="object"?r?.name:String(r),s=i?.from,a=s&&typeof s=="object"?s?.name:s?String(s):null;return a&&n?`${e} changed priority from ${a} to ${n}`:`${e} changed priority to ${n}`}case w.ASSIGN:{let r=t.changes?.assignedTo?.to;return r&&typeof r=="object"&&r.name?`${e} assigned to ${r.name}`:`${e} assigned the comment`}case w.ACCESS_MODE_CHANGE:{let r=t.changes?.accessMode?.to;return r?`${e} changed access to ${r}`:`${e} changed the access mode`}case w.CUSTOM_LIST_CHANGE:return`${e} changed the custom list`;case w.APPROVE:return`${e} approved the comment`;case w.ACCEPT:case w.SUGGESTION_ACCEPT:return`${e} accepted a suggestion`;case w.REJECT:case w.SUGGESTION_REJECT:return`${e} rejected a suggestion`;case w.REACTION_ADD:return`${e} reacted to a comment`;case w.REACTION_DELETE:return`${e} removed a reaction`;case w.SUBSCRIBE:return`${e} subscribed to the thread`;case w.UNSUBSCRIBE:return`${e} unsubscribed from the thread`;default:return""}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getCommentDisplayMessage:",e),""}}getRecorderDisplayMessage(t){try{let e=t.actionUser?.name??"Someone";switch(t.actionType){case Je.RECORDING_ADD:return`${e} added a recording`;case Je.RECORDING_DELETE:return`${e} deleted a recording`;default:return""}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getRecorderDisplayMessage:",e),""}}getReactionDisplayMessage(t){try{let e=t.actionUser?.name??"Someone";switch(t.actionType){case Ke.REACTION_ADD:return`${e} added a reaction`;case Ke.REACTION_DELETE:return`${e} removed a reaction`;default:return""}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getReactionDisplayMessage:",e),""}}getCrdtDisplayMessage(t){try{let e=t.actionUser?.name??"Someone",r=t.entityData?.editCount??0,n=t.targetEntityId??"unknown";return`${e} made ${r} edit${r!==1?"s":""} to editor ${n}`}catch(e){return this.loggingService.catch("Error in ActivityUtilsService getCrdtDisplayMessage:",e),""}}stripCommentPII(t){return A(this,null,function*(){try{let e=yield this.commentUtilsService.stripCommentAnnotationData({data:t.entityData,actionType:t.eventType??N.NEWLY_ADDED});if(e?.originalData&&(t.entityData=this.commentUtilsService.formatCommentData(e.originalData),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&Tt(t.entityData?.context)),t.entityTargetData&&(t.entityTargetData=this.commentUtilsService.formatCommentThreadData(this.commentUtilsService.stripCommentsFromAnnotationData({comment:t.entityTargetData}))),this.activityResolverService.activityDataProviderAvailable()||this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){t.changes?.commentText&&delete t.changes.commentText;for(let i of Object.keys(t.changes??{}))Bi(i,t.changes[i])&&delete t.changes[i]}}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripCommentPII:",e)}})}rehydrateCommentUserData(t){try{t.entityData&&this.commentUtilsService.mergeCommentWithUser(t.entityData),t.entityTargetData&&(this.rehydrateUserInObject(t.entityTargetData,"from"),this.rehydrateUsersInArray(t.entityTargetData,"to"),this.rehydrateUsersInArray(t.entityTargetData,"taggedUserContacts"))}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateCommentUserData:",e)}}stripReactionPII(t){try{if(!t.entityData)return;this.activityResolverService.activityDataProviderAvailable()&&this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()&&this.reactionUtilsService.stripReactionAnnotationData(t.entityData),t.entityData=this.reactionUtilsService.formatReactionData(t.entityData)}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripReactionPII:",e)}}rehydrateReactionUserData(t){try{if(!t.entityData)return;this.reactionUtilsService.mergeReactionWithUser(t.entityData)}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateReactionUserData:",e)}}stripRecorderPII(t){try{if(!t.entityData)return;if(this.activityResolverService.activityDataProviderAvailable()&&this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){this.serviceBook.get(ue)?.stripRecorderAnnotationData({data:t.entityData});return}let e=t.entityData;if(this.usersService.userDataProviderAvailable()){e.from&&typeof e.from=="object"&&"userId"in e.from&&(e.from={userId:e.from.userId});let i=e.transcription;i?.from&&typeof i.from=="object"&&"userId"in i.from&&(i.from={userId:i.from.userId})}}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripRecorderPII:",e)}}rehydrateRecorderUserData(t){try{if(!t.entityData)return;this.serviceBook.get(ue)?.mergeRecorderWithUser(t.entityData)}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateRecorderUserData:",e)}}mergeActivityWithCommentAnnotationData(t){try{if(!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let e=this.commentAnnotationsResolverService.getAnnotationById(t.targetEntityId);if(!e)return t;let i=t.entityData?.comments;if(Array.isArray(i))for(let r of i){let n=r?.commentId;if(n==null)continue;let s=e.comments?.[String(n)];s&&(s.commentText&&(r.commentText=s.commentText),s.commentHtml&&(r.commentHtml=s.commentHtml))}if(t.targetSubEntityId&&t.entityTargetData){let r=e.comments?.[t.targetSubEntityId];if(r){let n=t.entityTargetData;r.commentText&&(n.commentText=r.commentText),r.commentHtml&&(n.commentHtml=r.commentHtml)}}return t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithCommentAnnotationData:",e),t}}mergeActivityWithReactionData(t){try{return!this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(t.entityData),t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithReactionData:",e),t}}mergeActivityWithRecorderData(t){try{return!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||!t.targetEntityId||!t.entityData||this.serviceBook.get(ue)?.mergeStrippedDataWithRecorderAnnotation(t.entityData),t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mergeActivityWithRecorderData:",e),t}}buildCommentActivityData(t){try{let{commentAnnotation:e,targetComment:i,actionType:r,otherFields:n}=t,s=e,a=i,o=r===N.DELETED&&n?.isAnnotationDelete?w.ANNOTATION_DELETE:this.mapCommentStatusToActionType(r);if(!o)return null;let l=s?.annotationId;if(!l)return null;let u=a?.commentId,g=this.buildCommentChanges(r,a,n);return{featureType:"comment",actionType:o,targetEntityId:l,eventType:r,targetSubEntityId:u??null,changes:Object.keys(g).length>0?g:void 0,entityData:e,entityTargetData:i??void 0}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService buildCommentActivityData:",e),null}}mapCommentStatusToActionType(t){try{switch(t){case N.NEWLY_ADDED:return w.ANNOTATION_ADD;case N.ADDED:return w.COMMENT_ADD;case N.UPDATED:return w.COMMENT_UPDATE;case N.DELETED:return w.COMMENT_DELETE;case N.STATUS_CHANGED:return w.STATUS_CHANGE;case N.PRIORITY_CHANGED:return w.PRIORITY_CHANGE;case N.ASSIGNED:return w.ASSIGN;case N.ACCESS_MODE_CHANGED:return w.ACCESS_MODE_CHANGE;case N.CUSTOM_LIST_CHANGED:return w.CUSTOM_LIST_CHANGE;case N.APPROVED:return w.APPROVE;case N.ACCEPTED:return w.ACCEPT;case N.REJECTED:return w.REJECT;case N.SUGGESTION_ACCEPTED:return w.SUGGESTION_ACCEPT;case N.SUGGESTION_REJECTED:return w.SUGGESTION_REJECT;case N.REACTION_ADDED:return w.REACTION_ADD;case N.REACTION_DELETED:return w.REACTION_DELETE;case N.SUBSCRIBED:return w.SUBSCRIBE;case N.UNSUBSCRIBED:return w.UNSUBSCRIBE;default:return null}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mapCommentStatusToActionType:",e),null}}buildRecorderActivityData(t){try{let e=t.annotationData,i=t.actionType,r=this.mapRecorderStatusToActionType(i);if(!r)return null;let n=e?.annotationId;return n?{featureType:"recorder",actionType:r,targetEntityId:n,entityData:e}:null}catch(e){return this.loggingService.catch("Error in ActivityUtilsService buildRecorderActivityData:",e),null}}mapRecorderStatusToActionType(t){try{switch(t){case Kt.ADDED:return Je.RECORDING_ADD;case Kt.DELETED:return Je.RECORDING_DELETE;default:return null}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mapRecorderStatusToActionType:",e),null}}buildReactionActivityData(t){try{let e=t.annotationData,i=t.actionType,r=this.mapReactionActionType(i);if(!r)return null;let n=e?.annotationId;return n?{featureType:"reaction",actionType:r,targetEntityId:n,entityData:e}:null}catch(e){return this.loggingService.catch("Error in ActivityUtilsService buildReactionActivityData:",e),null}}mapReactionActionType(t){try{switch(t){case"add":return Ke.REACTION_ADD;case"delete":return Ke.REACTION_DELETE;default:return null}}catch(e){return this.loggingService.catch("Error in ActivityUtilsService mapReactionActionType:",e),null}}buildCommentChanges(t,e,i){try{let r={};switch(t){case N.NEWLY_ADDED:case N.ADDED:r.commentText={from:null,to:e?.commentText??null};break;case N.UPDATED:r.commentText={from:i?.oldCommentText??null,to:e?.commentText??null};break;case N.DELETED:r.commentText={from:e?.commentText??null,to:null};break;case N.STATUS_CHANGED:r.status={from:i?.oldStatus??null,to:i?.newStatus??null};break;case N.PRIORITY_CHANGED:r.priority={from:i?.oldPriority??null,to:i?.newPriority??null};break;case N.ASSIGNED:{r.assignedTo={from:i?.oldAssignedTo??null,to:i?.newAssignedTo??null};break}case N.ACCESS_MODE_CHANGED:r.accessMode={from:i?.oldAccessMode??null,to:i?.newAccessMode??null};break;case N.CUSTOM_LIST_CHANGED:r.customList={from:i?.oldCustomList??null,to:i?.newCustomList??null};break}return r}catch(r){return this.loggingService.catch("Error in ActivityUtilsService buildCommentChanges:",r),{}}}extractFeatureSpecificUserIds(t,e){try{switch(t.featureType){case"comment":this.extractCommentActivityUserIds(t,e);break;case"reaction":this.extractReactionActivityUserIds(t,e);break;case"recorder":this.extractRecorderActivityUserIds(t,e);break}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractFeatureSpecificUserIds:",i)}}extractCommentActivityUserIds(t,e){try{if(t.entityData){let i=this.commentUtilsService.getUserIdsToResolveFromComments([t.entityData]);for(let r of i)e.add(r)}if(t.entityTargetData){let i=t.entityTargetData;if(this.extractUserIdFromValue(i.from,e),Array.isArray(i.to))for(let r of i.to)this.extractUserIdFromValue(r,e);if(Array.isArray(i.taggedUserContacts))for(let r of i.taggedUserContacts)this.extractUserIdFromValue(r,e)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractCommentActivityUserIds:",i)}}extractReactionActivityUserIds(t,e){try{if(!t.entityData)return;let i=this.reactionUtilsService.getUserIdsToResolveFromReactions([t.entityData]);for(let r of i)e.add(r)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractReactionActivityUserIds:",i)}}extractRecorderActivityUserIds(t,e){try{if(!t.entityData)return;let i=this.serviceBook.get(ue)?.getUserIdsToResolveFromRecorders([t.entityData])??[];for(let r of i)e.add(r)}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractRecorderActivityUserIds:",i)}}stripUsersFromChanges(t){try{for(let e of Object.keys(t)){let i=t[e];i&&(i.from=this.stripUserIfPresent(i.from),i.to=this.stripUserIfPresent(i.to))}}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromChanges:",e)}}stripUserIfPresent(t){try{return t&&typeof t=="object"&&"userId"in t?{userId:t.userId}:t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService stripUserIfPresent:",e),t}}stripUsersFromTemplateData(t){try{for(let e of Object.keys(t)){let i=t[e];i&&typeof i=="object"&&"userId"in i&&(t[e]={userId:i.userId})}}catch(e){this.loggingService.catch("Error in ActivityUtilsService stripUsersFromTemplateData:",e)}}rehydrateUsersInChanges(t){try{for(let e of Object.values(t))e&&(e.from=this.rehydrateIfUser(e.from),e.to=this.rehydrateIfUser(e.to))}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInChanges:",e)}}rehydrateIfUser(t){try{if(t&&typeof t=="object"&&"userId"in t){let e=t.userId;return this.usersService.getUserById(e)??t}return t}catch(e){return this.loggingService.catch("Error in ActivityUtilsService rehydrateIfUser:",e),t}}rehydrateUsersInTemplateData(t){try{for(let e of Object.keys(t))t[e]=this.rehydrateIfUser(t[e])}catch(e){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInTemplateData:",e)}}rehydrateUserInObject(t,e){try{let i=t[e];if(i&&typeof i=="object"&&"userId"in i){let r=i.userId,n=this.usersService.getUserById(r);n&&(t[e]=n)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUserInObject:",i)}}rehydrateUsersInArray(t,e){try{let i=t[e];Array.isArray(i)&&(t[e]=i.map(r=>this.rehydrateIfUser(r)))}catch(i){this.loggingService.catch("Error in ActivityUtilsService rehydrateUsersInArray:",i)}}extractUserIdFromValue(t,e){try{if(t&&typeof t=="object"&&"userId"in t){let i=t.userId;typeof i=="string"&&e.add(i)}}catch(i){this.loggingService.catch("Error in ActivityUtilsService extractUserIdFromValue:",i)}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K),T(zt),T(kt),T(me),T(Re),T(Pe),T(xt),T(Ne))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Ht=class{constructor({apiKey:c,documentId:z,organizationId:t,folderId:e,veltFolderId:i,clientDocumentId:r,clientOrganizationId:n}){this.paths={},this.apiKey=c,this.documentId=z,this.organizationId=t,this.folderId=e,this.veltFolderId=i,this.clientDocumentId=r,this.clientOrganizationId=n,r&&(this.documentId=Ce(r)),n&&(this.organizationId=Be(n)),e&&(this.folderId=e,this.veltFolderId=Ee(e)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let c=`${this.apiKey}`;this.organizationId&&(c=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`),this.documentId&&(this.paths.docs=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.folder=`${c}/${h.FIREBASE_PARTIAL_PATH_FOLDERS}/`,this.paths.presence=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_PRESENCE}/`,this.paths.cursor=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_CURSOR}/`,this.paths.comment=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_COMMENT}/`,this.paths.multiThread=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,this.paths.tag=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_TAG}/`,this.paths.area=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_AREA}/`,this.paths.arrow=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_ARROW}/`,this.paths.selection=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_SELECTION}/`,this.paths.audioHuddle=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,this.paths.huddle=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_HUDDLE}/`,this.paths.recorder=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_RECORDER}/`,this.paths.flock=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,this.paths.syncVideoPlayer=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,this.paths.liveState=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,this.paths.liveStateSingleEditorMode=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,this.paths.reaction=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_REACTION}/`,this.paths.crdt=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_CRDT}/`,this.paths.views=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_VIEWS}/`,this.paths.notifications=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,this.paths.metadata=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_METADATA}/`,this.paths.users=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.documentIam=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.userConfig=`${c}/${h.FIREBASE_PARTIAL_PATH_USERS}`),this.paths.customerMetadata=`${c}/${h.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,this.paths.groupContacts=`${c}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_GROUPS}/`,this.paths.globalContacts=`${c}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_GLOBAL}/`,this.paths.logins=`${c}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_LOGINS}/`,this.paths.userFeedback=`${c}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,this.paths.userReportBugs=`${c}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_BUGS}/`,this.paths.userContactUs=`${c}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,this.organizationId&&(this.paths.organizationMetadata=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,this.paths.organizationIam=`${c}/${h.FIREBASE_PARTIAL_PATH_IAM}/`,this.paths.organizationGroups=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,this.paths.organizationNotifications=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,this.documentId&&(this.paths.organizationNotificationsWithDocumentId=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/`,this.paths.heartbeatByDocument=`${c}/${h.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${this.documentId}/`),this.paths.organizationNotificationsLastNotificationTimestamp=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${h.FIREBASE_PARTIAL_PATH_DOCS}/`,this.paths.organizationNotificationsUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_USERS}/`,this.paths.heartbeat=`${c}/${h.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),this.paths.workspaceIam=`${this.apiKey}/${h.FIREBASE_PARTIAL_PATH_IAM}/`}}catch{}}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("User config path is not available.")}get workspaceIam(){return this.paths.workspaceIam?this.paths.workspaceIam:this.throwError("Workspace IAM path is not available.")}get docs(){return this.paths.docs?this.paths.docs:this.throwError("Docs path is not available.")}get presence(){return this.paths.presence?this.paths.presence:this.throwError("Presence path is not available.")}get cursor(){return this.paths.cursor?this.paths.cursor:this.throwError("Cursor path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get arrow(){return this.paths.arrow?this.paths.arrow:this.throwError("Arrow path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get tag(){return this.paths.tag?this.paths.tag:this.throwError("Tag path is not available.")}get selection(){return this.paths.selection?this.paths.selection:this.throwError("Selection path is not available.")}get audioHuddle(){return this.paths.audioHuddle?this.paths.audioHuddle:this.throwError("Audio huddle path is not available.")}get huddle(){return this.paths.huddle?this.paths.huddle:this.throwError("Huddle path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get flock(){return this.paths.flock?this.paths.flock:this.throwError("Flock path is not available.")}get syncVideoPlayer(){return this.paths.syncVideoPlayer?this.paths.syncVideoPlayer:this.throwError("Sync video player path is not available.")}get liveState(){return this.paths.liveState?this.paths.liveState:this.throwError("Live state path is not available.")}get liveStateSingleEditorMode(){return this.paths.liveStateSingleEditorMode?this.paths.liveStateSingleEditorMode:this.throwError("Live state single editor mode path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get views(){return this.paths.views?this.paths.views:this.throwError("Views path is not available.")}get notifications(){return this.paths.notifications?this.paths.notifications:this.throwError("Notifications path is not available.")}get metadata(){return this.paths.metadata?this.paths.metadata:this.throwError("Metadata path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get documentIam(){return this.paths.documentIam?this.paths.documentIam:this.throwError("Document IAM path is not available.")}get organizationMetadata(){return this.paths.organizationMetadata?this.paths.organizationMetadata:this.throwError("Organization metadata path is not available.")}get organizationIam(){return this.paths.organizationIam?this.paths.organizationIam:this.throwError("Organization IAM path is not available.")}get customerMetadata(){return this.paths.customerMetadata?this.paths.customerMetadata:this.throwError("Customer metadata path is not available.")}get groupContacts(){return this.paths.groupContacts?this.paths.groupContacts:this.throwError("Group contacts path is not available.")}get globalContacts(){return this.paths.globalContacts?this.paths.globalContacts:this.throwError("Global contacts path is not available.")}get logins(){return this.paths.logins?this.paths.logins:this.throwError("Logins path is not available.")}get userFeedback(){return this.paths.userFeedback?this.paths.userFeedback:this.throwError("User feedback path is not available.")}get userReportBugs(){return this.paths.userReportBugs?this.paths.userReportBugs:this.throwError("User report bugs path is not available.")}get userContactUs(){return this.paths.userContactUs?this.paths.userContactUs:this.throwError("User contact us path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("Organization groups path is not available.")}get heartbeat(){return this.paths.heartbeat?this.paths.heartbeat:this.throwError("Heartbeat path is not available.")}get heartbeatByDocument(){return this.paths.heartbeatByDocument?this.paths.heartbeatByDocument:this.throwError("Heartbeat by document path is not available.")}get organizationNotifications(){return this.paths.organizationNotifications?this.paths.organizationNotifications:this.throwError("Organization notifications path is not available.")}get organizationNotificationsWithDocumentId(){return this.paths.organizationNotificationsWithDocumentId?this.paths.organizationNotificationsWithDocumentId:this.throwError("Organization notifications with document id path is not available.")}get organizationNotificationsUsers(){return this.paths.organizationNotificationsUsers?this.paths.organizationNotificationsUsers:this.throwError("Organization notifications users path is not available.")}get organizationNotificationsLastNotificationTimestamp(){return this.paths.organizationNotificationsLastNotificationTimestamp?this.paths.organizationNotificationsLastNotificationTimestamp:this.throwError("Organization notifications last notification timestamp path is not available.")}throwError(c){throw{type:"DocumentPaths",message:c,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var ot=class{constructor({apiKey:c,documentId:z,organizationId:t,clientDocumentId:e,clientOrganizationId:i,folderId:r,veltFolderId:n}){this.paths={},this.apiKey=c,this.documentId=z,this.organizationId=t,this.veltFolderId=n,e&&(this.documentId=Ce(e)),i&&(this.organizationId=Be(i)),r&&(this.folderId=r,this.veltFolderId=Ee(r)),this.generateDocumentPaths()}generateDocumentPaths(){try{if(this.paths.clientDocumentId=this.clientDocumentId,this.paths.documentId=this.documentId,this.organizationId&&(this.paths.organizationId=this.organizationId,this.paths.clientOrganizationId=this.clientOrganizationId),this.veltFolderId&&(this.paths.folderId=this.folderId,this.paths.veltFolderId=this.veltFolderId),this.apiKey){let c=`apiKey/${this.apiKey}`;this.paths.activities=`${c}/${h.FIREBASE_PARTIAL_PATH_ACTIVITIES}`,this.paths.userNotificationIndex=`${c}/${h.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION_INDEX}`,this.organizationId&&(c=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.paths.organizationId}`,this.paths.organization=c,this.paths.folder=`${c}/${h.FIREBASE_PARTIAL_PATH_FOLDERS}`,this.paths.organizationUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,this.paths.users=`${c}/${h.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,this.paths.notificationDocs=`${c}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,this.paths.notificationUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.paths.organizationGroups=`${c}/${h.FIREBASE_PARTIAL_PATH_GROUPS}`,this.paths.lastNotificationTimestamp=`${c}/${h.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}`,this.paths.lastActivityTimestamp=`${c}/${h.FIREBASE_PARTIAL_PATH_LAST_ACTIVITY_TIMESTAMP}`,this.paths.userConfig=`${c}/${h.FIREBASE_PARTIAL_PATH_USERS}`,this.paths.permissionsUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_PERMISSIONS_USERS}`),this.veltFolderId&&(this.paths.folderUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_FOLDERS}/${this.veltFolderId}/${h.FIREBASE_PARTIAL_PATH_FOLDER_USERS}`),this.documentId&&(this.paths.document=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}`,this.paths.comment=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_COMMENT}`,this.paths.location=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_LOCATION}`,this.paths.multiThread=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,this.paths.area=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_AREA}`,this.paths.recorder=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_RECORDER}`,this.paths.reaction=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_REACTION}`,this.paths.crdt=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_CRDT}`,this.paths.notificationViews=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,this.paths.documentViews=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,this.paths.locationViews=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,this.paths.documentUsers=`${c}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,this.paths.docNotification=`${this.paths.notificationDocs}/${this.documentId}/${h.FIREBASE_PARTIAL_PATH_DOC_NOTIFICATION}`)}}catch{}}get userNotificationIndex(){return this.paths.userNotificationIndex}get permissionsUsers(){return this.paths.permissionsUsers?this.paths.permissionsUsers:this.throwError("PermissionsUsers path is not available.")}get users(){return this.paths.users?this.paths.users:this.throwError("Users path is not available.")}get userConfig(){return this.paths.userConfig?this.paths.userConfig:this.throwError("UserConfig path is not available.")}get folder(){return this.paths.folder?this.paths.folder:this.throwError("Folder path is not available.")}get lastNotificationTimestamp(){return this.paths.lastNotificationTimestamp?this.paths.lastNotificationTimestamp:this.throwError("LastNotificationTimestamp path is not available.")}get organizationGroups(){return this.paths.organizationGroups?this.paths.organizationGroups:this.throwError("organizationGroups path is not available.")}get docNotification(){return this.paths.docNotification?this.paths.docNotification:this.throwError("DocNotification path is not available.")}get organization(){return this.paths.organization?this.paths.organization:this.throwError("Organization path is not available.")}get document(){return this.paths.document?this.paths.document:this.throwError("Document path is not available.")}get location(){return this.paths.location?this.paths.location:this.throwError("Location path is not available.")}get area(){return this.paths.area?this.paths.area:this.throwError("Area path is not available.")}get comment(){return this.paths.comment?this.paths.comment:this.throwError("Comment path is not available.")}get documentViews(){return this.paths.documentViews?this.paths.documentViews:this.throwError("DocumentViews path is not available.")}get locationViews(){return this.paths.locationViews?this.paths.locationViews:this.throwError("LocationViews path is not available.")}get notificationViews(){return this.paths.notificationViews?this.paths.notificationViews:this.throwError("NotificationViews path is not available.")}get documentUsers(){return this.paths.documentUsers?this.paths.documentUsers:this.throwError("DocumentUsers path is not available.")}get folderUsers(){return this.paths.folderUsers?this.paths.folderUsers:this.throwError("FolderUsers path is not available.")}get organizationUsers(){return this.paths.organizationUsers?this.paths.organizationUsers:this.throwError("OrganizationUsers path is not available.")}get notificationDocs(){return this.paths.notificationDocs?this.paths.notificationDocs:this.throwError("NotificationDocs path is not available.")}get notificationUsers(){return this.paths.notificationUsers?this.paths.notificationUsers:this.throwError("NotificationUsers path is not available.")}get multiThread(){return this.paths.multiThread?this.paths.multiThread:this.throwError("Multi thread path is not available.")}get recorder(){return this.paths.recorder?this.paths.recorder:this.throwError("Recorder path is not available.")}get reaction(){return this.paths.reaction?this.paths.reaction:this.throwError("Reaction path is not available.")}get crdt(){return this.paths.crdt?this.paths.crdt:this.throwError("CRDT path is not available.")}get activities(){return this.paths.activities?this.paths.activities:this.throwError("Activities path is not available.")}get lastActivityTimestamp(){return this.paths.lastActivityTimestamp?this.paths.lastActivityTimestamp:this.throwError("LastActivityTimestamp path is not available.")}throwError(c){throw{type:"DocumentPaths",message:c,metadata:{apiKey:this.apiKey,documentId:this.documentId,organizationId:this.organizationId}}}};var or=(()=>{let c=class c{constructor(t,e){this.loggingService=t,this.usersService=e}getUserIdsToResolveFromAreaAnnotations(t){try{this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: getUserIdsToResolveFromAreaAnnotations","color: green;");let e=new Set;for(let i of t)i?.from?.userId&&e.add(i?.from?.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in AreaUtilsService getUserIdsToResolveFromAreaAnnotations:",e),[]}}mergeAreaWithUser(t){try{if(this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: mergeAreaWithUser","color: green;"),t?.from?.userId){let e=this.usersService.getUserById(t?.from?.userId);e&&(t.from=e)}return t}catch(e){return this.loggingService.catch("Error in AreaUtilsService mergeAreaWithUser:",e),t}}formatAreaData(t){try{return this.loggingService.log("%c[WB] Calling AreaUtilsService FUNCTION: formatAreaData","color: green;"),this.usersService.userDataProviderAvailable()&&t?.from?.userId&&(t.from={userId:t.from.userId}),t}catch(e){return this.loggingService.catch("Error in AreaUtilsService formatAreaData:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var sr=(()=>{let c=class c{constructor(t,e){this.loggingService=t,this.usersService=e}getUserIdsToResolveFromUserIamData(t){try{this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: getUserIdsToResolveFromUserIamData","color: green;");let e=new Set;if(t?.length)for(let i of t)i?.user?.userId&&e.add(i?.user?.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in ContactUtilsService getUserIdsToResolveFromUserIamData: ",e),[]}}mergeUserIamWithUser(t){try{if(this.loggingService.log("%c[WB] Calling ContactUtilsService FUNCTION: mergeUserIamWithUser","color: green;"),t?.user?.userId){let e=this.usersService.getUserById(t?.user?.userId);if(e){let i=e;t?.user&&typeof t.user=="object"&&(i=S(S({},i),t.user));let r=this.usersService.getContactListUser(t.user.userId);r&&(i=S(S({},i),r)),t=L(S({},t),{user:i})}}return t}catch(e){return this.loggingService.catch("Error in ContactUtilsService mergeUserIamWithUser: ",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var ar=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.usersService=i}getUserIdsToResolveFromLiveStateCustom(t){try{let e=new Set;return t?.updatedBy&&e.add(t?.updatedBy?.userId),Array.from(e)}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustom:",e),[]}}mergeLiveStateCustomWithUser(t){try{if(t?.updatedBy?.userId){let e=this.usersService.getUserById(t?.updatedBy?.userId);e&&(t.updatedBy=e)}return t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateCustomWithUser:",e),t}}formatLiveStateCustomData(t){try{return this.usersService.userDataProviderAvailable()&&t?.updatedBy&&(t.updatedBy={userId:t.updatedBy.userId}),t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateCustomData:",e),t}}getUserIdsToResolveFromLiveStateCustoms(t){try{let e=new Set;for(let i of t)i?.updatedBy?.userId&&e.add(i?.updatedBy?.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateCustoms:",e),[]}}getUserIdsToResolveFromLiveStates(t){try{let e=new Set;return t?.default?.singleEditorMode?.editor?.userId&&e.add(t?.default?.singleEditorMode?.editor?.userId),Array.from(e)}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStates:",e),[]}}getUserIdsToResolveFromLiveStateSingleEditorMode(t){try{let e=new Set;return t?.editor?.userId&&e.add(t?.editor?.userId),t?.requestEditorAccess?.user?.userId&&e.add(t?.requestEditorAccess?.user?.userId),Array.from(e)}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService getUserIdsToResolveFromLiveStateSingleEditorMode:",e),[]}}mergeLiveStateWithUser(t){try{if(t?.default?.singleEditorMode?.editor?.userId){let e=this.usersService.getUserById(t?.default?.singleEditorMode?.editor?.userId);e&&(t.default.singleEditorMode.editor=e)}if(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId){let e=this.usersService.getUserById(t?.default?.singleEditorMode?.requestEditorAccess?.user?.userId);e&&(t.default.singleEditorMode.requestEditorAccess.user=e)}return t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService mergeLiveStateWithUser:",e),t}}mergeSingleEditorLiveStateDataWithUser(t){try{if(t?.editor?.userId){let e=this.usersService.getUserById(t?.editor?.userId);e&&(t.editor=e)}if(t?.requestEditorAccess?.user?.userId){let e=this.usersService.getUserById(t?.requestEditorAccess?.user?.userId);e&&(t.requestEditorAccess.user=e)}return t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService mergeSingleEditorLiveStateDataWithUser:",e),t}}resolveAndMergeSingleEditorLiveStateDataWithUser(t){return A(this,null,function*(){try{let e=this.getUserIdsToResolveFromLiveStates({default:{singleEditorMode:t}});if(e.length){let i=b(),r=ht.GET_SINGLE_EDITOR_USERS;return this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:ce.RESOLVE_AND_MERGE_SINGLE_EDITOR_LIVE_STATE_DATA_WITH_USER,moduleName:r,source:"internal",payload:{userIds:e}}),yield this.usersService.resolveUsers({userIds:e,uniqueId:i,moduleName:r}),this.mergeSingleEditorLiveStateDataWithUser(t)}return t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService resolveAndMergeSingleEditorLiveStateDataWithUser:",e),t}})}formatLiveStateSingleEditorModeData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.editor?.userId&&(t.editor={userId:t.editor.userId}),t?.requestEditorAccess?.user?.userId&&(t.requestEditorAccess.user={userId:t.requestEditorAccess.user.userId})),t}catch(e){return this.loggingService.catch("Error in LiveStateUtilsService formatLiveStateSingleEditorModeData:",e),t}}mergeLiveStateCustomsWithUsers(t){try{for(let e of t)if(e?.updatedBy?.userId){let i=this.usersService.getUserById(e?.updatedBy?.userId);i&&(e.updatedBy=i)}return t}catch(e){return this.loggingService.catch("Error in mergeLiveStateCustomsWithUsers:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(K))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var cr=(()=>{let c=class c{constructor(t,e,i){this.loggingService=t,this.usersService=e,this.commentAnnotationsResolverService=i}getUserIdsToResolveFromMultiThreads(t){try{let e=new Set;for(let i of t)i?.from?.userId&&e.add(i?.from?.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in MultiThreadUtilsService getUserIdsToResolveFromMultiThreads:",e),[]}}mergeMultiThreadWithUser(t){try{if(t?.from?.userId){let e=this.usersService.getUserById(t?.from?.userId);e&&(t.from=e)}return t}catch(e){return this.loggingService.catch("Error in MultiThreadUtilsService mergeMultiThreadWithUser:",e),t}}formatMultiThreadData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.commentAnnotationsMap&&(t.commentAnnotationsMap=null)),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()&&(t=Li(t)),t}catch(e){return this.loggingService.catch("Error in MultiThreadUtilsService formatMultiThreadData:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K),T(me))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var lr=(()=>{let c=class c{constructor(t,e){this.loggingService=t,this.usersService=e}getUserIdsToResolveFromSelections(t){try{let e=new Set;for(let i of t)i?.user?.userId&&e.add(i.user.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in SelectionUtilsService getUserIdsToResolveFromSelections:",e),[]}}mergeSelectionWithUser(t){try{if(t?.user?.userId){let e=this.usersService.getUserById(t?.user?.userId);e&&(t.user=e)}return t}catch(e){return this.loggingService.catch("Error in SelectionUtilsService mergeSelectionWithUser:",e),t}}formatSelectionData(t){try{return this.usersService.userDataProviderAvailable()&&t?.user?.userId&&(t.user={userId:t.user.userId}),t}catch(e){return this.loggingService.catch("Error in SelectionUtilsService formatSelectionData:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var dr=(()=>{let c=class c{constructor(t,e){this.loggingService=t,this.usersService=e}getUserIdsToResolveFromTags(t){try{let e=new Set;for(let i of t)if(i?.from?.userId&&e.add(i.from.userId),i?.to?.length)for(let r of i.to)r?.userId&&e.add(r.userId);return Array.from(e)}catch(e){return this.loggingService.catch("Error in TagUtilsService getUserIdsToResolveFromTags:",e),[]}}mergeTagWithUser(t){try{if(t?.from?.userId){let e=this.usersService.getUserById(t?.from?.userId);e&&(t.from=e)}return t?.to?.length&&(t.to=t.to.map(e=>{if(e?.userId){let i=this.usersService.getUserById(e?.userId);i&&(e=i)}return e})),t}catch(e){return this.loggingService.catch("Error in TagUtilsService mergeTagWithUser:",e),t}}formatTagData(t){try{return this.usersService.userDataProviderAvailable()&&(t?.from?.userId&&(t.from={userId:t.from.userId}),t?.to?.length&&(t.to=t.to.map(e=>(e?.userId&&(e={userId:e.userId}),e)))),t}catch(e){return this.loggingService.catch("Error in TagUtilsService formatTagData:",e),t}}};c.\u0275fac=function(e){return new(e||c)(T(B),T(K))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Gt=(()=>{let c=class c{constructor(t,e,i){this.coreActionsService=t,this.loggingService=e,this.analyticsService=i,this.resolveTimeout=60*1e3,this.retryDeleteConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.retryGetConfig={retryCount:0,retryDelay:0,revertOnFailure:!1},this.notificationDataProvider$=new P(null),this.notificationById$=new P({}),this.inFlightRequests=new Map,this.getNotificationById=r=>{try{return this.notificationDataProviderAvailable()?this.notificationById$.value?.[r]:void 0}catch(n){this.loggingService.catch("Error in NotificationResolverService getNotificationById:",n);return}};try{this.loggingService.log("NotificationResolverService initialized"),this.notificationDataProvider$.subscribe(r=>{r&&(r.config?.resolveTimeout&&(this.resolveTimeout=r.config.resolveTimeout),r.config?.deleteRetryConfig&&(this.retryDeleteConfig=r.config.deleteRetryConfig),r.config?.getRetryConfig&&(this.retryGetConfig=r.config.getRetryConfig))})}catch(r){this.loggingService.catch("Error in NotificationResolverService constructor:",r)}}getProvider(){try{let t=this.notificationDataProvider$.getValue();return t||void 0}catch(t){this.loggingService.catch("Error in NotificationResolverService getProvider:",t);return}}ngOnDestroy(){try{this.notificationById$.next({})}catch(t){this.loggingService.catch("Error in NotificationResolverService ngOnDestroy:",t)}}resolveNotifications(r){return A(this,arguments,function*({request:t,uniqueId:e,moduleName:i}){try{if(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: resolveNotifications","color: green;"),!this.notificationDataProviderAvailable())return{};let n,s=!1,a=!1,o=()=>{n&&(clearTimeout(n),n=void 0,a=!0)};return new Promise((l,u)=>{n=setTimeout(()=>{if(!a){s=!0,o();let p=e||b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:new Error("Notification resolution timeout"),request:t}}),u(new Error("Notification resolution timeout"))}},this.notificationDataProvider$.value?.config?.resolveTimeout||this.resolveTimeout);let g=this.getProvider();if(!g)return o(),l({});let f={},d=this.notificationById$.getValue()||{},m=[...new Set(t.notificationIds||[])],O=[],D=[],U=[];for(let p of m)d[p]||(this.inFlightRequests.has(p)?(O.push(this.inFlightRequests.get(p)),D.push(p)):U.push(p));let y=L(S({},t),{notificationIds:U});A(this,null,function*(){try{if(O.length>0&&(yield Promise.allSettled(O)),U.length>0){let p=e||b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:p,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{request:y}});let C,_=new Promise(V=>{C=V});for(let V of U)this.inFlightRequests.set(V,_.then(ie=>ie?.[V]));let Q=G(()=>g?.config?.getConfig?.url?J(g.config.getConfig.url,g.config.getConfig.headers,y,!0,g.config.getConfig.credentials):g?.get?.(y)||Promise.resolve(void 0),"getNotifications",this.retryGetConfig).then(V=>s?{}:(o(),V&&V.statusCode!==200?(this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:p,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:V,request:y}}),this.loggingService.catch(V?.message??"Error in NotificationResolverService resolveNotifications:"),{}):V?.data)).catch(V=>{throw o(),V});try{f=(yield Q)||{},C(f);for(let ie of U)this.inFlightRequests.delete(ie);this.analyticsService.trackEvent(v.Events.Resolver.NOTIFICATION_RESOLVER_GET,{sourceMethod:"resolveNotifications",source:"sdk",notificationIds:U});let V={};Object.entries(f).forEach(([ie,M])=>{let pe=this.notificationById$.value?.[ie];pe?pe&&JSON.stringify(pe)!==JSON.stringify(M)&&(V[ie]=M):V[ie]=M}),Object.keys(V).length>0&&this.notificationById$.next(S(S({},this.notificationById$.getValue()),V)),this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:p,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{result:V,request:y}}),l(V)}catch(V){C({});for(let M of U)this.inFlightRequests.delete(M);let ie=e||b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:ie,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:V,request:y}}),s||u(V),l(f)}}else o(),l({})}catch(p){o();let C=e||b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:C,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:p,request:y}}),u(p)}})})}catch(n){this.loggingService.catch("Error in NotificationResolverService resolveNotifications:",n);let s=e||b();return this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:s,methodName:re.RESOLVE_NOTIFICATIONS,moduleName:i,source:"internal",payload:{error:n,request:t}}),{}}})}deleteNotification(t,e,i){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: deleteNotification","color: green;");let r=this.getProvider();if(!this.notificationDataProviderAvailable())throw new Error("Notification delete data provider not available");let n=i||b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_DELETE_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:n,methodName:re.DELETE_NOTIFICATION,source:"internal",payload:{notificationId:t,organizationId:e}});let s=this.notificationById$.getValue(),a=S({},s);delete a?.[t],this.notificationById$._value=a;let o={notificationId:t,organizationId:e},l=yield G(()=>r?.config?.deleteConfig?.url?J(r.config.deleteConfig.url,r.config.deleteConfig.headers,o,!1,r.config.deleteConfig.credentials):r?.delete?.(o)||Promise.resolve(void 0),"deleteNotification",this.retryDeleteConfig);return l&&l.statusCode!==200?(this.retryDeleteConfig.revertOnFailure&&(this.notificationById$._value=s),this.loggingService.catch(l?.message??"Error in NotificationResolverService deleteNotification:"),this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:re.DELETE_NOTIFICATION,source:"internal",payload:{error:l,notificationId:t,organizationId:e}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!1}):(this.analyticsService.trackEvent(v.Events.Resolver.NOTIFICATION_RESOLVER_DELETE,{sourceMethod:"deleteNotification",source:"sdk",notificationId:t}),this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_DELETE_RESULT,timestamp:new Date().getTime(),uniqueId:n,methodName:re.DELETE_NOTIFICATION,source:"internal",payload:{result:{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0},notificationId:t,organizationId:e}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0})}catch(r){this.loggingService.warn("Error in NotificationResolverService deleteNotification:",r);let n=i||b();return this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_DELETE_ERROR,timestamp:new Date().getTime(),uniqueId:n,methodName:re.DELETE_NOTIFICATION,source:"internal",payload:{error:r,notificationId:t,organizationId:e}}),{revertOnFailure:this.retryDeleteConfig.revertOnFailure,isSuccess:!0}}})}getNotificationsById$(){try{return this.notificationDataProviderAvailable()?(this.loggingService.log("%c[WB] Calling NotificationResolverService FUNCTION: getNotificationsById$","color: green;"),this.notificationById$.asObservable()):$(void 0)}catch(t){return this.loggingService.catch("Error in NotificationResolverService getNotificationsById$:",t),$(void 0)}}setNotificationDataProvider(t){try{if(t){this.loggingService.log("Setting notification data provider");let e=t.config,i=[{method:"get",configKey:"getConfig"},{method:"delete",configKey:"deleteConfig"}],r=[];if(i.forEach(({method:n,configKey:s})=>{let a=e?.[s]?.url,o=n in t&&typeof t[n]=="function";!a&&!o&&r.push(n)}),r.length>0){let n=`DataProviders.notification is invalid. The following methods are missing or are not functions (and no corresponding config provided): ${r.join(", ")}.`;this.loggingService.catch(n);return}else this.notificationDataProvider$.next(t)}}catch(e){this.loggingService.catch("Error in NotificationResolverService setNotificationDataProvider:",e)}}notificationDataProviderAvailable(){try{return!!this.notificationDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in NotificationResolverService notificationDataProviderAvailable:",t),!1}}};c.\u0275fac=function(e){return new(e||c)(T(H),T(B),T(oe))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var ur=(()=>{let c=class c{constructor(t,e,i,r,n,s,a,o,l,u,g,f,d,m,O,D,U,y,R,p){this.activityUtilsService=t,this.areaUtilsService=e,this.commentUtilsService=i,this.contactUtilsService=r,this.coreActionsService=n,this.liveStateUtilsService=s,this.loggingService=a,this.multiThreadUtilsService=o,this.reactionUtilsService=l,this.selectionUtilsService=u,this.tagUtilsService=g,this.usersService=f,this.docService=d,this.commentAnnotationsResolverService=m,this.reactionAnnotationsResolverService=O,this.recorderAnnotationsResolverService=D,this.notificationResolverService=U,this.activityResolverService=y,this.serviceBook=R,this.attachmentResolverService=p}getErrorForGetRequests({feature:t,error:e}){try{switch(t){case"apiKeyMetadata":case"organizationMetadata":case"documentMetadata":case"folderMetadata":return(e?.message??"")?.includes("Missing or insufficient permissions.")?{errorCode:"PERMISSION_DENIED"}:null;default:return null}}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService getErrorForGetRequests:",i),null}}getFirestorePath({feature:t,properties:e,documentPaths:i,apiKey:r}){try{if(!r)return;if(t==="userNotificationIndex"){if(!e?.id)return;let l=new ot({apiKey:r});return l?.userNotificationIndex?`${l.userNotificationIndex}/${e.id}`:void 0}let{documentId:n,organizationId:s,folderId:a}=e;if(!s&&(s=i?.organizationId,!s))return;let o=new ot({apiKey:r,documentId:n?`${n}`:"",organizationId:s?`${s}`:"",veltFolderId:a?`${a}`:void 0});switch(t){case"userConfig":return e?.userId&&o?.userConfig?`${o?.userConfig}/${e?.userId}${e?.documentId?`/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${e?.documentId}`:""}`:void 0;case"allPermissionsUsers":return o?.permissionsUsers?`${o?.permissionsUsers}`:void 0;case"comment":return e?.documentId&&e?.id&&o?.comment?`${o?.comment}/${e?.id}`:void 0;case"allComments":return e?.documentId&&o?.comment?`${o?.comment}`:void 0;case"multiThread":return e?.documentId&&e?.id&&o?.multiThread?`${o?.multiThread}/${e?.id}`:void 0;case"allMultiThreads":return e?.documentId&&o?.multiThread?`${o?.multiThread}`:void 0;case"crdt":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}`:void 0;case"allLastNotificationTimestamp":return o?.lastNotificationTimestamp?`${o?.lastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return e?.id&&o?.lastNotificationTimestamp?`${o?.lastNotificationTimestamp}/${e?.id}`:void 0;case"activity":return e?.id&&o?.activities?`${o?.activities}/${e?.id}`:void 0;case"allActivities":return o?.activities?`${o?.activities}`:void 0;case"allLastActivityTimestamp":return o?.lastActivityTimestamp?`${o?.lastActivityTimestamp}`:void 0;case"lastActivityTimestamp":return e?.id&&o?.lastActivityTimestamp?`${o?.lastActivityTimestamp}/${e?.id}`:void 0;case"area":return e?.documentId&&e?.id&&o?.area?`${o?.area}/${e?.id}`:void 0;case"allAreas":return e?.documentId&&o?.area?`${o?.area}`:void 0;case"allDocuments":return o?.document?`${o?.document}`:void 0;case"allLocations":return o?.location?`${o?.location}`:void 0;case"allFolders":return o?.folder?`${o?.folder}`:void 0;case"folder":return o?.folder&&e.folderId?`${o?.folder}/${e.folderId}`:void 0;case"documentUserAccess":return e?.documentId&&e?.id&&o?.documentUsers?`${o?.documentUsers}/${e?.id}`:void 0;case"reaction":return e?.documentId&&e?.id&&o?.reaction?`${o?.reaction}/${e?.id}`:void 0;case"allReactions":return e?.documentId&&o?.reaction?`${o?.reaction}`:void 0;case"recorder":return e?.documentId&&e?.id&&o?.recorder?`${o?.recorder}/${e?.id}`:void 0;case"allRecorders":return e?.documentId&&o?.recorder?`${o?.recorder}`:void 0;case"recorderTrackEvent":return e?.documentId&&e?.id&&o?.recorder?`${o?.recorder}/${e?.id}/trackRecorderEvent`:void 0;case"documentAccessType":return e?.documentId&&o?.document?`${o?.document}/${e?.documentId}`:void 0;case"apiKeyMetadata":return r?`apiKey/${r}`:void 0;case"organizationMetadata":return o?.organization?`${o?.organization}`:void 0;case"documentIam":case"documentMetadata":return e?.documentId&&o?.document?`${o?.document}/${e?.documentId}`:void 0;case"folderMetadata":return e?.folderId&&o?.folder?`${o?.folder}/${e?.folderId}`:void 0;case"locationMetadata":return e?.documentId&&o?.location&&e?.id?`${o?.location}/${e?.id}`:void 0;case"documentUser":return e?.documentId&&e?.id&&o?.documentUsers?`${o?.documentUsers}/${e?.id}`:void 0;case"allDocumentUsers":return o?.users?`${o?.users}`:void 0;case"allFolderUsers":return o?.users?`${o?.users}`:void 0;case"allOrganizationGroups":return o?.organizationGroups?`${o?.organizationGroups}`:void 0;case"allOrganizationUsers":return o?.users?`${o?.users}`:void 0;case"notificationViewsTimestamp":return e?.documentId&&e?.id&&o?.notificationViews?`${o?.notificationViews}/${e?.id}`:void 0;case"allDocumentViews":return e?.documentId&&o?.documentViews?`${o?.documentViews}`:void 0;case"documentViews":case"documentMetadataViews":case"documentDayViews":case"documentUsersViews":return e?.documentId&&e?.id&&o?.documentViews?`${o?.documentViews}/${e?.id}`:void 0;case"locationDayViews":case"locationUsersViews":case"locationViews":case"locationMetadataViews":case"location":return e?.documentId&&e?.id&&o?.locationViews?`${o?.locationViews}/${e?.id}`:void 0;case"allLocationViews":return e?.documentId&&o?.locationViews?`${o?.locationViews}`:void 0;case"allDocNotifications":return e?.documentId&&o?.docNotification?`${o?.docNotification}`:void 0;case"docNotificationViews":case"docNotification":return e?.documentId&&e?.id&&o?.docNotification?`${o?.docNotification}/${e?.id}`:void 0;case"userNotificationViews":case"userNotification":return e?.userId&&e?.id&&o?.notificationUsers?`${o?.notificationUsers}/${e?.userId}/${h.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}/${e?.id}`:void 0;case"allUserNotifications":return e?.userId&&o?.notificationUsers?`${o?.notificationUsers}/${e?.userId}/${h.FIREBASE_PARTIAL_PATH_USER_NOTIFICATION}`:void 0;default:throw new Error(`Unknown feature: ${t}`)}}catch(n){this.loggingService.catch("Error in CommonDbUtilsService getFirestorePath:",n);return}}getFirestoreCollectionGroupPath(t){try{switch(t){case"allComments":return h.FIREBASE_PARTIAL_PATH_COMMENT;case"allDocuments":return h.FIREBASE_PARTIAL_PATH_DOCS;case"allLocations":return h.FIREBASE_PARTIAL_PATH_LOCATION;case"allMultiThreads":return h.FIREBASE_PARTIAL_PATH_MULTI_THREAD;case"allAreas":return h.FIREBASE_PARTIAL_PATH_AREA;case"allReactions":return h.FIREBASE_PARTIAL_PATH_REACTION;case"allRecorders":return h.FIREBASE_PARTIAL_PATH_RECORDER;case"allDocumentViews":return h.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS;case"allLocationViews":return h.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS;case"allDocumentUsers":return h.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS;case"allFolderUsers":return h.FIREBASE_PARTIAL_PATH_FOLDER_USERS;default:throw new Error(`Unknown feature: ${t}`)}}catch(e){this.loggingService.catch("Error in CommonDbUtilsService getFirestoreCollectionGroupPath:",e);return}}getDocumentPath({feature:t,properties:e,defaultDocumentPaths:i,apiKey:r,useFirestore:n}){try{if(!r)return;let{documentId:s,organizationId:a}=e;a||(a=i?.organizationId);let o=new Ht({apiKey:r,documentId:s?`${s}`:"",organizationId:a?`${a}`:""});switch(t){case"userConfig":return e?.userId&&e?.documentId&&o?.userConfig?`${o?.userConfig}/${e?.userId}/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_CONFIGURATIONS}/${e?.documentId}`:void 0;case"allComments":return!n&&e?.documentId&&o?.comment?`${o?.comment}`:void 0;case"allGlobalContacts":return e?.documentId&&o?.globalContacts?`${o?.globalContacts}`:void 0;case"globalContacts":return e?.documentId&&e?.userId&&o?.globalContacts?`${o?.globalContacts}${e?.userId}`:void 0;case"groupContacts":return e?.documentId&&e?.groupId&&o?.groupContacts?`${o?.groupContacts}${e?.groupId}`:void 0;case"groupContactsUser":return e?.documentId&&e?.groupId&&e?.userId&&o?.groupContacts?`${o?.groupContacts}${e?.groupId}/${e?.userId}`:void 0;case"allLoginContacts":return e?.documentId&&e?.userId&&o?.logins?`${o?.logins}${e?.userId}/contacts`:void 0;case"allLogins":return e?.documentId&&o?.logins?`${o?.logins}`:void 0;case"logins":return e?.documentId&&e?.userId&&o?.logins?`${o?.logins}${e?.userId}`:void 0;case"customerMetadata":return o?.customerMetadata?`${o?.customerMetadata}`:void 0;case"allArrows":return e?.documentId&&o?.arrow?`${o?.arrow}`:void 0;case"arrow":return e?.documentId&&o?.arrow&&e.id?`${o?.arrow}${e.id}`:void 0;case"allCursors":return e?.documentId&&o?.cursor?`${o?.cursor}`:void 0;case"cursor":return e?.documentId&&o?.cursor&&e.id?`${o?.cursor}${e.id}`:void 0;case"flockUser":return e?.documentId&&o?.flock&&e.id?`${o?.flock}users/${e.id}`:void 0;case"flockSession":return e?.documentId&&o?.flock&&e.id?`${o?.flock}sessions/${e.id}`:void 0;case"allHuddleAttendees":return e?.documentId&&o?.huddle?`${o?.huddle}attendees`:void 0;case"huddleAttendee":return e?.documentId&&o?.huddle&&e.id?`${o?.huddle}attendees/${e.id}`:void 0;case"huddleAttendeeState":return e?.documentId&&o?.huddle&&e.id?`${o?.huddle}attendees/${e.id}/state`:void 0;case"allHuddleInvitees":return e?.documentId&&o?.huddle?`${o?.huddle}invitees`:void 0;case"huddleConnection":return e?.documentId&&o?.huddle&&e.id?`${o?.huddle}connections/${e.id}`:void 0;case"huddleIceCandidate":return e?.documentId&&o?.huddle&&e.id?`${o?.huddle}iceCandidates/${e.id}`:void 0;case"allHuddleIceCandidates":return e?.documentId&&o?.huddle?`${o?.huddle}iceCandidates`:void 0;case"allHuddleMessages":return e?.documentId&&o?.huddle?`${o?.huddle}messages`:void 0;case"huddleMessage":return e?.documentId&&o?.huddle&&e.id?`${o?.huddle}messages/${e.id}`:void 0;case"allLiveStates":return e?.documentId&&o?.liveState?`${o?.liveState}`:void 0;case"allLiveStateCustoms":return e?.documentId&&o?.liveState?`${o?.liveState}custom`:void 0;case"liveStateCustom":return e?.documentId&&o?.liveState&&e?.id?`${o?.liveState}custom/${e.id}`:void 0;case"liveStateSingleEditorMode":return e?.documentId&&o?.liveStateSingleEditorMode?`${o?.liveStateSingleEditorMode}`:void 0;case"liveStateAutoSyncState":return e?.documentId&&o?.liveState?`${o?.liveState}default/autoSyncState`:void 0;case"liveStateAutoSyncStateCurrent":return e?.documentId&&o?.liveState?`${o?.liveState}default/autoSyncState/current`:void 0;case"liveStateAutoSyncStateHistoryId":return e?.documentId&&o?.liveState&&e?.id?`${o?.liveState}default/autoSyncState/history/${e.id}`:void 0;case"presence":return e?.documentId&&o?.presence&&e?.userId?`${o?.presence}${e?.userId}`:void 0;case"allPresence":return e?.documentId&&o?.presence?`${o?.presence}`:void 0;case"workspaceIam":return o?.workspaceIam?`${o?.workspaceIam}`:void 0;case"selection":return e?.documentId&&o?.selection&&e?.userId?`${o?.selection}${e?.userId}`:void 0;case"allSelections":return e?.documentId&&o?.selection?`${o?.selection}`:void 0;case"syncVideoPlayer":return e?.documentId&&o?.syncVideoPlayer?`${o?.syncVideoPlayer}`:void 0;case"allTags":return e?.documentId&&o?.tag?`${o?.tag}`:void 0;case"tag":return e?.documentId&&o?.tag&&e?.id?`${o?.tag}${e?.id}`:void 0;case"userContactUs":return e?.documentId&&o?.userContactUs?`${o?.userContactUs}`:void 0;case"userFeedback":return e?.documentId&&o?.userFeedback?`${o?.userFeedback}`:void 0;case"userReportBug":return e?.documentId&&o?.userReportBugs?`${o?.userReportBugs}`:void 0;case"comment":return!n&&e?.documentId&&e?.id&&o?.comment?`${o?.comment}${e?.id}`:void 0;case"allMultiThreads":return!n&&e?.documentId&&o?.multiThread?`${o?.multiThread}`:void 0;case"crdt":return!n&&e?.documentId&&o?.crdt?`${o?.crdt}`:void 0;case"crdtData":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/data`:void 0;case"crdtSyncState":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/sync/state`:void 0;case"crdtSyncPresence":return e?.documentId&&e.userId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/sync/presence/${e.userId}`:void 0;case"allCrdtSyncPresence":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/sync/presence`:void 0;case"crdtPresence":return e?.documentId&&e.userId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/presence/${e.userId}`:void 0;case"allCrdtPresence":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/presence`:void 0;case"crdtVersion":return e?.documentId&&o?.crdt&&e?.id&&e?.versionId?`${o?.crdt}/${e?.id}/versions/${e?.versionId}`:void 0;case"crdtVersions":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/versions`:void 0;case"crdtMessages":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/messages`:void 0;case"crdtMessage":return e?.documentId&&o?.crdt&&e?.id&&e?.messageId?`${o?.crdt}/${e?.id}/messages/${e?.messageId}`:void 0;case"crdtSnapshot":return e?.documentId&&o?.crdt&&e?.id?`${o?.crdt}/${e?.id}/snapshot`:void 0;case"multiThread":return!n&&e?.documentId&&e?.id&&o?.multiThread?`${o?.multiThread}${e?.id}`:void 0;case"allLastNotificationTimestamp":return!n&&o?.organizationNotificationsLastNotificationTimestamp?`${o?.organizationNotificationsLastNotificationTimestamp}`:void 0;case"lastNotificationTimestamp":return!n&&e?.id&&o?.organizationNotificationsLastNotificationTimestamp?`${o?.organizationNotificationsLastNotificationTimestamp}${e?.id}`:void 0;case"documentIam":return!n&&e?.documentId&&o?.documentIam?`${o?.documentIam}`:void 0;case"allDocuments":return!n&&o?.docs&&e?.documentId?`${o?.docs}/${e?.documentId}/${h.FIREBASE_PARTIAL_PATH_METADATA}`:void 0;case"allAreas":return!n&&e?.documentId&&o?.area?`${o?.area}`:void 0;case"area":return!n&&e?.id&&o?.area?`${o?.area}${e?.id}`:void 0;case"folder":return!n&&e?.folderId&&o?.folder?`${o?.folder}${e?.folderId}`:void 0;case"documentUserAccess":return!n&&e?.id&&o?.documentIam?`${o?.documentIam}users/${e?.id}`:void 0;case"documentUser":return!n&&e?.documentId&&e?.id&&o?.documentIam?`${o?.documentIam}users/${e?.id}`:void 0;case"allDocumentUsers":return!n&&e?.documentId&&o?.documentIam?`${o?.documentIam}users/`:void 0;case"allOrganizationGroups":return!n&&o?.organizationGroups?`${o?.organizationGroups}`:void 0;case"allOrganizationUsers":return!n&&o?.organizationIam?`${o?.organizationIam}users/`:void 0;case"reaction":return!n&&e?.id&&o?.reaction?`${o?.reaction}${e?.id}`:void 0;case"allReactions":return!n&&e?.documentId&&o?.reaction?`${o?.reaction}`:void 0;case"recorder":return!n&&e?.documentId&&e?.id&&o?.recorder?`${o?.recorder}${e?.id}`:void 0;case"allRecorders":return!n&&e?.documentId&&o?.recorder?`${o?.recorder}`:void 0;case"organizationMetadata":return!n&&o?.organizationMetadata?`${o?.organizationMetadata}`:void 0;case"heartbeat":return e?.id&&o?.heartbeat?`${o?.heartbeat}${e?.id}`:void 0;case"allHeartbeats":return o?.heartbeat?`${o?.heartbeat}`:void 0;case"heartbeatByDocument":return e?.id&&o?.heartbeatByDocument?`${o?.heartbeatByDocument}${e?.id}`:void 0;case"allHeartbeatsByDocument":return o?.heartbeatByDocument?`${o?.heartbeatByDocument}`:void 0;case"documentAccessType":return!n&&o?.documentIam?`${o?.documentIam}`:void 0;case"documentMetadata":return!n&&e?.documentId&&o?.metadata?`${o?.metadata}`:void 0;case"allDocumentViews":return!n&&e?.documentId&&o?.views?`${o?.views}documentViews/`:void 0;case"documentViews":return!n&&e?.documentId&&e?.id&&o?.views?`${o?.views}documentViews/${e?.id}`:void 0;case"allLocationViews":return!n&&e?.documentId&&o?.views?`${o?.views}locationViews/`:void 0;case"notificationViewsTimestamp":return!n&&e?.id&&e?.user&&o?.views?`${o?.views}notification/${e?.id}/views/${e?.user}`:void 0;case"documentUsersViews":return!n&&e?.id&&e?.user&&e?.date&&o?.views?`${o?.views}documentViews/${e?.id}/users/${e?.user}/${e?.date}`:void 0;case"documentMetadataViews":return!n&&e?.id&&o?.views?`${o?.views}documentViews/${e?.id}/metadata`:void 0;case"documentDayViews":return!n&&e?.id&&e?.date&&e?.user&&o?.views?`${o?.views}documentViews/${e?.id}/day/${e?.date}/${e?.user}`:void 0;case"locationViews":return!n&&e?.id&&o?.views?`${o?.views}locationViews/${e?.id}/location`:void 0;case"location":return!n&&e?.id&&o?.views?`${o?.views}locationViews/${e?.id}`:void 0;case"locationUsersViews":return!n&&e?.id&&e?.user&&e?.date&&o?.views?`${o?.views}locationViews/${e?.id}/users/${e?.user}/${e?.date}`:void 0;case"locationMetadataViews":return!n&&e?.id&&o?.views?`${o?.views}locationViews/${e?.id}/metadata`:void 0;case"locationDayViews":return!n&&e?.id&&e?.date&&e?.user&&o?.views?`${o?.views}locationViews/${e?.id}/day/${e?.date}/${e?.user}`:void 0;case"docNotificationViews":case"docNotification":return e?.documentId&&e?.id&&o?.organizationNotificationsWithDocumentId?`${o?.organizationNotificationsWithDocumentId}${e?.id}`:void 0;case"allDocNotifications":return e?.documentId&&o?.organizationNotificationsWithDocumentId?`${o?.organizationNotificationsWithDocumentId}`:void 0;case"allUserNotifications":return e?.userId&&o?.organizationNotificationsUsers?`${o?.organizationNotificationsUsers}${e?.userId}`:void 0;case"userNotificationViews":case"userNotification":return e?.userId&&e?.id&&o?.organizationNotificationsUsers?`${o?.organizationNotificationsUsers}${e?.userId}/${e?.id}`:void 0;case"locationMetadata":return;case"allLocations":return;case"folderMetadata":return;case"allPermissionsUsers":return;default:throw new Error(`Unknown feature: ${t}`)}}catch(s){this.loggingService.catch("Error in CommonDbUtilsService getDocumentPath:",s);return}}resolveAnnotations(i){return A(this,arguments,function*({data:t,feature:e}){try{if(t&&t?.length>0)switch(e){case"allComments":{if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let r=b(),n=Qe.GET_COMMENT_ANNOTATIONS;this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:j.RESOLVE_COMMENT_ANNOTATIONS,moduleName:n,source:"internal",payload:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:r,moduleName:n})}break}case"allReactions":{if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let r=b(),n=Ye.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:n,source:"internal",payload:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:r,moduleName:n})}break}case"allRecorders":{if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let r=b(),n=Ze.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:n,source:"internal",payload:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""}}),this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:t,organizationId:this.docService.getDocumentPaths()?.clientOrganizationId??""},uniqueId:r,moduleName:n})}break}default:break}}catch(r){this.loggingService.catch(`Error in CommonDbUtilsService resolveAnnotations: ${e}`,r)}})}formatResponse(g){return A(this,arguments,function*({feature:t,data:e,organizationId:i,shouldAwait:r=!1,forceResolve:n=!1,shouldCommentAnnotationsResolverAwait:s=!1,shouldNotificationResolverAwait:a=!1,shouldActivityResolverAwait:o=!1,shouldReactionResolverAwait:l=!1,shouldRecorderResolverAwait:u=!1}){try{let f=i??this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId??"";if(this.usersService.userDataProviderAvailable()){let d=[];switch(t){case"allAreas":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.areaUtilsService.getUserIdsToResolveFromAreaAnnotations(Object.values(e)));break}case"allArrows":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(Dt)?.getUserIdsToResolveFromArrowAnnotations(Object.values(e))??[]);break}case"allCursors":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(Ot)?.getUserIdsToResolveFromCursorUsers(Object.values(e))??[]);break}case"allComments":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.commentUtilsService.getUserIdsToResolveFromComments(Object.values(e)));break}case"allDocumentUsers":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(e)));break}case"allFolderUsers":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(e)));break}case"allOrganizationUsers":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.contactUtilsService.getUserIdsToResolveFromUserIamData(Object.values(e)));break}case"allMultiThreads":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.multiThreadUtilsService.getUserIdsToResolveFromMultiThreads(Object.values(e)));break}case"allDocNotifications":{e&&typeof e=="object"&&(d=this.serviceBook.get(ve)?.getUserIdsToResolveFromNotifications(Array.isArray(e)?e:Object.values(e))??[]);break}case"allUserNotifications":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(ve)?.getUserIdsToResolveFromNotifications(Object.values(e))??[]);break}case"allPresence":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(Ct)?.getUserIdsToResolveFromPresenceUsers(Object.values(e))??[]);break}case"allRecorders":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(ue)?.getUserIdsToResolveFromRecorders(Object.values(e))??[]);break}case"allReactions":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.reactionUtilsService.getUserIdsToResolveFromReactions(Object.values(e)));break}case"allTags":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.tagUtilsService.getUserIdsToResolveFromTags(Object.values(e)));break}case"allHuddleAttendees":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.serviceBook.get(pt)?.getUserIdsToResolveFromHuddleAttendees(Object.values(e))??[]);break}case"liveStateCustom":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustom(e));break}case"allLiveStateCustoms":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateCustoms(Object.values(e)));break}case"allLiveStates":{e&&typeof e=="object"&&(d=this.liveStateUtilsService.getUserIdsToResolveFromLiveStates(e));break}case"liveStateSingleEditorMode":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.liveStateUtilsService.getUserIdsToResolveFromLiveStateSingleEditorMode(e));break}case"allSelections":{e&&typeof e=="object"&&!Array.isArray(e)&&(d=this.selectionUtilsService.getUserIdsToResolveFromSelections(Object.values(e)));break}case"allActivities":{e&&typeof e=="object"&&(d=this.activityUtilsService.getUserIdsToResolveFromActivities(Array.isArray(e)?e:Object.values(e)));break}default:d=[]}if(d?.length){let m=b(),O=ht.GET_USERS;this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:ce.FORMAT_RESPONSE,source:"internal",moduleName:O,payload:{userIds:d,feature:t,forceResolve:n}}),r?yield this.usersService.resolveUsers({userIds:d,forceResolve:n,feature:t,organizationId:i,uniqueId:m,moduleName:O}):this.usersService.resolveUsers({userIds:d,forceResolve:n,feature:t,organizationId:i,uniqueId:m,moduleName:O})}}if(this.notificationResolverService.notificationDataProviderAvailable()){let d=[];switch(t){case"allDocNotifications":case"allUserNotifications":{e&&typeof e=="object"&&(d=this.serviceBook.get(ve)?.getCustomNotificationIdsToResolve(e)??[],d=d.filter(O=>!this.notificationResolverService.getNotificationById(O)));break}default:d=[]}if(d?.length){let m=b(),O=Di.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:re.FORMAT_RESPONSE,moduleName:O,source:"internal",payload:{notificationIds:d,organizationId:f,shouldNotificationResolverAwait:a}}),a?yield this.notificationResolverService.resolveNotifications({request:{notificationIds:d,organizationId:f},uniqueId:m,moduleName:O}):this.notificationResolverService.resolveNotifications({request:{notificationIds:d,organizationId:f},uniqueId:m,moduleName:O})}}if(this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()){let d=[];switch(t){case"allDocNotifications":{if(e&&typeof e=="object"){let O=this.serviceBook.get(ve)?.getTargetAnnotationIdsFromNotifications(e)??[];d=[...d,...O],d=d.filter(D=>!this.commentAnnotationsResolverService.getCommentAnnotationById(D))}break}case"allUserNotifications":{if(e&&typeof e=="object"&&!Array.isArray(e)){let O=this.serviceBook.get(ve)?.getTargetAnnotationIdsFromNotifications(e)??[];d=[...d,...O],d=d.filter(D=>!this.commentAnnotationsResolverService.getCommentAnnotationById(D))}break}case"allActivities":{if(e&&typeof e=="object"){let m=Array.isArray(e)?e:Object.values(e),O=this.activityUtilsService.getEntityIdsToResolveFromActivities(m,"comment");d=[...d,...O],d=d.filter(D=>!this.commentAnnotationsResolverService.getCommentAnnotationById(D))}break}default:d=[]}if(d?.length){let m=b(),O=Qe.GET_NOTIFICATIONS;this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:j.FORMAT_RESPONSE,moduleName:O,source:"internal",payload:{commentAnnotationIds:d,organizationId:f,shouldCommentAnnotationsResolverAwait:s}}),s?yield this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:d,organizationId:f},uniqueId:m,moduleName:O}):this.commentAnnotationsResolverService.resolveCommentAnnotations({request:{commentAnnotationIds:d,organizationId:f},uniqueId:m,moduleName:O})}}if(t==="allActivities"&&e&&typeof e=="object"){let d=Array.isArray(e)?e:Object.values(e),m=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(this.activityResolverService.activityDataProviderAvailable()){let O=[];for(let D of d)D?.id&&!this.activityResolverService.getActivityById(D.id)&&O.push(D.id);if(O.length){let D=b(),U=Oi.GET_ACTIVITIES;this.coreActionsService.triggerAction(E.ACTIVITY_RESOLVER,{event:v.Events.Resolver.ACTIVITY_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,methodName:le.FORMAT_RESPONSE,moduleName:U,source:"internal",payload:{activityIds:O,organizationId:m,shouldActivityResolverAwait:o}}),o?yield this.activityResolverService.resolveActivities({request:{activityIds:O,organizationId:m},uniqueId:D,moduleName:U}):this.activityResolverService.resolveActivities({request:{activityIds:O,organizationId:m},uniqueId:D,moduleName:U})}}if(this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()){let O=this.activityUtilsService.getEntityIdsToResolveFromActivities(d,"reaction");if(O=O.filter(D=>!this.reactionAnnotationsResolverService.getAnnotationById(D)),O.length){let D=b(),U=Ye.GET_REACTION_ANNOTATIONS;this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,methodName:x.RESOLVE_REACTION_ANNOTATIONS,moduleName:U,source:"internal",payload:{reactionAnnotationIds:O,organizationId:m,shouldReactionResolverAwait:l}}),l?yield this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:O,organizationId:m},uniqueId:D,moduleName:U}):this.reactionAnnotationsResolverService.resolveReactionAnnotations({request:{reactionAnnotationIds:O,organizationId:m},uniqueId:D,moduleName:U})}}if(this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()){let O=this.activityUtilsService.getEntityIdsToResolveFromActivities(d,"recorder");if(O=O.filter(D=>!this.recorderAnnotationsResolverService.getAnnotationById(D)),O.length){let D=b(),U=Ze.GET_RECORDER_ANNOTATIONS;this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:D,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,moduleName:U,source:"internal",payload:{recorderAnnotationIds:O,organizationId:m,shouldRecorderResolverAwait:u}}),u?yield this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:O,organizationId:m},uniqueId:D,moduleName:U}):this.recorderAnnotationsResolverService.resolveRecorderAnnotations({request:{recorderAnnotationIds:O,organizationId:m},uniqueId:D,moduleName:U})}}}return e}catch(f){return this.loggingService.catch("Error in CommonDbUtilsService formatResponse:",f),e}})}mergeCommentAnnotationsWithData({data:t,feature:e}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeCommentAnnotationsWithData","color: green;"),this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())switch(e){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[r,n])=>(i[r]=this.commentUtilsService.mergeStrippedDataWithCommentAnnotations(n),i),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let i=this.serviceBook.get(ve);return Object.entries(t).reduce((r,[n,s])=>(r[n]=i?i.mergeStrippedDataWithNotification(s):s,r),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeCommentAnnotationsWithData:",i),t}}mergeActivityResolverWithData({data:t,feature:e}){try{return this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeActivityResolverWithData","color: green;"),this.activityResolverService.activityDataProviderAvailable()&&e==="allActivities"&&Array.isArray(t)?t.map(i=>this.activityUtilsService.mergeActivityWithResolverData(i)):t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeActivityResolverWithData:",i),t}}mergeNotificationsWithResolvedData({data:t,feature:e}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeNotificationsWithResolvedData","color: green;"),this.notificationResolverService.notificationDataProviderAvailable())switch(e){case"allDocNotifications":case"allUserNotifications":{let i=this.serviceBook.get(ve);return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[n,s])=>(r[n]=i?i.mergeResolvedNotificationData(s):s,r),{}):Array.isArray(t)?t.map(r=>i?i.mergeResolvedNotificationData(r):r):t}default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeNotificationsWithResolvedData:",i),t}}mergeNotificationsWithResolvedData$({data:t,feature:e}){try{return this.notificationResolverService.getNotificationsById$().pipe(k(()=>{let i=this.mergeNotificationsWithResolvedData({data:t?.data??{},feature:e}),r=this.mergeUsersWithData({feature:e,data:i??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),q(X))}catch(i){return this.loggingService.catch("Error in mergeNotificationsWithResolvedData$:",i),$(t)}}mergeReactionAnnotationsWithData({data:t,feature:e}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeReactionAnnotationsWithData","color: green;"),this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable())switch(e){case"allReactions":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((i,[r,n])=>(i[r]=this.reactionUtilsService.mergeStrippedDataWithReactionAnnotations(n),i),{}):t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeReactionAnnotationsWithData:",i),t}}mergeRecorderAnnotationsWithData({data:t,feature:e}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeRecorderAnnotationsWithData","color: green;"),this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable())switch(e){case"allRecorders":if(t&&typeof t=="object"&&!Array.isArray(t)){let i=this.serviceBook.get(ue);return Object.entries(t).reduce((r,[n,s])=>(r[n]=i?i.mergeStrippedDataWithRecorderAnnotation(s):s,r),{})}else return t;case"allActivities":return this.mergeActivitiesWithFeatureData(t);default:return t}return t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeRecorderAnnotationsWithData:",i),t}}mergeActivitiesWithFeatureData(t){return Array.isArray(t)?t.map(e=>this.activityUtilsService.mergeActivityWithFeatureData(e)):t}mergeLocationMetadataWithData({data:t,feature:e,locationMetadata:i}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeLocationMetadataWithData","color: green;"),i&&typeof i=="object"&&!Array.isArray(i))switch(e){case"allComments":return t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).reduce((r,[n,s])=>(r[n]=this.commentUtilsService.mergeLocationWithCommentAnnotations(s,i),r),{}):t;case"allDocNotifications":case"allUserNotifications":if(t&&typeof t=="object"&&!Array.isArray(t)){let r=this.serviceBook.get(ve);return Object.entries(t).reduce((n,[s,a])=>(n[s]=r?r.mergeLocationWithNotification(a,i):a,n),{})}else return t;default:return t}return t}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService mergeLocationMetadataWithData:",r),t}}mergeUsersWithData({feature:t,data:e}){try{if(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: mergeUsersWithData","color: green;"),this.usersService.userDataProviderAvailable())switch(t){case"allAreas":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.areaUtilsService.mergeAreaWithUser(n),i),{}):e;case"allArrows":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(Dt);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?i.mergeArrowWithUser(s):s,r),{})}else return e;case"allCursors":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(Ot);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?i.mergeCursorUserWithUser(s):s,r),{})}else return e;case"allComments":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.commentUtilsService.mergeCommentWithUser(n),i),{}):e;case"allDocumentUsers":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.contactUtilsService.mergeUserIamWithUser(n),i),{}):e;case"allFolderUsers":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.contactUtilsService.mergeUserIamWithUser(n),i),{}):e;case"allOrganizationUsers":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.contactUtilsService.mergeUserIamWithUser(n),i),{}):e;case"allMultiThreads":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.multiThreadUtilsService.mergeMultiThreadWithUser(n),i),{}):e;case"allDocNotifications":if(e&&typeof e=="object"){let i=this.serviceBook.get(ve);return e?.map(r=>i?i.mergeNotificationWithUser(r):r)}else return e;case"allUserNotifications":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(ve);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?i.mergeNotificationWithUser(s):s,r),{})}else return e;case"allPresence":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(Ct);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?i.mergePresenceUserWithUser(s):s,r),{})}else return e;case"allRecorders":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(ue);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?i.mergeRecorderWithUser(s):s,r),{})}else return e;case"allReactions":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.reactionUtilsService.mergeReactionWithUser(n),i),{}):e;case"allTags":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.tagUtilsService.mergeTagWithUser(n),i),{}):e;case"allHuddleAttendees":if(e&&typeof e=="object"&&!Array.isArray(e)){let i=this.serviceBook.get(pt);return Object.entries(e).reduce((r,[n,s])=>(r[n]=i?.mergeHuddleAttendeeWithUser(s)??s,r),{})}else return e;case"liveStateCustom":return e&&typeof e=="object"&&!Array.isArray(e)?this.liveStateUtilsService.mergeLiveStateCustomWithUser(e):e;case"allLiveStateCustoms":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.liveStateUtilsService.mergeLiveStateCustomWithUser(n),i),{}):e;case"allLiveStates":return e&&typeof e=="object"?this.liveStateUtilsService.mergeLiveStateWithUser(e):e;case"liveStateSingleEditorMode":return e&&typeof e=="object"&&!Array.isArray(e)?this.liveStateUtilsService.mergeSingleEditorLiveStateDataWithUser(e):e;case"allSelections":return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).reduce((i,[r,n])=>(i[r]=this.selectionUtilsService.mergeSelectionWithUser(n),i),{}):e;case"allActivities":return Array.isArray(e)?e.map(i=>this.activityUtilsService.mergeActivityWithUser(i)):e;default:return e}return e}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService mergeUsersWithData:",i),e}}mergeCommentAnnotationsWithData$({data:t,feature:e}){try{return this.commentAnnotationsResolverService.getCommentAnnotationsById$().pipe(k(()=>{let i=this.mergeCommentAnnotationsWithData({data:t?.data??{},feature:e}),r=this.mergeUsersWithData({feature:e,data:i??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),q(X))}catch(i){return this.loggingService.catch("Error in mergeCommentAnnotationsWithData:",i),$(t)}}mergeReactionAnnotationsWithData$({data:t,feature:e}){try{return this.reactionAnnotationsResolverService.getReactionAnnotationsById$().pipe(k(()=>{let i=this.mergeReactionAnnotationsWithData({data:t?.data??{},feature:e}),r=this.mergeUsersWithData({feature:e,data:i??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),q(X))}catch(i){return this.loggingService.catch("Error in mergeReactionAnnotationsWithData:",i),$(t)}}mergeRecorderAnnotationsWithData$({data:t,feature:e}){try{return this.recorderAnnotationsResolverService.getRecorderAnnotationsById$().pipe(k(()=>{let i=this.mergeRecorderAnnotationsWithData({data:t?.data??{},feature:e}),r=this.mergeUsersWithData({feature:e,data:i??{}});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),q(X))}catch(i){return this.loggingService.catch("Error in mergeRecorderAnnotationsWithData:",i),$(t)}}mergeUsersWithData$({feature:t,data:e}){try{return this.usersService.getUserById$().pipe(k(()=>{let i=this.mergeUsersWithData({feature:t,data:e?.data??{}});return typeof i=="object"?{data:JSON.parse(JSON.stringify(i)),operation:e?.operation??null}:{data:i,operation:e?.operation??null}}),q(X))}catch(i){return this.loggingService.catch(`Error in mergeUsersWithData for ${t}:`,i),$(e)}}mergeLocationMetadataWithData$({data:t,feature:e}){try{return this.docService.getLocationMetadata$().pipe(k(i=>{let r=this.mergeLocationMetadataWithData({data:t?.data??{},feature:e,locationMetadata:i});return typeof r=="object"?{data:JSON.parse(JSON.stringify(r)),operation:t?.operation??null}:{data:r,operation:t?.operation??null}}),q(X))}catch(i){return this.loggingService.catch(`Error in mergeLocationMetadataWithData for ${e}:`,i),$(t)}}handleDataStripping(n){return A(this,arguments,function*({feature:t,data:e,actionType:i,commentId:r}){try{switch(this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: handleDataStripping","color: green;"),t){case"comment":{let s=yield this.commentUtilsService.stripCommentAnnotationData({data:e,actionType:i,commentId:r});return this.filterOriginalDataForVeltDb({feature:t,result:s,providerAvailable:this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable()})}case"reaction":{let s=this.reactionUtilsService.stripReactionAnnotationData(e);return this.filterOriginalDataForVeltDb({feature:t,result:s,providerAvailable:this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable()})}case"recorder":{let s=this.serviceBook.get(ue)?.stripRecorderAnnotationData({data:e,actionType:i})??{originalData:e,strippedData:null};return this.filterOriginalDataForVeltDb({feature:t,result:s,providerAvailable:this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()})}default:return{originalData:e,strippedData:null}}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService handleDataStripping:",s),{originalData:e,strippedData:null}}})}filterOriginalDataForVeltDb({feature:t,result:e,providerAvailable:i}){try{return!i||!e||e.originalData===null||e.originalData===void 0?e:L(S({},e),{originalData:this.applyVeltDbFieldFilter(t,e.originalData,e)})}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService filterOriginalDataForVeltDb:",r),e}}applyVeltDbFieldFilter(t,e,i){switch(t){case"comment":return yt(e,{stripAttachmentFiles:this.attachmentResolverService.attachmentDataProviderAvailable(),keepContextText:!!i?.veltCopyKeepsContextText});case"reaction":return Mi(e);case"recorder":return Vi(e);default:return e}}formatData({feature:t,data:e,properties:i,offset:r,isRealtimeDb:n}){try{this.loggingService.log("%c[WB] Calling CommonDbUtilsService FUNCTION: formatData","color: green;"),typeof e=="object"&&(e=JSON.parse(JSON.stringify(e)));let s=new Date().getTime()+r;switch(t){case"documentAccessType":return delete e?.users,{docIamConfig:e};case"organizationMetadata":case"documentMetadata":return n?e:{metadata:e};case"documentCommentMetadata":return e;case"cursor":{let a=this.serviceBook.get(Ot);return a?a.formatCursorUserData(e):e}case"comment":return this.commentUtilsService.formatCommentData(e);case"area":return this.areaUtilsService.formatAreaData(e);case"arrow":{let a=this.serviceBook.get(Dt);return a?a.formatArrowData(e):e}case"liveStateCustom":return this.liveStateUtilsService.formatLiveStateCustomData(e);case"liveStateSingleEditorMode":return this.liveStateUtilsService.formatLiveStateSingleEditorModeData(e);case"multiThread":return this.multiThreadUtilsService.formatMultiThreadData(e);case"reaction":return this.reactionUtilsService.formatReactionData(e);case"recorder":return this.serviceBook.get(ue)?.formatRecorderData(e,s)??e;case"notificationViewsTimestamp":return{views:{[i.user??""]:e}};case"documentUsersViews":return n?e:{users:{[i.user??""]:{[i.date??""]:e}}};case"documentDayViews":return n?e:{day:{[i.date??""]:{[i.user??""]:e}}};case"documentMetadataViews":return n?e:{metadata:e};case"huddleMessage":return this.serviceBook.get(pt)?.formatHuddleMessageData(e)??e;case"locationMetadataViews":return n?e:{metadata:e};case"locationUsersViews":return n?e:{users:{[i.user??""]:{[i.date??""]:e}}};case"locationDayViews":return n?e:{day:{[i.date??""]:{[i.user??""]:e}}};case"locationViews":return n?e:{location:e};case"docNotificationViews":return n?e:{views:e.views};case"userNotificationViews":return n?e:{views:e.views};case"presence":{let a=this.serviceBook.get(Ct);return a?a.formatPresenceUserData(e):e}case"selection":return this.selectionUtilsService.formatSelectionData(e);case"tag":return this.tagUtilsService.formatTagData(e);default:return e}}catch(s){return this.loggingService.catch("Error in CommonDbUtilsService formatData:",s),e}}modifyAndSetData(n){return A(this,arguments,function*({feature:t,data:e,subscriber:i,operation:r=null}){try{let s=yield this.modifyData({feature:t,data:e});i.next({data:s,operation:r})}catch(s){this.loggingService.catch("Error in CommonDbUtilsService modifyAndSetData:",s)}})}isDataAlreadyProcessedInLocalCache({feature:t,change:e,cache:i}){try{if(t==="allReactions"||t==="allComments"){if(e.type==="removed")return!Object.keys(i??{}).includes(e.doc.id);if(i?.[e.doc.id]){let r=e.doc.data(),n=i?.[e.doc.id];return r?.lastUpdated===n?.lastUpdated}}return!1}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService isDataAlreadyProcessedInLocalCache:",r),!1}}modifyData(i){return A(this,arguments,function*({feature:t,data:e}){try{return yield this.formatResponse({feature:t,data:e})}catch(r){return this.loggingService.catch("Error in CommonDbUtilsService modifyData:",r),e}})}addMetadata(t,e){try{return t&&typeof t=="object"&&!Array.isArray(t)?L(S({},t),{metadata:t?.metadata??{documentId:e?.documentId,organizationId:e?.organizationId,apiKey:e?.apiKey}}):t}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService addMetadata:",i),t}}setDataInLocal(a){return A(this,arguments,function*({feature:t,data:e,observablesCache:i,eventType:r,id:n,operation:s=null}){try{let l={comment:"allComments",reaction:"allReactions"}[t];if(!l)return null;let u=e?.metadata?.documentId,g=e?.metadata?.veltFolderId;return Object.keys(i).filter(f=>f.includes(l)&&(!u||f.includes(u)||g&&f.includes(g))).forEach(f=>{let d=i[f]?.subject?.getValue()??{};r==="DELETE"?n&&d?.data?.[n]&&(delete d?.data?.[n],i[f]?.subject&&i[f].subject.next({data:d?.data,operation:s})):i[f]?.subject?.next({data:L(S({},d?.data),{[e?.annotationId]:e}),operation:s})}),null}catch(o){return this.loggingService.catch("Error in CommonDbUtilsService setDataInLocal:",o),null}})}handleCommentEncryption(s){return A(this,arguments,function*({data:t,firestorePath:e,extraData:i,eventType:r,metadata:n}){try{return yield this.commentUtilsService.handleCommentEncryption({data:t,firestorePath:e,extraData:i,eventType:r,metadata:n})}catch(a){return this.loggingService.catch("Error in CommonDbUtilsService handleCommentEncryption:",a),t}})}prepareCommentNotificationData({data:t,extraData:e}){return this.commentUtilsService.prepareCommentNotificationData({data:t,extraData:e})}getCommentNotificationDenialSteps(){return this.commentUtilsService.getCommentNotificationDenialSteps()}isPermissionProviderUsed(){return this.commentUtilsService.isPermissionProviderUsed()}handleReactionEncryption(r){return A(this,arguments,function*({data:t,firestorePath:e,eventType:i}){try{return yield this.reactionUtilsService.handleReactionEncryption({data:t,firestorePath:e,eventType:i})}catch(n){return this.loggingService.catch("Error in CommonDbUtilsService handleReactionEncryption:",n),t}})}rtdbDefaultTransactionCallback(t,e){try{let i=S({},t||{});return Object.entries(e).forEach(([r,n])=>{n==null?delete i[r]:i[r]=n}),i}catch(i){return this.loggingService.catch("Error in CommonDbUtilsService rtdbDefaultTransactionCallback:",i),t}}};c.\u0275fac=function(e){return new(e||c)(T(Wt),T(or),T(zt),T(sr),T(H),T(ar),T(B),T(cr),T(kt),T(lr),T(dr),T(K),T(qe),T(me),T(Re),T(Pe),T(Gt),T(xt),T(Ne),T(Ge))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var gr=(()=>{let c=class c{allow(){return Promise.resolve({allow:!0})}canRead(t){return A(this,null,function*(){return this.allow()})}canWrite(t){return A(this,null,function*(){return this.allow()})}};c.\u0275fac=function(e){return new(e||c)},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var wr=new Set(["unimplemented","invalid-argument"]),Br=new Set(["failed-precondition"]),Mr="portable transport not connected",fr="portable transport disconnected",Sr="portable transport send failed",Vr="portable request timed out",zr="portable request failed in transport",Ir=new Set([Mr,fr,Sr]),hi=new Set([fr,Vr,zr]);function Er(I){let c=I?.message;return typeof c=="string"&&hi.has(c)}var mr="portable publish op '",vr="' requires a channel on the OperationRequest";function kr(I){let c=I;return!c||c.code!=="failed-precondition"||c.reasonCode||typeof c.message!="string"||hi.has(c.message)?!1:Ir.has(c.message)||c.message.startsWith(mr)&&c.message.endsWith(vr)&&c.message.length>mr.length+vr.length}var jr="portable session that issued the frame ended before the transport was ready",xr="shutting_down",Wr=new Set(["docNotificationViews"]),Hr=new Set(["comment","reaction","documentViews","userNotificationViews","userNotification"]),Gr={crdtData:"the crdt message-log api (pushMessage / onMessage / getMessages)",crdtSyncState:"the crdt message-log api (saveSnapshot / getSnapshot)"},us=(()=>{let c=class c{constructor(t,e,i,r,n,s,a,o,l,u,g,f,d,m,O,D,U,y,R){this.activityUtilsService=t,this.authService=e,this.commonDbUtilsService=i,this.coreActionsService=r,this.loggingService=n,this.firestoreService=s,this.databaseService=a,this.configService=o,this.docService=l,this.usersService=u,this.commentAnnotationsResolverService=g,this.reactionAnnotationsResolverService=f,this.recorderAnnotationsResolverService=d,this.notificationResolverService=m,this.serviceBook=O,this.realtimeAdapter=D,this.dbAdapter=U,this.authzAdapter=y,this.adapterSelectorService=R,this.offset=0,this.db=null,this.firestore=null,this.subscriptions=[],this.offsetListener=null,this.serverTimeOffsetUnsub=null,this.portableOffset=0,this.portableOffsetUnsub=null,this.portableOffsetSourceUnsub=null,this.observablesCache={},this.reportedPortableRacedWrites=new Set,this.reportedPortableWriteDenials=new Set,this.reportedPortableUnservedReads=new Set,this.reportedDocChannelIdentityMismatches=new Set,this.reportedProviderCheckNeedsDocumentId=!1,this.firestoreSubscriptions={},this.rtdbSubscriptions={},this.loggingService.log("%c[WB] Creating CLASS: CommonDbService","color: blue;"),this.serviceBook.observe(ji).subscribe(p=>{this.activityService=p??void 0}),this.docService.setCommonDbService(this),this.authService.setCommonDbService(this),this.usersService.setCommonDbService(this),this.subscriptions.push(this.databaseService.getDb().subscribe(p=>{p&&(this.db=p)})),this.serverTimeOffsetUnsub=this.realtimeAdapter.onServerTimeOffset(p=>{this.offset=p}),this.portableOffsetUnsub=Pt(()=>{try{this.portableOffsetSourceUnsub?.(),this.portableOffsetSourceUnsub=this.adapterSelectorService?.resolveRealtimeAdapter().onServerTimeOffset(p=>{this.portableOffset=p})??null}catch(p){this.loggingService.catch("Error wiring portable server-time offset: ",p)}}),this.subscriptions.push(this.firestoreService.getFirestore().subscribe(p=>{p&&(this.firestore=p)}))}unsubscribeFromObservables(){try{Object.values(this.firestoreSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.values(this.rtdbSubscriptions??{}).forEach(t=>{t?.unsubscribe()}),Object.entries(this.observablesCache??{}).forEach(([t,e])=>{e?.subject?.complete(),e?.subject?.unsubscribe()}),this.observablesCache={},this.firestoreSubscriptions={},this.rtdbSubscriptions={}}catch(t){this.loggingService.catch("Error in unsubscribeFromObservables:",t)}}ngOnDestroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.offsetListener&&this.offsetListener(),this.serverTimeOffsetUnsub&&(this.serverTimeOffsetUnsub(),this.serverTimeOffsetUnsub=null),this.portableOffsetSourceUnsub?.(),this.portableOffsetSourceUnsub=null,this.portableOffsetUnsub?.(),this.portableOffsetUnsub=null,this.unsubscribeFromObservables()}setupOnDisconnect(t,e,i,r){return A(this,null,function*(){try{if(i&&this.isPortableChannelFeature(i)&&ii(rt(i))){let n=this.buildPortableChannelKey(i,r);if(n){let s=this.currentUserId();if(yield this.whenPortableRealtimeReady(),!this.isSamePortableIssuer(s)){this.discardPortableEphemeralFrame("onDisconnect",i);return}yield this.adapterSelectorService.resolveRealtimeAdapter().onDisconnect(n,e,{onResult:a=>this.reportPortableEphemeralOutcome("onDisconnect",i,a)})}else this.loggingService.catch(`Velt [portable backend]: could not build a channel key for the '${i}' disconnect intent \u2014 no cleanup was registered. A path-scoped presence feature needs its instance id in properties.id.`,void 0,void 0,!0);return}if(this.db){let n=this.realtimeAdapter.rtdbRef(this.db,t);return this.realtimeAdapter.rtdbOnDisconnectUpdate(i??"commondb",n,e)}return Promise.resolve()}catch(n){return this.loggingService.catch("Error in setupOnDisconnect:",n),Promise.resolve()}})}getOffset(){try{if(this.isPortableBackendActive())return this.portableOffset}catch{}return this.offset}getServerTimestamp(){return new Date().getTime()+this.getOffset()}subscribeToServices(t){Ve([this.databaseService.getDb(),this.firestoreService.getFirestore()]).pipe(Ie(([e,i])=>!!e),$e(1),dt(([e,i])=>{t({db:e,firestore:i})})).subscribe({error:e=>{this.loggingService.catch("Error in CommonDbService subscription: ",e)}})}performDatabaseOperation(t,e,i,r,n,s){return A(this,null,function*(){try{if(!e){this.loggingService.warn(`%c[WB] No properties found for ${t}`,"color: red;");return}if(this.isPortableUnservedWrite(t)){this.reportPortableUnservedWrite(t),n?.({ok:!1,code:"unimplemented",message:`'${t}' has no portable backend surface`});return}let a=!1,o=null;return this.isPortableBackendActive()||(o=Pt(()=>{try{if(o?.(),o=null,a)return;if(this.isPortableUnservedWrite(t)){a=!0,this.reportPortableUnservedWrite(t),n?.({ok:!1,code:"unimplemented",message:`'${t}' has no portable backend surface`});return}a=!0,this.reportedPortableRacedWrites.has(t)||(this.reportedPortableRacedWrites.add(t),this.loggingService.catch(`Velt [portable backend]: the write for '${t}' was issued before the portable transport registered and cannot be re-dispatched from this junction, so it was NOT persisted. This is a client-side ordering fault, not a backend denial.`,void 0,void 0,!0)),n?.({ok:!1,code:"failed-precondition",message:`'${t}' write raced portable activation and was not sent`})}catch(l){this.loggingService.catch(`Error in portable activation watch for ${t}: `,l)}})),this.subscribeToServices(g=>A(this,[g],function*({db:l,firestore:u}){if(a)return;a=!0,o?.(),o=null;let f;e?.skipFirestore||(f=this.commonDbUtilsService.getFirestorePath({feature:t,properties:e,documentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()}));let d=this.commonDbUtilsService.getDocumentPath({feature:t,properties:e,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey(),useFirestore:this.shouldUseFirestore()});if(!l){this.loggingService.warn(`%c[WB] No database or firestore found for ${t}`,"color: red;");return}try{let m,O;try{d&&(m=this.realtimeAdapter.rtdbRef(l,`${d}`))}catch{this.loggingService.catch("Error in dbRef")}try{f?.includes("/organizations")&&u&&f&&(O=this.dbAdapter.firestoreDoc(u,`${f}`))}catch{this.loggingService.catch("Error in docRef")}if(!this.authService.getUser())return;yield i({dbRef:m,firestoreRef:O,data:r,firestorePath:f}),s&&s({firestoreAvailable:!!u})}catch(m){this.loggingService.catch(`Error in ${t} operation: `,m),n&&n(m)}}))}catch(a){this.loggingService.catch("Error in performDatabaseOperation:",a)}})}setData(a){return A(this,arguments,function*({feature:t,data:e,properties:i,callback:r,errorCallback:n,extraData:s}){try{if(this.loggingService.log(`%c[WB] Calling FUNCTION: setData for ${t}`,"color: green;"),this.dropsWriteWithoutMetadataApiKey(t,e,"set"))return;if(this.commonDbUtilsService.setDataInLocal({feature:t,data:e,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,s),this.isPortableChannelFeature(t)){let o=it(t,"set");return o?this.invokePortableDbWriteOp(o,t,e,i,r,n,s):this.publishPortableChannelState(t,e,i,r,n)}return this.performDatabaseOperation(t,i,o=>A(this,null,function*(){if(o.dbRef){let l=this.commonDbUtilsService.formatData({feature:t,data:o.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,o.dbRef,()=>JSON.parse(JSON.stringify(l))):yield this.realtimeAdapter.rtdbSet(t,o.dbRef,JSON.parse(JSON.stringify(l)))}try{if(o.firestoreRef&&o.data&&!i?.skipFirestore){let l=this.commonDbUtilsService.formatData({feature:t,data:o.data,properties:i,offset:this.getOffset()});typeof l=="object"&&(l=JSON.parse(JSON.stringify(l)));let{strippedData:u,originalData:g,eventType:f}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:l,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId??i?.targetCommentId});if(t==="comment"){let d=null,m=b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:j.SET_DATA,source:"internal",payload:{strippedData:u,originalData:g,eventType:f,commentId:s?.targetAnnotationData?.commentId}}),u&&(d=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:u,eventType:f,commentId:s?.targetAnnotationData?.commentId},m)),g&&(d?.isSuccess||d===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:o.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(t==="reaction"){let d=null,m=b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:x.SET_DATA,source:"internal",payload:{strippedData:u,originalData:g}}),u&&(d=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(u,m)),g&&(d?.isSuccess||d===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:o.firestorePath??""}))}else if(t==="recorder"){let d=null,m=b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:W.SET_DATA,source:"internal",payload:{strippedData:u,originalData:g}}),u&&(d=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:u,eventType:f},m)),g&&(d?.isSuccess||d===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,O=>A(this,null,function*(){O.set(o.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(o.firestoreRef,l)}}catch(l){this.authService.getUser()&&this.loggingService.catch(`Error in setData for ${t}`,l)}}),e,n,r)}catch(o){this.loggingService.catch(`Error in setData for ${t}`,o)}})}updateData(a){return A(this,arguments,function*({feature:t,data:e,properties:i,callback:r,errorCallback:n,extraData:s}){try{if(this.loggingService.log(`%c[WB] Calling FUNCTION: updateData for ${t}`,"color: green;"),this.dropsWriteWithoutMetadataApiKey(t,e,"update"))return;if(this.commonDbUtilsService.setDataInLocal({feature:t,data:e,observablesCache:this.observablesCache,operation:null}),this.createActivityFromExtraData(t,s),this.isPortableChannelFeature(t)){let o=it(t,"update");return o?this.invokePortableDbWriteOp(o,t,e,i,r,n,s):this.publishPortableChannelState(t,e,i,r,n)}return this.performDatabaseOperation(t,i,o=>A(this,null,function*(){if(o.dbRef&&!i?.skipRtdb){let l=this.commonDbUtilsService.formatData({feature:t,data:o.data,properties:i,offset:this.getOffset(),isRealtimeDb:!0});i?.rtdbTransaction?yield this.realtimeAdapter.rtdbRunTransaction(t,o.dbRef,u=>{let g;return i?.rtdbTransactionCallback?g=i.rtdbTransactionCallback(u,l):g=this.commonDbUtilsService.rtdbDefaultTransactionCallback(u,l),JSON.parse(JSON.stringify(g))}):yield this.realtimeAdapter.rtdbUpdate(t,o.dbRef,JSON.parse(JSON.stringify(l)))}try{if(o.firestoreRef&&o.data&&!i?.skipFirestore){let l=this.commonDbUtilsService.formatData({feature:t,data:o.data,properties:i,offset:this.getOffset()});typeof l=="object"&&(l=JSON.parse(JSON.stringify(l)));let{strippedData:u,originalData:g,eventType:f}=yield this.commonDbUtilsService.handleDataStripping({feature:t,data:l,actionType:s?.actionType,commentId:s?.targetAnnotationData?.commentId});if(t==="comment"){let d=null,m=b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:j.UPDATE_DATA,source:"internal",payload:{strippedData:u,originalData:g,eventType:f,commentId:s?.targetAnnotationData?.commentId}}),u&&(d=yield this.commentAnnotationsResolverService.saveCommentAnnotation({commentAnnotation:u,eventType:f,commentId:s?.targetAnnotationData?.commentId},m)),g&&(d?.isSuccess||d===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({data:g,firestorePath:o.firestorePath??"",extraData:s,metadata:i?.metadata}))}else if(t==="reaction"){let d=null,m=b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:x.UPDATE_DATA,source:"internal",payload:{strippedData:u,originalData:g}}),u&&(d=yield this.reactionAnnotationsResolverService.saveReactionAnnotation(u,m)),g&&(d?.isSuccess||d===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({data:g,firestorePath:o.firestorePath??""}))}else if(t==="recorder"){let d=null,m=b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:m,methodName:W.UPDATE_DATA,source:"internal",payload:{strippedData:u,originalData:g}}),u&&(d=yield this.recorderAnnotationsResolverService.saveRecorderAnnotation({recorderAnnotation:u,eventType:f},m)),g&&(d?.isSuccess||d===null)&&this.firestore&&(yield this.dbAdapter.firestoreRunTransaction(this.firestore,O=>A(this,null,function*(){O.set(o.firestoreRef,JSON.parse(JSON.stringify(g)))})))}else yield this.dbAdapter.firestoreSetDoc(o.firestoreRef,l,{merge:!0})}}catch(l){this.authService.getUser()&&this.loggingService.catch(`Error in updateDoc for ${t}`,l)}}),e,n,r)}catch(o){this.loggingService.catch(`Error in updateData for ${t}`,o)}})}createActivityFromExtraData(t,e){try{if(!e?.actionType||!this.activityService)return;let i=this.activityUtilsService.buildActivityDataFromExtraData({feature:t,extraData:e});i&&this.activityService.createActivity(i)}catch(i){this.loggingService.catch("Error in CommonDbService createActivityFromExtraData:",i)}}deleteData(a){return A(this,arguments,function*({feature:t,properties:e,callback:i,errorCallback:r,extraData:n,hubNotification:s}){try{if(this.loggingService.log(`%c[WB] Calling FUNCTION: deleteData for ${t}`,"color: green;"),this.commonDbUtilsService.setDataInLocal({feature:t,observablesCache:this.observablesCache,eventType:"DELETE",id:e?.id,operation:{type:"removed",ids:[e?.id]}}),this.createActivityFromExtraData(t,n),this.isPortableChannelFeature(t)){let o=it(t,"delete");if(o)return this.invokePortableDbWriteOp(o,t,void 0,e,i,r,s);if(Yi(t)){this.loggingService.warn(`[WB] No portable delete op mapped for ${t}`),r?.({ok:!1,code:"unimplemented"});return}return this.publishPortableChannelState(t,{userId:e?.userId,userSnippylyId:e?.userId,onlineStatus:h.PRESENCE_STATUS_OFFLINE,timestamp:this.getServerTimestamp()},e,i,r)}return this.performDatabaseOperation(t,e,o=>A(this,null,function*(){o.dbRef&&(yield this.realtimeAdapter.rtdbRemove(t,o.dbRef));try{if(o.firestoreRef&&!e?.skipFirestore)if(t==="comment"){let l=null,u=b();this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:j.DELETE_DATA,source:"internal",payload:{commentAnnotationId:e?.id??"",metadata:e?.metadata}}),l=yield this.commentAnnotationsResolverService.deleteCommentAnnotation(e?.id??"",e?.metadata,u),(l?.isSuccess||l===null)&&(yield this.commonDbUtilsService.handleCommentEncryption({firestorePath:o.firestorePath??"",eventType:"DELETE",metadata:e?.metadata}))}else if(t==="reaction"){let l=null,u=b();this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:x.DELETE_DATA,source:"internal",payload:{reactionAnnotationId:e?.id??"",metadata:e?.metadata}}),l=yield this.reactionAnnotationsResolverService.deleteReactionAnnotation(e?.id??"",e?.metadata,u),(l?.isSuccess||l===null)&&(yield this.commonDbUtilsService.handleReactionEncryption({firestorePath:o.firestorePath??"",eventType:"DELETE"}))}else if(t==="recorder"){let l=null,u=b();this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:W.DELETE_DATA,source:"internal",payload:{recorderAnnotationId:e?.id??"",metadata:e?.metadata}}),l=yield this.recorderAnnotationsResolverService.deleteRecorderAnnotation(e?.id??"",e?.metadata,u),(l?.isSuccess||l===null)&&(yield this.dbAdapter.firestoreDeleteDoc(o.firestoreRef))}else if(t==="userNotification"){let l=null,u=b();this.coreActionsService.triggerAction(E.NOTIFICATION_RESOLVER,{event:v.Events.Resolver.NOTIFICATION_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:re.DELETE_DATA,source:"internal",payload:{notificationId:e?.id??"",organizationId:e?.organizationId??""}}),l=yield this.notificationResolverService.deleteNotification(String(e?.id??""),this.docService.getDocumentPaths()?.clientOrganizationId??"",u),(l?.isSuccess||l===null)&&(yield this.dbAdapter.firestoreDeleteDoc(o.firestoreRef))}else yield this.dbAdapter.firestoreDeleteDoc(o.firestoreRef)}catch(l){this.authService.getUser()&&this.loggingService.catch(`Error in deleteData for ${t}`,l)}}),void 0,r,i)}catch(o){this.loggingService.catch(`Error in deleteData for ${t}`,o)}})}shouldUseFirestore(){try{return this.authService.getAdvancedQueriesEnabled(this.isPortableSession())}catch(t){return this.loggingService.catch("Error in shouldUseFirestore:",t),!1}}canAskPortableOrganizationUsers(){try{return this.isPortableBackendActive()&&typeof this.adapterSelectorService?.resolveDbAdapter()?.getOrganizationUsers=="function"}catch(t){return this.loggingService.catch("Error in canAskPortableOrganizationUsers:",t),!1}}getPortableOrganizationUsers(t){return A(this,null,function*(){try{return yield this.adapterSelectorService.resolveDbAdapter().getOrganizationUsers({scope:"org",data:t})}catch(e){return this.loggingService.catch("Error in getPortableOrganizationUsers:",e),{ok:!1,code:"failed-precondition",message:Sr}}})}isPortableSession(){try{return this.adapterSelectorService?.isPortableSession?.()===!0}catch(t){return this.loggingService.catch("Error in isPortableSession:",t),!1}}generateDocumentId(){try{let t=this.firestoreService.generateFirestoreDocumentId();return t||(t=b()),t||"noDocumentId"}catch(t){return this.loggingService.catch("Error in generateFirestoreDocumentId:",t),b()||"noDocumentId"}}queryData(i){return A(this,arguments,function*({feature:t,properties:e}){try{let r=this.shouldUseFirestore();return!t||!e?(this.loggingService.warn("[WB] Missing required parameters in queryData"),[]):r?yield this.handleFirestoreQuery(t,e):yield this.handleRtdbQuery(t,e)}catch(r){return this.loggingService.catch(`Error in queryData for ${t}`,r),[]}})}handleFirestoreQuery(t,e){return A(this,null,function*(){try{if(!this.firestore)return this.loggingService.warn("[WB] Firestore not initialized"),[];let i=e?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:e,documentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),[];try{let r=this.dbAdapter.firestoreCollection(this.firestore,i);e?.useCollectionGroup&&(r=this.dbAdapter.firestoreCollectionGroup(this.firestore,i));let n=e?.firestoreQuery??[],s=this.dbAdapter.firestoreQuery(r,...n);if(!this.authService.getUser()&&!e?.skipUserCheck)return[];if(e?.getCount)try{let a=yield this.dbAdapter.firestoreGetCountFromServer(s).catch(o=>(this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,o),null));return a?a.data().count:0}catch(a){return this.authService.getUser()&&this.loggingService.catch(`Error in getCountFromServer for ${t}`,a),0}else try{let a=yield this.dbAdapter.firestoreGetDocs(s).catch(l=>(this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,l),null));if(!a)return[];let o=a.docs.map(l=>l.data());try{return yield this.commonDbUtilsService.modifyData({feature:t,data:o})}catch(l){return this.loggingService.catch(`Error in modifyData for ${t}`,l),o}}catch(a){return this.authService.getUser()&&this.loggingService.catch(`Error in getDocs for ${t}`,a),[]}}catch(r){return this.loggingService.catch(`Error in Firestore query for ${t}:`,r),[]}}catch(i){return this.loggingService.catch(`Error in Firestore query for ${t}:`,i),[]}})}handleRtdbQuery(t,e){return A(this,null,function*(){if(!this.db)return this.loggingService.warn("[WB] Realtime Database not initialized"),[];let i=this.commonDbUtilsService.getDocumentPath({feature:t,properties:e,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()});if(!i)return this.loggingService.warn(`[WB] No database path found for ${t}`),[];try{let r=this.realtimeAdapter.rtdbRef(this.db,i),n=e?.rtdbQuery??[],s=this.realtimeAdapter.rtdbQueryRef(r,...n);if(!this.authService.getUser()&&!e?.skipUserCheck)return[];let a=yield this.realtimeAdapter.rtdbGet(s).catch(l=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,l),null));if(!a)return[];let o=a.val();return o?e?.skipObjectValues?o:Object.values(o??{}):[]}catch(r){return this.loggingService.catch(`Error in RTDB query for ${t}:`,r),[]}})}buildAuthzRequest(t,e){return{feature:t,scope:"doc",resourceId:e?.id!=null?String(e.id):void 0,apiKey:e?.apiKey??this.configService.getApiKey()??void 0,organizationId:e?.organizationId!=null?String(e.organizationId):void 0,documentId:e?.documentId!=null?String(e.documentId):void 0}}getData(i){return A(this,arguments,function*({feature:t,properties:e}){try{let r=this.shouldUseFirestore();if(e?.skipFirestore&&(r=!1),!t||!e)return this.loggingService.warn("[WB] Missing required parameters in getData"),{};try{if(Ki(t)&&this.isPortableBackendActive())return yield this.invokePortableDbRead(t,e)}catch(n){return this.loggingService.catch(`Error in getData portable branch for ${t}: `,n),{}}if(r&&this.firestore){let n=this.commonDbUtilsService.getFirestorePath({feature:t,properties:e,documentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()});if(!n)return this.loggingService.warn(`[WB] No firestore path found for ${t}`),{};try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getData]",void 0,void 0,!0),{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,e))).allow)return{};let a=yield this.dbAdapter.read({feature:t,scope:"doc",location:n,store:"firestore",field:e?.field,suppressError:e?.suppressError}).catch(l=>(this.authService.getUser()&&!e?.suppressError&&this.loggingService.catch(`Error in getDoc for ${t}`,l),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:l})));if(a){if(a?.errorCode)return a}else return this.loggingService.warn(`[WB] No document found at ${n}`),{};let o=a.data;return e?.field?o?.[e.field]??{}:o??{}}catch(s){return this.loggingService.catch(`Error fetching Firestore data for ${t}:`,s),{}}}if(this.db){let n=this.commonDbUtilsService.getDocumentPath({feature:t,properties:e,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()});if(!n)return this.loggingService.warn(`[WB] No database path found for ${t}`),{};try{if(!this.authService.getUser())return{};if(!(yield this.authzAdapter.canRead(this.buildAuthzRequest(t,e))).allow)return{};let a=yield this.dbAdapter.read({feature:t,scope:"doc",location:n,store:"rtdb",field:e?.field,suppressError:e?.suppressError}).catch(l=>(this.authService.getUser()&&this.loggingService.catch(`Error in get for ${t}`,l),this.commonDbUtilsService.getErrorForGetRequests({feature:t,error:l})));if(a){if(a?.errorCode)return a}else return this.loggingService.warn(`[WB] No data found at ${n}`),{};let o=a.data;return e?.field?o?.[e.field]??{}:o??{}}catch(s){return this.loggingService.catch(`Error fetching RTDB data for ${t}:`,s),{}}}return this.loggingService.warn("[WB] No database connection available"),{}}catch(r){return this.loggingService.catch("Unexpected error in getData:",r),{}}})}dbListener({feature:t,properties:e}){try{if(Lt(t)&&this.isPortableBackendActive())return this.getPortableChannelObservable(t,e)}catch(n){this.loggingService.catch(`Error in dbListener portable branch for ${t}: `,n)}let i=this.shouldUseFirestore();e?.skipFirestore&&(i=!1);let r=`${t}-${JSON.stringify(e)}`;return fi(this.portableUnservedRead$(t),Ve([this.databaseService.getDb(),this.firestoreService.getFirestore(),this.authService.getUser$().pipe(Ie(n=>!!n))]).pipe(Ie(([n,s])=>n?i&&!s?(this.loggingService.warn(`[WB] Firestore requested but not available for ${t}`),!1):!0:(this.loggingService.warn(`[WB] No database found for ${t}`),!1)),se(([n,s])=>{try{if(i&&s){if(!!!this.observablesCache[r]){this.observablesCache[r]={subject:new P({}),count:0};let l=this.handleFirestoreListener(t,e,s).subscribe(u=>{this.observablesCache[r]?.subject?.next(u)},u=>this.observablesCache[r]?.subject?.error(u));this.firestoreSubscriptions[r]=l}return new Te(o=>{let l=this.observablesCache[r]?.subject?.subscribe(u=>o.next(u),u=>o.error(u),()=>o.complete());return this.observablesCache[r].count+=1,()=>{l?.unsubscribe(),this.observablesCache[r]&&(this.observablesCache[r].count-=1,this.observablesCache[r].count<=0&&(this.firestoreSubscriptions[r]?.unsubscribe(),delete this.firestoreSubscriptions[r],this.observablesCache[r]?.subject?.complete(),delete this.observablesCache[r]))}})}else if(n){if(!!!this.observablesCache[r]){this.observablesCache[r]={subject:new P({}),count:0};let l=this.handleRealtimeDbListener(t,e,n).subscribe(u=>{this.observablesCache[r]?.subject?.next(u)},u=>this.observablesCache[r]?.subject?.error(u));this.rtdbSubscriptions[r]=l}return new Te(o=>{let l=this.observablesCache[r]?.subject?.subscribe(u=>o.next(u),u=>o.error(u),()=>o.complete());return this.observablesCache[r].count+=1,()=>{l?.unsubscribe(),this.observablesCache[r]&&(this.observablesCache[r].count-=1,this.observablesCache[r].count<=0&&(this.rtdbSubscriptions[r]?.unsubscribe(),delete this.rtdbSubscriptions?.[r],this.observablesCache[r]?.subject?.complete(),delete this.observablesCache?.[r]))}})}return $({})}catch(a){return this.loggingService.catch(`Error setting up listener for ${t}:`,a),$({})}}),Ei(()=>{this.loggingService.log(`[WB] Cleaning up listener for ${t} and key ${r}`)})))}handleFirestoreListener(t,e,i){let r=e?.useCollectionGroup?this.commonDbUtilsService.getFirestoreCollectionGroupPath(t):this.commonDbUtilsService.getFirestorePath({feature:t,properties:e,documentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()}),n=`${t}-${JSON.stringify(e)}`;return r?new Te(s=>{let a=e.isCollection?this.setupCollectionListener(i,r,t,s,e):this.setupDocumentListener(i,r,t,s,e);return()=>{s.complete(),s.unsubscribe(),a(),this.observablesCache[n]?.subject?.complete(),this.observablesCache[n]?.subject?.unsubscribe(),delete this.observablesCache[n]}}).pipe(se(s=>this.commonDbUtilsService.mergeUsersWithData$({feature:t,data:s})),se(s=>["allComments","allUserNotifications"].includes(t)?this.commonDbUtilsService.mergeCommentAnnotationsWithData$({data:s,feature:t}):$(s)),se(s=>["allReactions"].includes(t)?this.commonDbUtilsService.mergeReactionAnnotationsWithData$({data:s,feature:t}):$(s)),se(s=>["allRecorders"].includes(t)?this.commonDbUtilsService.mergeRecorderAnnotationsWithData$({data:s,feature:t}):$(s)),q(X)):(this.loggingService.warn(`[WB] No firestore path found for ${t} and key ${n}`),$({}))}setupCollectionListener(t,e,i,r,n){let s=`${i}-${JSON.stringify(n)}`,a=this.dbAdapter.firestoreCollection(t,e);if(n?.useCollectionGroup&&(a=this.dbAdapter.firestoreCollectionGroup(t,e)),n?.useQuery&&n?.firestoreQuery){let u=n?.firestoreQuery??[];a=this.dbAdapter.firestoreQuery(a,...u)}let o=!0,l=[];return i==="allComments"&&this.loggingService.logContext("[CONTEXT] setupCollectionListener called with path:",e,"feature:",i,"properties:",JSON.stringify(n??"nil")),this.dbAdapter.firestoreOnSnapshot(a,u=>{try{let g=JSON.parse(JSON.stringify(this.observablesCache[s]?.subject?.getValue()?.data??{})),f=null,d=!1;u?.docChanges()?.length?u.docChanges().forEach(m=>{["allComments","allReactions","allRecorders"].includes(i)&&!o&&m.type!=="removed"&&l.push(m.doc.id),this.commonDbUtilsService.isDataAlreadyProcessedInLocalCache({feature:i,change:m,cache:this.observablesCache[s]?.subject?.getValue()?.data??{}})||(d=!0,Object.assign(g,this.handleCollectionChange(m,g)),m.type==="removed"&&(f||(f={type:m.type,ids:[]}),f.ids.push(m.doc.id)))}):d=!0,d&&(["allComments","allReactions","allRecorders"].includes(i)&&l?.length&&(this.commonDbUtilsService.resolveAnnotations({data:l,feature:i}),l=[]),this.commonDbUtilsService.modifyAndSetData({feature:i,data:g,subscriber:r,operation:f})),o=!1}catch(g){this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,g),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(n??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(g,i,r)}},u=>{this.loggingService.logContext(`[ERROR] Firestore listener error for feature ${i}:`,u),this.loggingService.logContext(`[ERROR] Firestore listener error for properties ${JSON.stringify(n??"nil")}:`),this.loggingService.logContext(`[ERROR] Firestore listener error for user ${JSON.stringify(this.authService.getUser()??"nil")}:`),this.handleListenerError(u,i,r)})}handleCollectionChange(t,e){switch(t.type){case"added":case"modified":e[t.doc.id]=t.doc.data();break;case"removed":delete e?.[t.doc.id];break}return e}setupDocumentListener(t,e,i,r,n){let s=this.dbAdapter.firestoreDoc(t,e);return this.dbAdapter.firestoreOnSnapshot(s,a=>{try{let o=a.data()||{};n?.field&&(o=o?.[n?.field]??{}),this.commonDbUtilsService.modifyAndSetData({feature:i,data:o,subscriber:r,operation:null})}catch(o){this.handleListenerError(o,i,r)}},a=>this.handleListenerError(a,i,r))}handleListenerError(t,e,i){this.loggingService.catch(`Firestore listener error for ${e}:`,t)}portableUnservedRead$(t){return mi(()=>{try{return this.isPortableBackendActive()?Lt(t)?ct:this.databaseService.getDbValue()||this.firestoreService.getFirestoreValue()?ct:(this.reportPortableUnservedRead(t),$({data:{},operation:null})):new Te(e=>Pt(()=>{e.next(null),e.complete()})).pipe(se(()=>this.portableUnservedRead$(t)))}catch(e){return this.loggingService.catch(`Error in portable unserved-read fallback for ${t}: `,e),ct}})}isPortableUnservedWrite(t){try{return!this.isPortableBackendActive()||this.isPortableChannelFeature(t)?!1:!this.databaseService.getDbValue()&&!this.firestoreService.getFirestoreValue()}catch(e){return this.loggingService.catch("Error in isPortableUnservedWrite: ",e),!1}}dropsWriteWithoutMetadataApiKey(t,e,i){if(!(this.shouldUseFirestore()&&e?.metadata&&!e?.metadata?.apiKey))return!1;let r=it(t,i)?.sendsNoRowBody===!0;if(this.isPortableChannelFeature(t)&&r)return!1;try{let n=`metadata-without-apikey:${t}`;this.isPortableSession()&&!this.reportedPortableWriteDenials.has(n)&&(this.reportedPortableWriteDenials.add(n),this.loggingService.catch(`Velt [portable backend]: a '${t}' write was NOT sent because its metadata has no apiKey (hosted's advanced-queries write rule, which applies on Tier B too). `+(r?"It was issued before the portable transport registered (the window right after identify); once the transport is active this operation carries no row and is never dropped. ":"This usually means the write ran before setDocument() resolved the document. ")+"Further drops for this feature are not logged.",void 0,void 0,!0))}catch{}return!0}reportPortableUnservedWrite(t){try{let e=`unserved-write:${t}`;if(this.reportedPortableWriteDenials.has(e))return;this.reportedPortableWriteDenials.add(e);let i=Gr[t];this.loggingService.catch(i?`Velt [portable backend]: '${t}' writes have no portable surface and were NOT sent. This api is SUPERSEDED on the self-hosted backend \u2014 use ${i} instead. This is an integration fix, not a deployment limitation.`:`Velt [portable backend]: '${t}' writes have no portable surface on this deployment and were NOT sent. This feature is not part of the self-hosted backend's operation catalogue \u2014 the write was dropped rather than silently queued forever. There is no alternative api: this is a deployment capability gap, NOT a misconfigured integration.`,void 0,void 0,!0)}catch{}}reportPortableUnservedRead(t){try{if(this.reportedPortableUnservedReads.has(t))return;this.reportedPortableUnservedReads.add(t),this.loggingService.log(`%c[WB] Portable backend serves no read channel for '${t}' \u2014 emitting an empty result so consumers render an empty state instead of loading forever.`,"color: orange;")}catch(e){this.loggingService.catch("Error in reportPortableUnservedRead: ",e)}}isPortableBackendActive(){try{return this.adapterSelectorService?.isPortableBackendActive()===!0}catch(t){return this.loggingService.catch("Error in isPortableBackendActive: ",t),!1}}isPortableChannelFeature(t){return Qi(t)&&this.isPortableBackendActive()}usesPortableChannelFeed(t){return Lt(t)&&this.isPortableBackendActive()}whenPortableRealtimeReady(){return A(this,null,function*(){try{if(!this.isPortableBackendActive())return;yield this.adapterSelectorService?.resolveRealtimeAdapter()?.whenReady?.()}catch(t){this.loggingService.catch("Error in CommonDbService whenPortableRealtimeReady:",t)}})}reportPortableUnsupportedWrite(t,e){try{this.loggingService.catch(`Portable write '${e}' (${t}) is not supported on the portable backend \u2014 not sent.`,void 0,void 0,!0);let i=`unsupported:${t}`;if(this.reportedPortableWriteDenials.has(i))return;this.reportedPortableWriteDenials.add(i),console.error(`Velt [portable backend]: '${t}' writes are NOT SUPPORTED on the portable backend and were not sent. Document-level notification read markers have no portable surface (the ratified surface is the user-scoped notification feed only), so doc-level "seen" state will read stale. Per-user read state is unaffected and works normally.`)}catch{}}clearReportedDenialsForOp(t){let e=`${t}:`;for(let i of Array.from(this.reportedPortableWriteDenials))i.startsWith(e)&&this.reportedPortableWriteDenials.delete(i)}currentUserId(){try{return this.authService?.getUser()?.userId}catch(t){this.loggingService.catch("Error in CommonDbService currentUserId: ",t);return}}isSamePortableIssuer(t){return this.isPortableBackendActive()&&this.currentUserId()===t}currentUserIdHash(){try{let t=this.authService?.getUser()?.userId;return t?Xe(t):void 0}catch(t){this.loggingService.catch("Error in CommonDbService currentUserIdHash: ",t);return}}buildPortableChannelKey(t,e,i){let r=this.docService.getDocumentPaths(),n=i??e?.userIdHash??e?.userId??e?.id;return Zi(t,{apiKey:e?.apiKey??this.configService.getApiKey(),organizationId:e?.organizationId??r?.organizationId,documentId:e?.documentId??r?.documentId,userIdHash:n!=null?String(n):void 0,instanceId:ti(t)&&e?.id!=null?String(e.id):void 0})}publishPortableChannelState(t,e,i,r,n){return A(this,null,function*(){try{if(!ii(rt(t))){this.loggingService.warn(`[WB] No portable write op mapped for ${t} (verb mismatch or unmapped)`),n?.({ok:!1,code:"unimplemented"});return}let s=this.buildPortableChannelKey(t,i);if(!s){this.loggingService.warn(`[WB] No portable channel key resolvable for ${t}`),n?.({ok:!1,code:"failed-precondition"});return}let a=this.commonDbUtilsService.formatData({feature:t,data:e,properties:i,offset:this.getOffset(),isRealtimeDb:!0}),o=this.currentUserId();if(yield this.whenPortableRealtimeReady(),!this.isSamePortableIssuer(o)){this.discardPortableEphemeralFrame("updatePresence",t),n?.({ok:!1,code:"failed-precondition",message:jr});return}let l=yield this.adapterSelectorService.resolveRealtimeAdapter().presence(s,a);this.reportPortableEphemeralOutcome("updatePresence",t,l),l.ok?r?.():n?.(l)}catch(s){this.loggingService.catch(`Error in publishPortableChannelState for ${t}: `,s),n?.(s)}})}invokePortableDbWriteOp(t,e,i,r,n,s,a){return A(this,null,function*(){try{if(Wr.has(e)){this.reportPortableUnsupportedWrite(e,t.op),s?.({ok:!1,code:"unimplemented",message:`'${e}' is not supported on the portable backend`});return}t.formatData&&i!==void 0&&(i=this.commonDbUtilsService.formatData({feature:e,data:i,properties:r,offset:this.getOffset()}));let o=i;if(t.payloadFields?.length){if(o={},i!==void 0)for(let U of t.payloadFields)i[U]!==void 0&&(o[U]=i[U])}else(t.op==="markNotificationRead"||t.op==="deleteNotification"||t.op==="deleteComment")&&(o=void 0);let l,u,g=t.verb==="delete";if(t.notificationData&&g?l=a?this.preparePortableHubNotification(t.op,e,a):void 0:t.notificationData&&(u=this.resolvePortablePermissionProviderFlag()),t.notificationData&&!g&&a)try{let U=i!==void 0?JSON.parse(JSON.stringify(i)):i,y=Bt(U),R=yield this.commonDbUtilsService.prepareCommentNotificationData({data:U,extraData:a});R&&typeof R=="object"&&(R.deniedForYouUsers=yield Mt(y,R,this.portableCommentNotificationDenialSteps(!!u,R))),l=R}catch(U){this.loggingService.catch(`Error preparing notificationData for portable ${t.op} (${e}) \u2014 op ships without it: `,U)}let f=r?.userIdHash??r?.userId??this.currentUserIdHash(),d=Hr.has(e)?this.buildPortableChannelKey(e,r,f?String(f):void 0):null,m=S(S(S(S({scope:t.scope,resourceId:r?.id!==void 0&&r?.id!==null?String(r.id):void 0},o!==void 0?{data:o}:{}),l!==void 0?{notificationData:l}:{}),u!==void 0?{isPermissionProviderUsed:u}:{}),d?{channel:d}:{}),D=yield this.adapterSelectorService.resolveDbAdapter()[t.op](m);D.ok?(this.clearReportedDenialsForOp(t.op),n?.({firestoreAvailable:!0})):(this.reportPortableWriteDenial(t.op,e,D),s?.(D))}catch(o){this.loggingService.catch(`Error in invokePortableDbWriteOp (${t.op}) for ${e}: `,o),s?.(o)}})}preparePortableHubNotification(t,e,i){try{let r=this.serviceBook?.get(zi);if(!r){this.loggingService.catch(`Velt [portable backend]: the hub notification for '${t}' (${e}) was not attached \u2014 the notification service is not available. The delete is sent without a notification.`,void 0,void 0,!0);return}let n=r.processNotificationData(i);if(!n||typeof n!="object")return;try{Ji(i,n)}catch(s){this.loggingService.catch(`Error applying notification visibility to the hub notification for portable ${t} (${e}): `,s)}return n}catch(r){this.loggingService.catch(`Error preparing the hub notification for portable ${t} (${e}) \u2014 op ships without it: `,r);return}}reportPortableWriteDenial(t,e,i,r=t){try{let n=i?.code??"unknown",s=tt(i),a=`Portable write op '${t}' (${e}) was denied by the backend: ${n}${s}`;this.loggingService.log(a),this.loggingService.catch(a,i,void 0,!0);let o=typeof i?.message=="string"&&hi.has(i.message),l=!o&&n==="failed-precondition"&&i?.reasonCode===xr,u=!o&&!l&&kr(i),g=!o&&!l&&!u&&Br.has(n)&&!s;if(!o&&!l&&!u&&!g&&!wr.has(n))return;let f=o?`${r}:${n}:outcome-unknown`:l?`${r}:${n}:shutting-down`:g?`${r}:${n}:gateway`:`${r}:${n}`;if(this.reportedPortableWriteDenials.has(f))return;this.reportedPortableWriteDenials.add(f);let d=t==="onDisconnect"?"disconnect cleanup":"write",m=i?.message?` (${i.message})`:"";console.error(o?`Velt [portable backend]: the operation '${t}' was sent and never answered${m}: outcome unknown \u2014 the ${d} for '${e}' may or may not have been applied; it is not retried.`:l?`Velt [portable backend]: the operation '${t}' was refused by the gateway while it was shutting down${s}${m}. It did not run: the ${d} for '${e}' was not persisted.`:u?`Velt [portable backend]: the operation '${t}' was NOT SENT${m}. The ${d} for '${e}' was not persisted and is NOT retried. This is a client-side precondition \u2014 usually the realtime connection was not open (handshake or reconnect window), or the channel could not be resolved.`:g?`Velt [portable backend]: the operation '${t}' failed at the gateway with '${n}'${m}. The gateway could not complete it \u2014 its own logs name the cause. The ${d} for '${e}' may not have been persisted and is not retried.`:`Velt [portable backend]: the operation '${t}' was rejected by the configured backend with '${n}'${s}${m}. ${t==="onDisconnect"?`The disconnect cleanup for '${e}' is NOT being registered.`:`Writes for '${e}' are NOT being persisted.`} This usually means the gateway does not expose this operation \u2014 check that the deployed backend implements the full operation catalogue for the features you have enabled.`)}catch{}}discardPortableEphemeralFrame(t,e){try{this.loggingService.log(`[WB] Portable op '${t}' (${e}) discarded: the session that issued it ended during the readiness wait.`)}catch{}}reportPortableEphemeralOutcome(t,e,i){try{let r=`${t}@${e}`;if(i?.ok){this.clearReportedDenialsForOp(r);return}if(i?.code==="failed-precondition"&&!i?.reasonCode&&Ir.has(i?.message)){this.loggingService.log(`Portable op '${t}' (${e}) was not delivered: ${i.code} (${i.message}).`);return}this.reportPortableWriteDenial(t,e,i,r)}catch{}}portableCommentNotificationDenialSteps(t,e){let i=this.commonDbUtilsService.getCommentNotificationDenialSteps();return e?.metadata?.clientDocumentId?i:(t&&this.reportProviderCheckNeedsDocumentId(),{getDeniedForYouUsers:()=>A(this,null,function*(){return[]}),applyNotificationVisibility:r=>i.applyNotificationVisibility(r)})}reportProviderCheckNeedsDocumentId(){try{if(this.reportedProviderCheckNeedsDocumentId)return;this.reportedProviderCheckNeedsDocumentId=!0,this.loggingService.catch("Velt [portable backend]: this comment's notification has no client document id to ask the permission provider about (the document's metadata is not cached \u2014 its folder filing was refused or not served), so the provider check was skipped. Private and restricted comments are still filtered; provider-denied subscribers are notified.",void 0,void 0,!0)}catch{}}resolvePortablePermissionProviderFlag(){try{return!!this.commonDbUtilsService.isPermissionProviderUsed()}catch(t){return this.loggingService.catch("Error resolving isPermissionProviderUsed for the portable addComment: ",t),!1}}invokePortableDbRead(t,e){return A(this,null,function*(){let i=Xt[t];if(!i)return{};let r=e?.id!==void 0&&e?.id!==null?String(e.id):"",n={feature:t,scope:i.scope,location:r,field:e?.field,suppressError:e?.suppressError,resourceId:r||void 0,apiKey:e?.apiKey??this.configService.getApiKey()??void 0,organizationId:e?.organizationId!==void 0&&e?.organizationId!==null?String(e.organizationId):void 0,documentId:e?.documentId!==void 0&&e?.documentId!==null?String(e.documentId):void 0,metadata:e?.userId?{userIdHash:String(e.userId)}:void 0},s=yield this.adapterSelectorService.resolveDbAdapter().read(n);if(s?.errorCode)return{};let a=s?.data;return a==null?{}:e?.field?a?.[e.field]??{}:a})}getPortableChannelObservable(t,e){let i=`portable-${t}-${JSON.stringify(e)}`;if(!this.observablesCache[i]){this.observablesCache[i]={subject:new P({}),count:0};let r={ids:null},n=this.applyDbListenerPostProcessing(t,this.handlePortableChannelListener(t,e,r)).pipe(k(s=>{let a=r.ids;if(!a?.length)return s;let o=s?.data??{},l=a.filter(g=>!(g in o));if(!l.length)return s;let u=a.filter(g=>g in o);return r.ids=u.length?u:null,L(S({},s),{operation:{type:"removed",ids:l}})}));this.firestoreSubscriptions[i]=n.subscribe(s=>{let a=this.observablesCache[i];a&&(a.primed=!0),a?.subject?.next(s)},s=>{this.loggingService.catch(`Portable channel feed error for ${t}: `,s);let a=this.observablesCache[i];a&&(a.primed=!0),a?.subject?.next({data:{},operation:null})})}return new Te(r=>{let n=this.observablesCache[i],s=!0,a=n?.subject?.subscribe(o=>{if(!(s&&!n?.primed)){if(s&&o?.operation){r.next(L(S({},o),{operation:null}));return}r.next(o)}},o=>r.error(o),()=>r.complete());return s=!1,this.observablesCache[i].count+=1,()=>{a?.unsubscribe(),this.observablesCache[i]&&(this.observablesCache[i].count-=1,this.observablesCache[i].count<=0&&(this.firestoreSubscriptions[i]?.unsubscribe(),delete this.firestoreSubscriptions[i],this.observablesCache[i]?.subject?.complete(),delete this.observablesCache[i]))}})}handlePortableChannelListener(t,e,i){return new Te(r=>{try{let n=We[t]?.materialize??"map",s=n==="map"&&e?.documentIds?.length?e.documentIds:void 0,a=(s?s.map(R=>this.buildPortableChannelKey(t,L(S({},e),{documentId:R}))):[this.buildPortableChannelKey(t,e)]).filter(R=>!!R),o=new Set,l=a.filter(R=>{let p=JSON.stringify(R);return o.has(p)?!1:(o.add(p),!0)});if(!l.length)return this.loggingService.warn(`[WB] No portable channel key resolvable for ${t}`),r.next({}),()=>{};let u=this.adapterSelectorService.resolveRealtimeAdapter(),g=_t(rt(t))?.mode??"ephemeral",f=l.map(()=>({})),d=l.map(()=>!1),m=l.map(()=>new Map),O=l.map(()=>{}),D={},U=()=>{r.next(Object.assign({},...f))},y=l.map((R,p)=>u.subscribe(R,g,C=>{try{if(d[p])return;if(n==="doc"){D=C.type==="removed"?{}:C.data??{},r.next(S({},D));return}if(typeof C.seq=="number"){let _=Math.max(m[p].get(C.id)??-1/0,O[p]??-1/0);if(C.seq<=_){this.loggingService.log(`[WB] Portable ${t}: dropped a ${C.type} delta for ${C.id} at seq ${C.seq} (floor ${_}).`);return}m[p].set(C.id,C.seq)}C.type==="removed"?(delete f[p][C.id],i&&g==="persistent"&&(i.ids=[...i.ids??[],C.id])):f[p][C.id]=this.stampDocChannelIdentity(this.commonDbUtilsService.addMetadata(C.data,this.channelScopedProperties(e,R)),R),U()}catch(_){this.loggingService.catch(`Error in portable channel delta for ${t}: `,_)}},{onSnapshotComplete:C=>{try{if(n==="doc"){r.next(S({},D));return}C?.full===!0?(m[p].clear(),O[p]=typeof C.seq=="number"?C.seq:void 0):typeof C?.seq=="number"&&(O[p]=C.seq),U()}catch(_){this.loggingService.catch(`Error in portable snapshot-complete emit for ${t}: `,_)}},onError:C=>{d[p]=!0,D={};for(let _ of Object.keys(f[p]))delete f[p][_];this.loggingService.catch(`Portable channel denied for ${t}: `,{ok:!1,code:C}),U()}}));return()=>y.forEach(R=>R.unsubscribe())}catch(n){return this.loggingService.catch(`Error in handlePortableChannelListener for ${t}: `,n),r.next({}),()=>{}}})}channelScopedProperties(t,e){try{if(e?.scope==="doc"&&e?.documentId!==void 0&&e?.documentId!==null&&(t?.documentId===void 0||t?.documentId===null))return L(S({},t),{documentId:e.documentId})}catch(i){this.loggingService.catch("Error in CommonDbService channelScopedProperties: ",i)}return t}stampDocChannelIdentity(t,e){try{if(e?.scope!=="doc"||e?.documentId===void 0||e?.documentId===null||!t||typeof t!="object"||Array.isArray(t))return t;let i=t.metadata;return!i||typeof i!="object"||Array.isArray(i)?t:i.documentId!==void 0&&i.documentId!==null&&i.documentId!==""?(this.reportDocChannelIdentityMismatch(i,e),t):L(S({},t),{metadata:S(L(S({},i),{documentId:e.documentId}),i.organizationId===void 0&&e.organizationId!==void 0?{organizationId:e.organizationId}:{})})}catch(i){return this.loggingService.catch("Error in CommonDbService stampDocChannelIdentity: ",i),t}}reportDocChannelIdentityMismatch(t,e){try{let i=String(t?.documentId)!==String(e?.documentId),r=t?.organizationId!==void 0&&e?.organizationId!==void 0&&String(t.organizationId)!==String(e.organizationId);if(!i&&!r)return;this.loggingService.log(`[WB] Portable doc-channel identity mismatch: row body claims document '${t?.documentId}'${r?` / organization '${t?.organizationId}'`:""} but arrived on the channel for document '${e?.documentId}'${r?` / organization '${e?.organizationId}'`:""}.`);let n=`${e?.documentId}>${t?.documentId}:${e?.organizationId}>${t?.organizationId}`;if(this.reportedDocChannelIdentityMismatches.has(n))return;this.reportedDocChannelIdentityMismatches.add(n),console.error(`Velt [portable backend]: a row delivered on the channel for document '${e?.documentId}' carries metadata naming document '${t?.documentId}'${r?` and organization '${t?.organizationId}' (channel organization is '${e?.organizationId}')`:""}. The row body is used as-is, so this row is being filed under the document/organization it names, NOT the channel it arrived on. If that is not intended, the gateway is routing rows to the wrong channel.`)}catch{}}handleRealtimeDbListener(t,e,i){let r=this.commonDbUtilsService.getDocumentPath({feature:t,properties:e,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey()});if(!r)return this.loggingService.warn(`[WB] No database path found for ${t}`),$({});let n=this.realtimeAdapter.rtdbRef(i,r);if(e?.useQuery&&e?.rtdbQuery){let s=e?.rtdbQuery??[];n=this.realtimeAdapter.rtdbQueryRef(n,...s)}return this.objectValFromChildEvents(n,t).pipe(lt(s=>(this.loggingService.catch(`RTDB listener error for ${t}:`,s),$({}))),k(s=>(s===null&&(s={}),s&&typeof s=="object"?Object.entries(s??{}).reduce((o,[l,u])=>(o[l]=this.commonDbUtilsService.addMetadata(u,e),o),{}):this.commonDbUtilsService.addMetadata(s,e))),s=>this.applyDbListenerPostProcessing(t,s))}applyDbListenerPostProcessing(t,e){return e.pipe(se(i=>this.commonDbUtilsService.modifyData({feature:t,data:i})),se(i=>this.usersService.getUserById$().pipe(k(()=>({data:this.commonDbUtilsService.mergeUsersWithData({feature:t,data:i}),operation:null})))))}pushData(r){return A(this,arguments,function*({feature:t,properties:e,data:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: pushData for ${t}`,"color: green;"),this.performDatabaseOperation(t,e,n=>A(this,null,function*(){if(n.dbRef){let s=this.realtimeAdapter.rtdbPush(t,n.dbRef);yield this.realtimeAdapter.rtdbSet(t,s,JSON.parse(JSON.stringify(n.data)))}}),i)}catch(n){this.loggingService.catch(`Error in pushData for ${t}`,n)}})}streamChildAdded({feature:t,properties:e,afterTs:i}){try{return this.loggingService.log(`%c[WB] Calling FUNCTION: streamChildAdded for ${t}`,"color: green;"),new Te(r=>{let n=null,s=!1,a=({db:o})=>{if(!o||s||!this.authService.getUser())return;let l=this.commonDbUtilsService.getDocumentPath({feature:t,properties:e,defaultDocumentPaths:this.docService.getDocumentPaths(),apiKey:e.apiKey??this.configService.getApiKey(),useFirestore:!1});if(!l)return;let g=this.realtimeAdapter.rtdbRef(o,l),f=!1,d=D=>{try{let U=D.val();if(f){if(i!=null&&U?.timestamp!=null&&U.timestamp<=i)return;r.next(U)}}catch(U){this.loggingService.catch(`streamChildAdded onChildAdded callback error for ${t}:`,U)}},m=D=>{try{this.loggingService.catch(`streamChildAdded error for ${t}:`,D),r.error(D)}catch(U){this.loggingService.catch(`streamChildAdded onError handler error for ${t}:`,U)}};this.realtimeAdapter.rtdbOnChildAdded(t,g,d,m);let O=this.realtimeAdapter.rtdbOnValue(t,g,()=>{f=!0},m,{onlyOnce:!0});n=()=>{try{O&&typeof O=="function"&&O(),this.realtimeAdapter.rtdbOff(g,"child_added",d)}catch(D){this.loggingService.catch(`streamChildAdded cleanup error for ${t}:`,D)}}};return this.subscribeToServices(a),()=>{s=!0,n&&n()}})}catch(r){return this.loggingService.catch(`Error in streamChildAdded for ${t}`,r),$(null)}}objectValFromChildEvents(t,e){return new Te(i=>{let r={},n=!1,s=null,a=m=>{try{this.loggingService.catch(`Realtime DB listener error for ${e}:`,m),i.error(m)}catch{}},o=m=>{try{if(!he(m,s)){let O=JSON.parse(JSON.stringify(m));s=O,i.next(O)}}catch{}},l=m=>{try{m.key&&(r[m.key]=m.val(),n&&o(S({},r)))}catch{}},u=m=>{try{m.key&&(r[m.key]=m.val(),n&&o(S({},r)))}catch{}},g=m=>{try{m.key&&(delete r[m.key],n&&o(S({},r)))}catch{}},f=m=>{try{if(!n){let O=r&&typeof r=="object"?JSON.parse(JSON.stringify(r)):{};s=O,i.next(O),n=!0}}catch{}};this.realtimeAdapter.rtdbOnChildAdded(e,t,l,a),this.realtimeAdapter.rtdbOnChildChanged(e,t,u,a),this.realtimeAdapter.rtdbOnChildRemoved(e,t,g,a);let d=this.realtimeAdapter.rtdbOnValue(e,t,f,a,{onlyOnce:!0});return()=>{try{d&&typeof d=="function"&&d(),this.realtimeAdapter.rtdbOff(t,"child_added",l),this.realtimeAdapter.rtdbOff(t,"child_changed",u),this.realtimeAdapter.rtdbOff(t,"child_removed",g)}catch{}}})}};c.\u0275fac=function(e){return new(e||c)(T(Wt),T(Ae),T(ur),T(H),T(B),T(xi),T(Nt),T(_e),T(qe),T(K),T(me),T(Re),T(Pe),T(Gt),T(Ne),T(Hi),T(Wi),T(gr),T($t))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();function Ar(I){let c=I;return c?.ok===!1&&c?.code==="permission-denied"&&c?.reasonCode==="folder_mismatch"}var qr=new Set(["portable session not established","portable apiEndpoint is not a secure URL; request not sent","portable request body could not be serialized; request not sent","portable request failed before it was sent"]),qe=(()=>{let c=class c{constructor(t,e,i,r,n,s,a,o,l,u,g,f){this.analyticsService=t,this.authService=e,this.databaseService=i,this.domService=r,this.configService=n,this.loggingService=s,this.commentResolverService=a,this.reactionResolverService=o,this.recorderResolverService=l,this.coreActionsService=u,this.functions=g,this.serviceBook=f,this.endpointsService=Le(xe),this.adapterSelectorService=Le($t),this.documentPaths$=new P(null),this.docContext$=new P(null),this.documentIds$=new P([]),this.organizationConfig$=new P(null),this.firestorePaths$=new P(null),this.location$=new P(null),this.excludedLocationIds$=new P([]),this.organizationMetadata$=new P(null),this.documentMetadata$=new P(null),this.locationMetadata$=new P(null),this.customerMetadata$=new P(null),this.currentDocumentId=null,this.isCustomDocId=!1,this.locations$=new P({}),this.preDocumentIdChangeFunctions=new Map,this.draftDocuments=[],this.clientDocumentMetadataMap={},this.uiState=new P({}),this.lastSetDocumentIdExecutionTime=0,this.lastSetDocumentIdCallTime=0,this.setDocumentIdSubject=new gi,this.DEBOUNCE_TIME=5e3,this.currentDebounceTime=this.DEBOUNCE_TIME,this.MAX_QUEUE_SIZE=100,this.queueSize=0,this.isDocumentIdInDebounceQueue=!1,this.currentValidationToken=null,this.pendingDocumentIds=[],this.pendingOptions={},this.draftLocationMap={locations:[],options:void 0},this.reportedOrgProfileDenials=new Set,this.reportedPortableDocumentOpFailures=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: DocService","color: blue;"),this.domService.setDocService(this),this.authService.setDocService(this),this.serviceBook.observe(ki).subscribe(d=>{this.commentService=d??void 0}),Ri(()=>this.documentPaths$.value?.clientDocumentId),this.setDocumentIdSubject.pipe(Si(()=>vi(this.currentDebounceTime))).subscribe({next:d=>A(this,null,function*(){try{yield this.setDocumentIdImpl(d.documentId,d.clientOrganizationId,d.options),this.lastSetDocumentIdExecutionTime=Date.now(),this.isDocumentIdInDebounceQueue=!1,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"})),this.draftLocationMap={locations:[],options:void 0}}finally{this.queueSize--}}),error:d=>{this.loggingService.catch("Error in setDocumentId subscription:",d),this.queueSize--}}),this.databaseService.getDb().pipe(Ie(d=>!!d),$e(1)).subscribe(d=>{d&&(this.db=d)}),this.configService.getApiKey$().subscribe(d=>{if(this.apiKey=d,this.apiKey){if(!this.isCustomDocId){let m=Et(window.location.href);this.currentUrl=m}this.analyticsService.updateDefaultProperties({apiKey:d})}}),this.authService.getUser$().subscribe(d=>A(this,null,function*(){if(d&&(this.analyticsService.updateDefaultProperties({organizationId:d?.organizationId,clientOrganizationId:d?.clientOrganizationId}),this.draftDocuments?.length?(yield this.setDocuments({documents:this.draftDocuments,options:this.draftOptions??void 0,source:"internal"}),this.draftDocuments=[],this.draftOptions=void 0,this.draftLocationMap.locations.length&&(yield this.setLocations({locations:this.draftLocationMap.locations,options:this.draftLocationMap.options,source:"internal"}).then(()=>this.draftLocationMap={locations:[],options:void 0}))):this.documentPaths$?.value&&d?.organizationId&&this.documentPaths$.value?.organizationId!==d?.organizationId&&(yield this.setDocuments({documents:this.documentIds$.value.length?this.documentIds$.value.map(m=>({id:m.clientDocumentId})):[{id:this.documentPaths$.value?.clientDocumentId}],options:void 0,source:"internal"})),setTimeout(()=>{this.documentPaths$.value||this.loggingService.catch("Error in DocService constructor:","Please set document id to continue.")},1e4),d?.organizationId&&d?.clientOrganizationId)){let m={organizationId:d?.organizationId,clientOrganizationId:d?.clientOrganizationId};this.getOrganizationConfig()||this.setOrganizationConfig({organizationId:d?.organizationId,clientOrganizationId:d?.clientOrganizationId}),yield this.updateOrganizationMetadata(m)}})),this.documentPaths$.subscribe(d=>{let m={documentId:d?.documentId,clientDocumentId:d?.clientDocumentId,folderId:d?.folderId,allDocuments:d?.allDocuments,veltFolderId:d?.veltFolderId};d?.organizationId&&(m.organizationId=d.organizationId,m.clientOrganizationId=d.clientOrganizationId),this.analyticsService.updateDefaultProperties(m),this.domService.resetSelectedAnnotationsMap()}),this.location$.subscribe(d=>{this.analyticsService.updateDefaultProperties({clientLocation:d?.location,locationId:d?.locationId})}),this.organizationMetadata$.subscribe(d=>{this.authService.setUserOrganization(d?.[this.documentPaths$.value?.organizationId])}),this.documentPaths$.pipe(Ie(d=>!!d),$e(1)).subscribe(()=>{try{this.subscribeToCustomerMetadata()}catch(d){this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",d)}},d=>{this.loggingService.catch("Error in DocService subscribeToCustomerMetadata:",d)}),this.loggingService.log("%c[WB] Creating CLASS: DocService 2","color: blue;"),this.onWindowPopstate(),this.onWindowClick()}catch(d){this.loggingService.catch("Error in DocService constructor:",d)}}getOptionsFromDocumentPaths(){try{return this.documentPaths$.value?{organizationId:this.documentPaths$.value?.clientOrganizationId,folderId:this.documentPaths$.value?.folderId,allDocuments:this.documentPaths$.value?.allDocuments,locationId:this.documentPaths$.value?.locationId,optimisticPermissions:this.documentPaths$.value?.optimisticPermissions}:null}catch(t){return this.loggingService.catch("Error in getOptionsFromDocumentPaths:",t),null}}clearCacheOnUserCascade(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCacheOnUserCascade in DocService","color: green;");try{this.setOrganizationConfig(null),this.organizationMetadata$.next(null),this.customerMetadata$.next(null),this.customerMetadataSubscription?.unsubscribe(),this.documentPaths$.value&&(this.draftOptions=this.getOptionsFromDocumentPaths(),this.draftDocuments=this.documentIds$.value.map(t=>({id:t.clientDocumentId})),this.draftLocationMap={locations:[this.location$.value?.location??null,...Object.values(this.locations$.value||{}).map(t=>t.location)].filter(t=>t!==null),options:{rootLocationId:this.location$.value?.location?.id}},this.currentDocumentId=null,this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.unsetDocuments({source:"internal"})}catch(t){this.loggingService.catch("Error in DocService clearCacheOnUserCascade: ",t)}}setUsersService(t){try{this.usersService=t}catch(e){this.loggingService.catch("Error in setUsersService:",e)}}setCommonDbService(t){try{this.commonDbService=t}catch(e){this.loggingService.catch("Error in setCommonDbService:",e)}}setUserPermissionService(t){try{this.userPermissionService=t}catch(e){this.loggingService.catch("Error in setUserPermissionService:",e)}}setCommentService(t){try{this.commentService=t}catch(e){this.loggingService.catch("Error in setCommentService:",e)}}onWindowPopstate(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowPopstate","color: green;");try{this.domService.onWindowPopState$().subscribe(()=>{this.loggingService.log("location",location.href);let t=Et(location.href);this.currentUrl!==t&&(this.currentUrl=t,!this.isCustomDocId&&this.apiKey&&this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowPopstate subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowPopstate: ",t)}}onWindowClick(){this.loggingService.log("%c[WB] Calling FUNCTION: onWindowClick","color: green;");try{this.domService.onWindowClick$().subscribe(()=>{let t=Et(location.href);this.currentUrl!==t&&(this.currentUrl=t,this.isCustomDocId||this.loggingService.log("current url in doc service",this.currentUrl))},t=>{this.loggingService.catch("Error in DocService onWindowClick subscription: ",t)})}catch(t){this.loggingService.catch("Error in onWindowClick: ",t)}}setDocument(n){return A(this,arguments,function*({documentId:t,documentMetadata:e,options:i,source:r="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocument","color: green;"),r==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,documentMetadata:e,methodName:"setDocument",source:r}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:ne.SET_DOCUMENTS,source:r,payload:{documentId:t,documentMetadata:e,options:i}}),yield this.setDocumentsImpl({documents:[{id:t,metadata:e}],options:S({organizationId:e?.organizationId},i??{}),source:r})}catch(s){this.loggingService.catch("Error in DocService setDocument:",s)}})}getEffectiveCompareOptions(t={}){let e=this.authService.getUser(),i=S({},t);return i.organizationId==null&&e?.organizationId&&e?.clientOrganizationId&&(i.organizationId=e.clientOrganizationId),It(i)??{}}shouldSetDocumentsAgain(t,e={}){try{this.loggingService.log("%c[WB] Calling FUNCTION: shouldSetDocumentsAgain","color: green;");let i=this.getEffectiveCompareOptions(e),r=t.some(u=>u?.metadata&&typeof u.metadata=="object"&&!he(this.clientDocumentMetadataMap[u.id],u.metadata));if(this.pendingDocumentIds.length>0&&!r&&t.length===this.pendingDocumentIds.length&&t.every(g=>this.pendingDocumentIds.includes(g.id))&&he(i,this.pendingOptions))return!1;let n=this.documentPaths$.value?.clientDocumentId,s=e?.rootDocumentId??t[0]?.id,a=this.documentIds$.value.map(u=>u.clientDocumentId),o=It(this.getOptionsFromDocumentPaths()??{})??{};return!((e?.allDocuments===!0||t.length===a.length)&&t.every(u=>a.includes(u.id)))||r||!he(o,i)||n!==s}catch(i){return this.loggingService.catch("Error in DocService shouldSetDocumentsAgain:",i),!0}}getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:e=!1}){try{let i=[];return t.forEach(r=>{let n=r.id,s=`${we(n)}`;e&&r?.metadata&&typeof r.metadata=="object"&&(this.clientDocumentMetadataMap[n]=r.metadata),i.push({documentId:s,clientDocumentId:n})}),i}catch(i){return this.loggingService.catch("Error in DocService getDocumentIdsFromDocuments:",i),[]}}setDocuments(n){return A(this,arguments,function*({documents:t,options:e,source:i="internal",skipPermissionValidation:r=!1}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocuments","color: green;"),i==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{documents:t,options:e,methodName:"setDocuments",source:i}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:ne.SET_DOCUMENTS,source:i,payload:{documents:t,options:e}}),yield this.setDocumentsImpl({documents:t,options:e??{},source:i,skipPermissionValidation:r})}catch(s){this.loggingService.catch("Error in DocService setDocuments:",s)}})}setRootDocument(i){return A(this,arguments,function*({document:t,source:e="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootDocument","color: green;"),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_ROOT_DOCUMENT_TRIGGERED,methodName:ne.SET_ROOT_DOCUMENT,source:e,payload:{document:t}});let r=this.getOptionsFromDocumentPaths()??{},n=this.documentIds$.value.map(s=>s.clientDocumentId);if(!n.includes(t.id)){let s=[...n.map(o=>({id:o})),{id:t.id}],a=this.getDocumentIdsFromDocuments({documents:s,setClientDocumentMetadataMap:!0});this.documentIds$.next(a)}yield this.setDocumentIdImpl(t.id,this.documentPaths$.value?.clientOrganizationId,r)}catch(r){this.loggingService.catch("Error in DocService setRootDocument:",r)}})}setDocContext(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocContext","color: green;");let e=JSON.parse(JSON.stringify(t??null));this.docContext$.next(e)}catch(e){this.loggingService.catch("Error in setDocContext: ",e)}}getDocContext(){return this.docContext$.getValue()}getDocContext$(){return this.docContext$.asObservable().pipe(q(X))}getProcessedDocContext(){return Ni(this.getDocContext())}filterRelevantDocuments(r){return A(this,arguments,function*({options:t,documentIds:e,skipPermissionValidation:i=!1}){try{let n=this.authService.getUser();return!n||!this.commonDbService?.shouldUseFirestore()||(e=yield this.fetchDocumentsFromFolder(t,e,n),yield this.handlePermissionProvider(t,e,n),e=yield this.filterDocumentsByPermissions(t,e,n,i),e=e.slice(0,50)),e}catch(n){return this.loggingService.catch("Error in DocService filterRelevantDocuments:",n),e}})}fetchDocumentsFromFolder(t,e,i){return A(this,null,function*(){if(!t?.folderId||!t?.allDocuments)return e;try{let r={organizationId:t?.organizationId??i?.clientOrganizationId,folderId:t?.folderId},n;if(this.isPortableDocumentOpCandidate()&&(yield this.resolvePortableDocumentOps())){if(!this.isSamePortableSession(i))return e;let s=yield this.callPortableDocumentOp("getDocuments","org",{metadata:r});if(!s?.ok)return this.reportPortableDocumentOpFailure("getDocuments",s),e;n=s.data?.veltData}else{let s=Ue(this.functions,be({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));n=yield At({methodName:"getDocuments",data:{type:"getDocuments",metadata:r},getSdkProxy:s,userId:i?.userId??""})}n?.data?.forEach(s=>{e.find(a=>a.clientDocumentId===s.id)||e.push({documentId:Ce(s.id),clientDocumentId:s.id})})}catch(r){this.loggingService.warn("Error in DocService fetchDocumentsFromFolder:",r)}return e})}buildPermissionRequests(t,e,i){try{let r=[];return t.organizationId&&t.organizationId!==i.clientOrganizationId&&r.push({userId:i.userId,resource:{id:t.organizationId,type:De.ORGANIZATION,source:de.SET_DOCUMENTS,organizationId:t.organizationId,context:t?.context}}),t.folderId&&r.push({userId:i.userId,resource:{id:t.folderId,type:De.FOLDER,source:de.SET_DOCUMENTS,organizationId:t?.organizationId??i?.clientOrganizationId??"",context:t?.context}}),e&&e.forEach(n=>{r.push({userId:i.userId,resource:S({id:n.clientDocumentId,type:De.DOCUMENT,source:de.SET_DOCUMENTS,organizationId:t?.organizationId??i?.clientOrganizationId??"",context:t?.context},t?.folderId&&{parentFolderId:t.folderId})})}),t?.context&&this.userPermissionService?.getIsContextEnabled()&&_i({input:t?.context}).forEach(s=>{let a=JSON.stringify(s.access);r.push({userId:i.userId,resource:{id:a,type:De.CONTEXT,source:de.SET_DOCUMENTS,organizationId:t?.organizationId??i?.clientOrganizationId??"",context:s}})}),r}catch(r){return this.loggingService.catch("Error in buildPermissionRequests:",r),[]}}processAccessibleContexts(t,e){try{if(!t?.success||!t?.data?.length||!this.userPermissionService?.getIsContextEnabled())return;let i=t.data.filter(r=>r.type===De.CONTEXT&&r.hasAccess).map(r=>r.resourceId);if(this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContextIds:",JSON.parse(JSON.stringify(i??"nil"))),i?.length){let r=e.filter(s=>i.includes(s.resource.id)).map(s=>s.resource.context).filter(s=>!!s),n=Pi({input:r});this.loggingService.logContext("[CONTEXT] processAccessibleContexts called with accessibleContext:",JSON.parse(JSON.stringify(n??"nil"))),n?.access&&(this.loggingService.logContext("[CONTEXT] setting accessibleContext in docContext:",JSON.parse(JSON.stringify(n??"nil"))),this.setDocContext(n))}}catch(i){this.loggingService.catch("Error in processAccessibleContexts:",i)}}handlePermissionProvider(t,e,i){return A(this,null,function*(){if(this.userPermissionService?.isPermissionProviderAvailable())try{this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(e??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil")));let r=this.buildPermissionRequests(t,e,i),n=b();this.coreActionsService.triggerAction(E.PERMISSION_PROVIDER,{event:v.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,methodName:de.SET_DOCUMENTS,uniqueId:n,timestamp:new Date().getTime(),source:"internal",payload:{requests:r}}),this.userPermissionService?.cancelPendingRevokes(r);let s=yield this.userPermissionService?.onResourceAccessRequired({requests:r,uniqueId:n,methodName:de.SET_DOCUMENTS,fromCache:!1});this.loggingService.logContext("[CONTEXT] handlePermissionProvider called with res:",JSON.parse(JSON.stringify(s??"nil")),"requests:",JSON.parse(JSON.stringify(r??"nil"))),this.processAccessibleContexts(s,r)}catch(r){this.loggingService.catch("Error in handlePermissionProvider:",r)}})}filterDocumentsByPermissions(t,e,i,r=!1){return A(this,null,function*(){if(r)return e;if(this.loggingService.logContext("[CONTEXT] filterDocumentsByPermissions called with options:",JSON.parse(JSON.stringify(t??"nil")),"documentIds:",JSON.parse(JSON.stringify(e??"nil")),"user:",JSON.parse(JSON.stringify(i??"nil"))),!(t?.optimisticPermissions!==!1))return yield this.validateAndFilterPermissions(t,e,i);let s=this.currentValidationToken,a=[...e];return s&&this.validatePermissionsInBackground(t,e,i,s),a})}validateAndFilterPermissions(t,e,i){return A(this,null,function*(){try{let r=t?.organizationId??i?.clientOrganizationId,n=yield this.userPermissionService?.getUserPermissions({organizationId:r,documentIds:e.map(o=>o.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]});if(!n)return e;this.userPermissionService?.setCurrentUserPermissions(n),r&&n?.[i.userId]?.organization?.[r]?.errorCode===Oe.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${r}`,void 0,void 0,!0),t?.folderId&&n?.[i.userId]?.folders?.[t?.folderId]?.errorCode===Oe.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0);let s=new Set;Object.entries(n?.[i.userId]?.documents??{}).forEach(([o,l])=>{l?.errorCode===Oe.PERMISSION_DENIED&&s.add(o)}),s.size>0&&(this.loggingService.catch(`User does not have access to documents: ${[...s].join(", ")}`,void 0,void 0,!0),this.coreActionsService.triggerAction(E.ERROR,{event:v.Events.Core.SDK_ERROR,sourceMethod:"validateAndFilterPermissions",message:"Access denied to documents in strict validation mode",documentIds:[...s],userId:i.userId,timestamp:new Date().getTime()}));let a=e.filter(o=>!s.has(o.clientDocumentId));return a.length===0&&e.length>0&&this.loggingService.catch("Error in validateAndFilterPermissions: All documents provided are denied"),a}catch(r){return this.loggingService.catch("Error in validateAndFilterPermissions:",r),e}})}validatePermissionsInBackground(t,e,i,r){let n=t?.organizationId??i?.clientOrganizationId;this.userPermissionService?.getUserPermissions({organizationId:n,documentIds:e.map(s=>s.clientDocumentId),folderIds:t?.folderId?[t?.folderId]:[]}).then(s=>{if(this.currentValidationToken===r&&s){this.userPermissionService?.setCurrentUserPermissions(s);let a=[];Object.entries(s?.[i.userId]?.documents??{}).forEach(([o,l])=>{l?.errorCode===Oe.PERMISSION_DENIED&&a.push(o)}),n&&s?.[i.userId]?.organization?.[n]?.errorCode===Oe.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to organization: ${n}`,void 0,void 0,!0),t?.folderId&&s?.[i.userId]?.folders?.[t?.folderId]?.errorCode===Oe.PERMISSION_DENIED&&this.loggingService.catch(`User does not have access to folder: ${t?.folderId}`,void 0,void 0,!0),a.length>0&&(this.loggingService.catch(`User does not have access to documents: ${a.join(", ")}`,void 0,void 0,!0),this.handleDeniedDocumentAccess(a,i,r))}}).catch(s=>{this.loggingService.catch("Error in background permission validation:",s)})}handleDeniedDocumentAccess(t,e,i){try{if(this.currentValidationToken!==i)return;let r=this.documentPaths$.value;this.coreActionsService.triggerAction(E.ERROR,{event:v.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"Access denied to document after optimistic load",documentIds:t,userId:e.userId,timestamp:new Date().getTime()});let n=this.documentIds$.value||[],s=n.filter(a=>!t.includes(a.clientDocumentId));s.length!==n.length&&(s.length>0?this.setDocuments({documents:s.map(a=>({id:a.clientDocumentId})),options:{organizationId:r?.clientOrganizationId},source:"internal",skipPermissionValidation:!0}):(this.loggingService.catch("Error in DocService handleDeniedDocumentAccess: Documents provided are all denied"),this.coreActionsService.triggerAction(E.ERROR,{event:v.Events.Core.SDK_ERROR,sourceMethod:"handleDeniedDocumentAccess",message:"All documents provided are denied",documentIds:t,userId:e.userId,timestamp:new Date().getTime()}),this.unsetDocuments({source:"internal"})))}catch(r){this.loggingService.catch("Error in handleDeniedDocumentAccess:",r)}}reportPortableOrgProfileDenial(t){try{let e=t?.code??"unknown",i=tt(t);if(this.loggingService.catch(`Tier B addUserInfoToOrganization denied/failed at the gateway: ${e}${i}`,t,void 0,!0),this.reportedOrgProfileDenials.has(e))return;this.reportedOrgProfileDenials.add(e);let r=`${i}${t?.message?` (${t.message})`:""}`;if(e==="not-found"){console.warn(`Velt [portable backend]: the organization-profile write (addUserInfoToOrganization) was answered 'not-found'${r}, which means the configured backend has no record of this organization. User profile / membership data is NOT being persisted for it, so contacts and mentions will be empty; everything else is unaffected and the call fails soft (hosted parity). Organizations are provisioned out of band on a self-hosted deployment \u2014 identify will issue a token for an organizationId that was never provisioned, so this is expected until yours is.`);return}console.error(`Velt [portable backend]: the organization-profile write (addUserInfoToOrganization) was rejected by the configured backend with '${e}'${r}. User profile / membership data is NOT being persisted for this organization. The call fails soft (hosted parity) \u2014 check that your gateway serves addUserInfoToOrganization and that the caller is permitted to write this user.`)}catch{}}addUserInfoToOrganization(n){return A(this,arguments,function*({organizationId:t,user:e,notificationsConfig:i,currentUserId:r}){try{if(this.adapterSelectorService?.isPortableBackendActive()){let a=yield this.adapterSelectorService.resolveDbAdapter().upsertOrgUserProfile({scope:"org",data:S({organizationId:t,user:this.usersService?.userResolverConfigured?.()?{userId:e?.userId}:e},i&&{notificationsConfig:i})});a?.ok||this.reportPortableOrgProfileDenial(a);return}let s=Ue(this.functions,be({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield At({data:S({type:"addUserInfoToOrganization",metadata:{organizationId:t},user:this.usersService?.userResolverConfigured?.()?{userId:e?.userId}:e},i&&{notificationsConfig:i}),getSdkProxy:s,userId:r??e?.userId??""})}catch(s){this.loggingService.warn("Error in DocService addUserInfoToOrganization:",s)}})}setDocumentsImpl(n){return A(this,arguments,function*({documents:t,options:e,source:i,skipPermissionValidation:r=!1}){try{if(this.loggingService.logContext("[CONTEXT] setDocumentsImpl called with documents:",JSON.parse(JSON.stringify(t??"nil")),"options:",JSON.parse(JSON.stringify(e??"nil"))),!this.shouldSetDocumentsAgain(t,It(e))){i==="external"&&this.loggingService.catch("setDocuments called with previous request");return}let s=b();this.currentValidationToken=s;let a=this.getDocumentIdsFromDocuments({documents:t,setClientDocumentMetadataMap:!0});if(a?.length===0){this.loggingService.warn("Minimum one document must be set in setDocuments");return}let o=this.authService.getUser();if(!o){this.draftDocuments=t,this.draftOptions=e;return}this.pendingDocumentIds=t.map(u=>u.id),this.pendingOptions=this.getEffectiveCompareOptions(e),this.documentPaths$.value?.organizationId&&e?.organizationId&&this.documentPaths$.value?.clientOrganizationId!==e?.organizationId?this.authService.resetServicesCache():this.unsetDocuments({source:"internal",unsetDocumentPaths:!1});let l=e?.organizationId??o?.clientOrganizationId;if(l&&this.addUserInfoToOrganization({organizationId:l,user:o}),a=yield this.filterRelevantDocuments({options:e,documentIds:a,skipPermissionValidation:r}),this.documentIds$.next(a),a?.length){let u=a[0]?.clientDocumentId;e?.rootDocumentId&&a.find(g=>g.clientDocumentId===e?.rootDocumentId)&&(u=e?.rootDocumentId),yield this.debounceSetDocuments({documentId:u,clientOrganizationId:e?.organizationId,options:e})}this.pendingDocumentIds=[],this.pendingOptions={};return}catch(s){this.pendingDocumentIds=[],this.pendingOptions={},this.loggingService.catch("Error in DocService setDocumentsImpl:",s)}})}setDocumentId(r){return A(this,arguments,function*({documentId:t,clientOrganizationId:e,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentId","color: green;"),i==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_DOCUMENTS_TRIGGERED,{payload:{id:t,clientOrganizationId:e,methodName:"setDocumentId",source:i}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_DOCUMENTS_TRIGGERED,methodName:ne.SET_DOCUMENT_ID,source:i,payload:{documentId:t,clientOrganizationId:e}}),yield this.setDocumentsImpl({documents:[{id:t}],options:{organizationId:e},source:i})}catch(n){this.loggingService.catch("Error in setDocumentId:",n);return}})}debounceSetDocuments(r){return A(this,arguments,function*({documentId:t,clientOrganizationId:e,options:i}){try{this.loggingService.log("%c[WB] Calling FUNCTION: debounceSetDocuments","color: green;");let n=i?.debounceTime??this.DEBOUNCE_TIME;this.currentDebounceTime=n;let s=Date.now(),a=s-this.lastSetDocumentIdCallTime,o=s-this.lastSetDocumentIdExecutionTime;if(this.lastSetDocumentIdCallTime=s,this.queueSize>=this.MAX_QUEUE_SIZE){this.loggingService.warn("SetDocumentId queue size exceeded limit");return}if(!this.documentPaths$.value&&!this.isDocumentIdInDebounceQueue||a>n&&o>n){yield this.setDocumentIdImpl(t,e,i),this.lastSetDocumentIdExecutionTime=s;return}this.documentPaths$.next(null),this.isDocumentIdInDebounceQueue=!0,this.draftLocationMap={locations:[],options:void 0},this.queueSize++,this.setDocumentIdSubject.next({documentId:t,clientOrganizationId:e,options:i??void 0});return}catch(n){this.loggingService.catch("Error in debounceSetDocuments:",n)}})}setDocumentIdImpl(t,e,i){return A(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentIdImpl","color: green;");try{let r=this.authService.getUser();if(!r)return;this.currentDocumentId&&this.documentPaths$.value&&(yield this.callPreDocumentIdChangeFunctions(this.documentPaths$.value));let n=this.currentDocumentId;if(this.apiKey){let s=`${we(t)}`,a=i?.folderId,o=i?.folderId?Ee(i?.folderId):void 0,l=i?.locationId,u=i?.allDocuments,g=i?.optimisticPermissions,f=r?.organizationId?e?Xe(e):r?.organizationId:void 0,d=b(),m=Qe.SET_DOCUMENTS;this.coreActionsService.triggerAction(E.COMMENT_RESOLVER,{event:v.Events.Resolver.COMMENT_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:j.INIT_DOCUMENTS,moduleName:m,source:"internal",payload:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""}});let O=b(),D=Ye.SET_DOCUMENTS;this.coreActionsService.triggerAction(E.REACTION_RESOLVER,{event:v.Events.Resolver.REACTION_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:O,moduleName:D,methodName:x.INIT_DOCUMENTS,source:"internal",payload:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""}});let U=b(),y=Ze.GET_RECORDER_ANNOTATIONS;if(this.coreActionsService.triggerAction(E.RECORDER_RESOLVER,{event:v.Events.Resolver.RECORDER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:U,moduleName:y,methodName:W.RESOLVE_RECORDER_ANNOTATIONS,source:"internal",payload:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""}}),yield Promise.allSettled([this.commentResolverService.resolveCommentAnnotations({request:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""},uniqueId:d,moduleName:m}),this.reactionResolverService.resolveReactionAnnotations({request:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""},uniqueId:O,moduleName:D}),this.recorderResolverService.resolveRecorderAnnotations({request:{documentIds:this.documentIds$.value.map(R=>R.clientDocumentId),organizationId:e??r?.clientOrganizationId??""},uniqueId:U,moduleName:y})]),this.currentDocumentId!==s||this.documentPaths$.value?.organizationId!==f){this.loggingService.log("setting new docid"),this.currentDocumentId=s;let R=new pi,p=new wt;R.clientDocumentId=t,p.clientDocumentId=t,R.folderId=a,p.folderId=a,R.locationId=l,p.locationId=l,R.allDocuments=u,R.optimisticPermissions=g,p.allDocuments=u,p.optimisticPermissions=g,R.veltFolderId=o,p.veltFolderId=o,R.documentId=s,p.documentId=s,f&&(R.organizationId=f,R.clientOrganizationId=e??r?.clientOrganizationId,p.organizationId=f,p.clientOrganizationId=e??r?.clientOrganizationId);let C=`${this.apiKey}`,_=`apiKey/${this.apiKey}`;f&&(C=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${R.organizationId}`,_=`${_}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${R.organizationId}`),p.organization=`apiKey/${this.apiKey}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}`,p.document=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}`,R.presence=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_PRESENCE}/`,R.cursor=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_CURSOR}/`,R.comment=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_COMMENT}/`,p.comment=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_COMMENT}`,R.multiThread=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_MULTI_THREAD}/`,p.multiThread=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_MULTI_THREAD}`,R.tag=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_TAG}/`,R.area=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_AREA}/`,p.area=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_AREA}`,R.arrow=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_ARROW}/`,R.selection=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_SELECTION}/`,R.audioHuddle=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_AUDIO_HUDDLE}/`,R.huddle=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_HUDDLE}/`,R.recorder=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_RECORDER}/`,p.recorder=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_RECORDER}`,R.flock=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_FOLLOW_ALONG}/`,R.syncVideoPlayer=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_SYNC_VIDEO_PLAYER}/`,R.liveState=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_LIVE_STATE}/`,R.liveStateSingleEditorMode=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_LIVE_STATE}/default/singleEditorMode`,R.reaction=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_REACTION}/`,p.reaction=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_REACTION}`,R.crdt=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_CRDT}/`,p.crdt=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_CRDT}`,R.customerMetadata=`${this.apiKey}/${h.FIREBASE_PARTIAL_PATH_CUSTOMER_METADATA}/`,R.views=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_VIEWS}/`,p.notificationViews=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_VIEWS}`,p.documentViews=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_VIEWS}`,p.locationViews=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_LOCATION_VIEWS}`,R.notifications=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATIONS}/`,R.metadata=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_METADATA}/`,R.users=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_USERS}/`,R.documentIam=`${C}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_IAM}/`,R.workspaceIam=`${this.apiKey}/${h.FIREBASE_PARTIAL_PATH_IAM}/`,R.groupContacts=`${C}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_GROUPS}/`,R.globalContacts=`${C}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_GLOBAL}/`,R.logins=`${C}/${h.FIREBASE_PARTIAL_PATH_CONTACTS}/${h.FIREBASE_PARTIAL_PATH_LOGINS}/`,R.userFeedback=`${C}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_FEEDBACK}/`,R.userReportBugs=`${C}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_BUGS}/`,R.userContactUs=`${C}/${h.FIREBASE_PARTIAL_PATH_USER_REQUESTS}/${h.FIREBASE_PARTIAL_PATH_CONTACT_US}/`,f&&(R.organizationMetadata=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_METADATA}/`,R.organizationIam=`${C}/${h.FIREBASE_PARTIAL_PATH_IAM}/`,R.organizationGroups=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_GROUPS}/`,R.organizationNotifications=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/`,s&&(R.organizationNotificationsWithDocumentId=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/`,R.heartbeatByDocument=`${C}/${h.FIREBASE_PARTIAL_PATH_HEARTBEAT_BY_DOCUMENT}/${s}/`),R.organizationNotificationsLastNotificationTimestamp=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_LAST_NOTIFICATION_TIMESTAMP}/${h.FIREBASE_PARTIAL_PATH_DOCS}/`,R.organizationNotificationsUsers=`${C}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_NOTIFICATIONS}/${h.FIREBASE_PARTIAL_PATH_USERS}/`,R.heartbeat=`${C}/${h.FIREBASE_PARTIAL_PATH_HEARTBEAT}/`),p.organizationUsers=`${_}/${h.FIREBASE_PARTIAL_PATH_ORGANIZATION_USERS}`,p.users=`${_}/${h.FIREBASE_PARTIAL_PATH_CENTRAL_USERS}`,p.documentUsers=`${_}/${h.FIREBASE_PARTIAL_PATH_DOCS}/${s}/${h.FIREBASE_PARTIAL_PATH_DOCUMENT_USERS}`,p.notificationDocs=`${_}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_DOCS}`,p.notificationUsers=`${_}/${h.FIREBASE_PARTIAL_PATH_NOTIFICATION_USERS}`,this.documentPaths$.next(R),this.firestorePaths$.next(p),R?.clientOrganizationId&&R?.organizationId&&!(R?.clientOrganizationId===this.getOrganizationConfig()?.clientOrganizationId&&R?.organizationId===this.getOrganizationConfig()?.organizationId)&&this.setOrganizationConfig({organizationId:R?.organizationId,clientOrganizationId:R?.clientOrganizationId}),Promise.allSettled([this.updateFolderMetadata(),this.updateDocumentMetadata(),this.fetchLocationMetadata(),this.updateOrganizationMetadata()]),n&&this.location$.value&&this.removeLocation({}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.SET_DOCUMENTS_SUCCESS,payload:{documentId:s,clientDocumentId:t}}),this.analyticsService.trackEvent(v.Events.Doc.SET_DOCUMENTS_SUCCESS,{documentId:s,clientDocumentId:t},!0,this.getUserIdForAnalytics())}}else this.loggingService.catch("Error in setDocumentIdImpl: API key is not provided.")}catch(r){this.loggingService.catch("Error in setDocumentIdImpl: ",r)}})}unsetDocumentId({source:t,unsetDocumentPaths:e}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentId","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(v.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocumentId",source:t}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,methodName:ne.UNSET_DOCUMENT_ID,source:t}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:e})}catch(i){this.loggingService.catch("Error in unsetDocumentId: ",i)}}unsetDocumentImpl({source:t,unsetDocumentPaths:e}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocumentImpl","color: green;");try{let i=JSON.parse(JSON.stringify(this.documentIds$.value??[])),r=JSON.parse(JSON.stringify(this.documentPaths$.value?.folderId??"")),n=this.getDocContext();this.currentDocumentId&&this.documentPaths$.value&&this.callPreDocumentIdChangeFunctions(this.documentPaths$.value),e&&(this.documentPaths$.next(null),this.firestorePaths$.next(null)),this.currentDocumentId=null,this.location$.next(null),this.excludedLocationIds$.next([]),this.documentMetadata$.next(null),this.locationMetadata$.next(null),this.locations$.next({}),this.documentIds$.next([]),this.setDocContext(null),this.userPermissionService?.revokeAccessOnDocumentUnset({documentIds:i,folderId:r,context:n}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.UNSET_DOCUMENTS_SUCCESS,source:t}),this.analyticsService.trackEvent(v.Events.Doc.UNSET_DOCUMENTS_SUCCESS,{documentId:this.currentDocumentId,documentMetadata:this.documentMetadata$.value?.[this.currentDocumentId??""],message:t==="external"?"User unset document id":"System unset document id",source:t},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetDocumentImpl: ",i)}}unsetDocuments({source:t,unsetDocumentPaths:e=!0}){this.loggingService.log("%c[WB] Calling FUNCTION: unsetDocuments","color: green;");try{t==="internal"&&this.analyticsService.trackEvent(v.Events.Core.UNSET_DOCUMENTS_TRIGGERED,{payload:{methodName:"unsetDocuments",source:t}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.UNSET_DOCUMENTS_TRIGGERED,source:t,methodName:ne.UNSET_DOCUMENTS}),this.unsetDocumentImpl({source:t,unsetDocumentPaths:e})}catch(i){this.loggingService.catch("Error in unsetDocuments: ",i)}}addPreDocumentIdChangeFunction(t,e){try{this.loggingService.log("%c[WB] Calling FUNCTION: addPreDocumentIdChangeFunction","color: green;"),this.preDocumentIdChangeFunctions.set(t,e)}catch(i){this.loggingService.catch("Error in addPreDocumentIdChangeFunction: ",i)}}callPreDocumentIdChangeFunctions(t){return A(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callPreDocumentIdChangeFunctions","color: green;");for(let[e,i]of this.preDocumentIdChangeFunctions)try{yield i(t)}catch(r){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",r)}}catch(e){this.loggingService.catch("Error in callPreDocumentIdChangeFunctions: ",e)}})}fetchOrganizationMetadata(t){return A(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: fetchOrganizationMetadata","color: green;");try{if(!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig()),this.db&&t?.organizationId){let e=t?.organizationId,i=t?.clientOrganizationId,r=this.authService.getUser()?.userId??"",n=yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:i});if(r&&n?.[r]?.organization?.[i]?.errorCode===Oe.PERMISSION_DENIED)return;yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{apiKey:this.apiKey??"",organizationId:e,field:"metadata"}}).then(s=>{s&&!s?.errorCode&&this.organizationMetadata$.next(L(S({},this.organizationMetadata$.value),{[e]:s}))}).catch(s=>{this.loggingService.catch("Error in fetchOrganizationMetadata: ",s)})}}catch(e){this.loggingService.catch("Error in fetchOrganizationMetadata: ",e)}})}fetchDocumentMetadata(t){return A(this,null,function*(){try{if(this.db&&this.authService.getUser()){let e=this.documentPaths$.value,i=this.documentMetadata$.value;if(t=t.filter(r=>!i?.[r.documentId]),t?.some(r=>!r?.documentId||!r?.clientDocumentId)||!e)return;if(this.commonDbService?.shouldUseFirestore()){let r=e?.folderId,n=[],s={organizationId:e?.clientOrganizationId,folderId:r},a=[],o=20;for(let u=0;u<t.length;u+=o)a.push(t.slice(u,u+o));a.forEach(u=>{let g=JSON.parse(JSON.stringify(s));g.documentIds=u.map(f=>f.clientDocumentId),n.push(this.fetchDocuments(g))});let l={};n.length>0&&(yield Promise.all(n).then(u=>{u?.forEach(g=>{g?.forEach(f=>{f?.metadata?.documentId&&(l[f.metadata.documentId]=f.metadata)})}),this.setAllDocumentMetadata(S(S({},this.documentMetadata$.value),l))}).catch(u=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",u)}))}else i?.[e?.documentId??t?.[0]?.documentId]||this.commonDbService?.queryData({feature:"allDocuments",properties:{apiKey:this.apiKey??"",organizationId:e?.organizationId,documentId:e?.documentId??t?.[0]?.documentId,skipObjectValues:!0}}).then(r=>{r?.documentId&&this.setDocumentMetadata(r.documentId,r)}).catch(r=>{this.loggingService.catch("Error in fetchDocumentMetadata: ",r)})}}catch(e){this.loggingService.catch("Error in fetchDocumentMetadata: ",e)}})}fetchLocationMetadata(){return A(this,null,function*(){try{let t=this.isPortableDocumentOpCandidate()?{user:this.authService.getUser(),documentPaths:this.documentPaths$.value,documentIds:this.documentIds$.value}:null,e=!!t&&(yield this.resolvePortableDocumentOps());if(t&&(!e||!this.isPortableLocationFetchCurrent(t)))return;if((this.db||e)&&this.authService.getUser()){let i=t?t.documentPaths:this.documentPaths$.value,r=t?t.documentIds:this.documentIds$.value,n=i?.folderId,s=i?.allDocuments,a=[],o={organizationId:i?.clientOrganizationId,folderId:n,allDocuments:s},l=[],u=20;for(let f=0;f<r.length;f+=u)l.push(r.slice(f,f+u));l.forEach(f=>{let d=JSON.parse(JSON.stringify(o));d.documentIds=f.map(m=>m.clientDocumentId),a.push(this.fetchLocations(d))});let g=this.locationMetadata$.value??{};a.length>0&&Promise.all(a).then(f=>{if(t&&!this.isPortableLocationFetchCurrent(t))return;let d=t?S({},this.locationMetadata$.value??{}):g;f?.forEach(m=>{m?.forEach(O=>{O?.metadata?.documentId&&(d[O.metadata.documentId]=L(S({},d?.[O.metadata.documentId]??{}),{[O.location.id]:O}))})}),Object.keys(d||{}).length>0&&this.locationMetadata$.next(d)}).catch(f=>{this.loggingService.catch("Error in fetchLocationMetadata: ",f)})}}catch(t){this.loggingService.catch("Error in fetchLocationMetadata: ",t)}})}getLocationMetadatas(){return this.locationMetadata$.value}subscribeToCustomerMetadata(){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeToCustomerMetadata","color: green;");try{if(this.customerMetadataSubscription)return;this.db&&this.authService.getUser()&&this.documentPaths$.value&&(this.customerMetadataSubscription=this.commonDbService?.dbListener({feature:"customerMetadata",properties:{skipFirestore:!0}}).pipe(lt(e=>$(null))).subscribe(e=>{this.customerMetadata$.next(e?.data)}))}catch(t){this.loggingService.catch("Error in subscribeToCustomerMetadata: ",t)}}getDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentId","color: green;"),this.documentPaths$.value?.documentId}getClientDocumentId(){return this.loggingService.log("%c[WB] Calling FUNCTION: getClientDocumentId","color: green;"),this.documentPaths$.value?.clientDocumentId}getDocumentIds$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds$","color: green;"),this.documentIds$.asObservable().pipe(k(t=>t?.slice()))}getDocumentIds(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentIds","color: green;"),this.documentIds$.value?.slice()}getLocationMetadata$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocationMetadata$","color: green;"),this.locationMetadata$.asObservable().pipe()}getDocumentPaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths$","color: green;"),this.documentPaths$.asObservable()}getFirestorePaths$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths$","color: green;"),this.firestorePaths$.asObservable()}getDocumentPaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.documentPaths$.value}generateDocumentId(t){try{return`${we(t)}`}catch(e){return this.loggingService.catch("Error in generateDocumentId: ",e),""}}generateOrganizationId(t){try{return`${Xe(t)}`}catch(e){return this.loggingService.catch("Error in generateOrganizationId: ",e),""}}getFirestorePaths(){return this.loggingService.log("%c[WB] Calling FUNCTION: getFirestorePaths","color: green;"),this.firestorePaths$.value}setLocation(i){return A(this,arguments,function*({location:t,source:e="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocation","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:void 0,methodName:"setLocation",source:e}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_LOCATIONS_TRIGGERED,source:e,methodName:ne.SET_LOCATION,payload:{locations:[t],options:void 0}}),this.setLocationsImpl({locations:[t]})}catch(r){this.loggingService.catch("Error in setLocation: ",r)}})}setLocations(r){return A(this,arguments,function*({locations:t,options:e,source:i="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocations","color: green;"),i==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:t,options:e,methodName:"setLocations",source:i}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:ne.SET_LOCATIONS,source:i,payload:{locations:t,options:e}}),this.setLocationsImpl({locations:t,options:e})}catch(n){this.loggingService.catch("Error in setLocations: ",n)}})}getValidLocations(t){try{let e=[];return t&&Array.isArray(t)&&t.forEach(i=>{if(i&&typeof i=="object"){let r=!0;i?.version&&(!i?.version?.id||!i?.version?.name)&&(this.loggingService.catch(`Error in setting location for locationId: ${i?.id}, If you're setting version then add id and name fields to version object.`),r=!1),r&&e.push(i)}}),e}catch(e){this.loggingService.catch("Error in getValidLocations: ",e)}return t}setRootLocation(i){return A(this,arguments,function*({location:t,source:e="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRootLocation","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_ROOT_LOCATION_TRIGGERED,{payload:{location:t,methodName:"setRootLocation",source:e}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_ROOT_LOCATION_TRIGGERED,methodName:ne.SET_ROOT_LOCATION,source:e,payload:{location:t}});let r=Object.values(this.locations$.value).map(n=>n.location).filter(n=>String(n.id)!==String(t.id));this.setLocationsImpl({locations:[t,...r],options:{rootLocationId:t.id}})}catch(r){this.loggingService.catch("Error in DocService setRootLocation:",r)}})}setLocationsImpl({locations:t,options:e}){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setLocationsImpl","color: green;"),t.length===0)return;if(!this.authService.getUser()){!e?.appendLocation&&t.length>0&&(this.draftLocationMap.options=L(S(S({},this.draftLocationMap.options??{}),e??{}),{rootLocationId:t[0].id})),this.draftLocationMap.locations=[...this.draftLocationMap.locations,...t],this.draftLocationMap.options=S(S({},this.draftLocationMap.options),e);return}let r=this.getValidLocations(t),n=[],s=[];this.location$.value?.location.id&&s.push(this.location$.value?.location.id),s=[...s,...Object.values(this.locations$.value).map(l=>l.location.id)].filter(l=>l!==void 0);let a;if(e?.rootLocationId&&e?.rootLocationId!==this.location$.value?.location.id&&(a=r.find(l=>l.id===e?.rootLocationId),!a)){this.loggingService.catch(`Error in setting locations, rootLocationId: ${e?.rootLocationId} not found in locations.`);return}if(e?.appendLocation){if(a){let l=vt(a),u=we(JSON.stringify(l));l.id&&n.push({locationId:u,location:l}),this.location$.next({locationId:u,location:l})}}else{a||(a=r[0]);let l=vt(a),u=we(JSON.stringify(l));l.id&&n.push({locationId:u,location:l}),this.location$.next({locationId:u,location:l})}let o=[];return r.slice(e?.appendLocation?0:1).forEach(l=>{if(l.id!==this.location$.value?.location.id){let u=S({},l),g=this.locations$.value;l?.id&&Object.keys(g).forEach(O=>{let D=g[O];D.location?.id===l.id&&(u=S(S({},D.location),l),delete g?.[O])});let f=this.genarateLocationId(u),d={locationId:f,location:u};u.id&&n.push({locationId:f,location:u}),o.push(d);let m=L(S({},g),{[f]:d});this.locations$.next(m)}}),this.updateDocumentLocationMetadata(n),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.SET_LOCATIONS_SUCCESS,methodName:ne.SET_LOCATIONS,payload:{locations:r,options:e}}),this.analyticsService.trackEvent(v.Events.Doc.SET_LOCATIONS_SUCCESS,{locations:r,options:e},!0,this.getUserIdForAnalytics()),o}catch(i){this.loggingService.catch("Error in setLocationImpl: ",i);return}}addLocation({location:t,source:e="internal"}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addLocation","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.SET_LOCATIONS_TRIGGERED,{payload:{locations:[t],options:{appendLocation:!0},methodName:"addLocation",source:e}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.SET_LOCATIONS_TRIGGERED,methodName:ne.ADD_LOCATION,source:e,payload:{locations:[t],options:{appendLocation:!0}}}),this.setLocationsImpl({locations:[t],options:{appendLocation:!0}})}catch(i){this.loggingService.catch("Error in DocService addLocation:",i);return}}removeLocation({location:t,source:e="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocation","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:[t],methodName:"removeLocation",source:e}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.REMOVE_LOCATIONS_TRIGGERED,source:e,methodName:ne.REMOVE_LOCATION,payload:{locations:[t]}}),t?this.removeLocationsImpl([t],e):e==="external"&&this.removeLocationsImpl(void 0,e)}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}removeLocations({locations:t,source:e="internal"}){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t,methodName:"removeLocations",source:e}}),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.REMOVE_LOCATIONS_TRIGGERED,methodName:ne.REMOVE_LOCATIONS,source:e,payload:{locations:t}}),this.removeLocationsImpl(t,e)}catch(i){this.loggingService.catch("Error in removeLocations: ",i)}}removeLocationsImpl(t,e="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeLocations","color: green;"),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.REMOVE_LOCATIONS_TRIGGERED,{payload:{locations:t},methodName:"removeLocations",message:"System removed locations",source:e},!0,this.getUserIdForAnalytics()),t?t.forEach(i=>{let r=this.genarateLocationId(i);this.getLocation()?.locationId===r&&(this.location$.next(null),e!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(n=>n.id!==i.id))),this.removeCustomLocation(i)}):(this.location$.next(null),this.locations$.next({}),e!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.analyticsService.trackEvent(v.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locations:t},source:e},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in removeLocation: ",i)}}unsetLocationIds(t,e="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsetLocationIds","color: green;"),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Core.UNSET_LOCATIONS_TRIGGERED,methodName:ne.UNSET_LOCATION_IDS,source:e,payload:{locationIds:t}}),e==="internal"&&this.analyticsService.trackEvent(v.Events.Core.UNSET_LOCATIONS_TRIGGERED,{payload:{locationIds:t},methodName:"unsetLocationIds",message:"System unset location ids",source:e},!0,this.getUserIdForAnalytics()),t?.length?t.forEach(i=>{this.getLocation()?.location.id===i&&(this.location$.next(null),e!=="internal"&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(r=>r.id!==i))),this.removeCustomLocationId(i)}):(this.location$.next(null),this.locations$.next({}),e!=="internal"&&(this.draftLocationMap.options=void 0,this.draftLocationMap.locations=[])),this.coreActionsService.triggerAction(E.INIT_UPDATE,{event:v.Events.Doc.REMOVE_LOCATIONS_SUCCESS,methodName:ne.REMOVE_LOCATIONS_SUCCESS,source:e,payload:{locationIds:t}}),this.analyticsService.trackEvent(v.Events.Doc.REMOVE_LOCATIONS_SUCCESS,{payload:{locationIds:t},source:e},!0,this.getUserIdForAnalytics())}catch(i){this.loggingService.catch("Error in unsetLocationIds: ",i)}}getLocation$(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.asObservable()}getLocation(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocation$","color: green;"),this.location$.value?JSON.parse(JSON.stringify(this.location$.value)):null}excludeLocationIds(t){try{this.excludedLocationIds$.next([...t])}catch(e){this.loggingService.catch("Error in excludeLocationIds: ",e)}}getExcludedLocationIds$(){try{return this.excludedLocationIds$.asObservable()}catch(t){return this.loggingService.catch("Error in getExcludedLocationIds$: ",t),$([])}}updateOrganizationMetadata(t){return A(this,null,function*(){try{!t&&this.getOrganizationConfig()&&(t=this.getOrganizationConfig());let e=t?.organizationId,i=t?.clientOrganizationId,r=this.documentPaths$.value;if(this.db&&e&&r?.documentId){if(this.organizationMetadata$.value?.[e])return;let s=new Ui;s.apiKey=this.configService?.getApiKey()??"",s.organizationId=e,s.clientOrganizationId=i;let a=this.authService.getUser()?.userId??"",o=i?yield this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:i}):null;!!(a&&i&&o?.[a]?.organization?.[i]?.errorCode===Oe.PERMISSION_DENIED)?this.loggingService.log(`%c[WB] updateOrganizationMetadata skipped \u2014 user does not have access to organization: ${i}`,"color: orange;"):this.userPermissionService?.hasEditAccess({organizationId:e})&&(yield this.commonDbService?.updateData({feature:"organizationMetadata",data:JSON.parse(JSON.stringify(s)),properties:{organizationId:e,documentId:r?.documentId??""}})),yield this.fetchOrganizationMetadata(t)}}catch(e){this.loggingService.catch("Error in updateOrganizationMetadata: ",e)}})}updateFolderMetadata(){return A(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateFolderMetadata","color: green;"),this.isPortableDocumentOpCandidate()){let t=this.authService.getUser(),e=this.documentPaths$.value;if(yield this.resolvePortableDocumentOps()){t&&(yield this.updatePortableFolderMetadata(t,e));return}}if(this.db&&this.authService.getUser()&&this.documentPaths$.value?.folderId){let t=this.documentPaths$.value;if(!t?.veltFolderId||!t?.organizationId)return;if(!(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{organizationId:t?.organizationId??"",folderId:t?.veltFolderId??""}}))?.metadata){let i=ri({folderId:this.documentPaths$.value?.folderId,clientOrganizationId:t?.clientOrganizationId});if(this.userPermissionService?.hasEditAccess({folderId:this.documentPaths$.value?.veltFolderId??""})){let r=Ue(this.functions,be({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));yield At({methodName:"createFolder",data:{type:"createFolder",metadata:i},getSdkProxy:r,userId:this.authService.getUser()?.userId??""})}}}}catch(t){this.loggingService.catch("Error in updateFolderMetadata: ",t)}})}updateDocumentMetadata(){return A(this,null,function*(){try{if(this.isPortableDocumentOpCandidate()){let t=this.authService.getUser(),e=this.documentPaths$.value,i=t&&e?this.collectDocumentsForMetadataWrite(e).map(r=>({document:r,input:this.buildDocumentMetadataWriteInput(r,e)})):[];if(yield this.resolvePortableDocumentOps()){t&&e&&(yield this.updatePortableDocumentMetadata(t,e,i));return}}if(this.db&&this.authService.getUser()){let t=this.documentPaths$.value;if(t){let e=this.collectDocumentsForMetadataWrite(t),i=e.map(r=>A(this,null,function*(){let n=this.buildDocumentMetadataWriteInput(r,t),s=ni(n),a=oi(n)?this.getDocumentMetadata(r?.documentId??"")??(yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:r?.documentId??"",organizationId:t?.organizationId??"",field:"metadata"}})):void 0,o=si(L(S({},n),{metadata:s,existing:a}));o.refusal&&this.loggingService.catch(Ft(o.refusal,r?.clientDocumentId,t?.folderId)),o.write&&this.userPermissionService?.hasEditAccess({documentId:r?.documentId??"",folderId:t?.allDocuments&&t?.veltFolderId?t?.veltFolderId:void 0})&&(yield this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(o.metadata)),properties:{organizationId:t?.organizationId??"",documentId:r?.documentId??""}}))}));yield Promise.allSettled(i),yield this.fetchDocumentMetadata(e)}}}catch(t){this.loggingService.catch("Error in updateDocumentMetadata: ",t)}})}collectDocumentsForMetadataWrite(t){let e=this.getDocumentIds();return e.find(i=>i.documentId===t.documentId)||e.push({documentId:t.documentId??"",clientDocumentId:t.clientDocumentId??""}),e}buildDocumentMetadataWriteInput(t,e){return{clientMetadata:this.clientDocumentMetadataMap?.[t.clientDocumentId],apiKey:this.configService?.getApiKey()??"",documentId:t.documentId,clientDocumentId:t.clientDocumentId,organizationId:e.organizationId,clientOrganizationId:e.clientOrganizationId,pageInfo:Yt(t.clientDocumentId),folderId:e?.folderId,veltFolderId:e?.veltFolderId,cached:this.documentMetadata$.value?.[t.documentId]}}isPortableDocumentOpCandidate(){try{let t=this.adapterSelectorService;return!!t&&(t.isPortableBackendActive()===!0||t.isPortableBackendPending?.()===!0)}catch(t){return this.loggingService.catch("Error in DocService isPortableDocumentOpCandidate: ",t),!1}}resolvePortableDocumentOps(){return A(this,null,function*(){try{return this.adapterSelectorService.isPortableBackendPending?.()===!0&&(yield Gi(c.PORTABLE_ACTIVATION_WAIT_MS)),this.adapterSelectorService.isPortableBackendActive()===!0}catch(t){return this.loggingService.catch("Error in DocService resolvePortableDocumentOps: ",t),!1}})}isSamePortableSession(t){try{return this.adapterSelectorService.isPortableBackendActive()===!0&&!!t?.userId&&this.authService.getUser()?.userId===t.userId}catch(e){return this.loggingService.catch("Error in DocService isSamePortableSession: ",e),!1}}callPortableDocumentOp(t,e,i){let r=this.adapterSelectorService.resolveDbAdapter(),n=r?.[t];return typeof n!="function"?Promise.resolve({ok:!1,code:"unimplemented",message:`the portable adapter does not implement '${t}'`}):n.call(r,{scope:e,data:i})}updatePortableFolderMetadata(t,e){return A(this,null,function*(){try{if(!this.isSamePortableSession(t)||!e?.folderId||!e?.veltFolderId||!e?.organizationId)return;let i=yield this.callPortableDocumentOp("fetchFolders","org",{organizationId:e.clientOrganizationId,folderId:e.folderId});if(!this.isSamePortableSession(t)||(i?.ok||this.reportPortableDocumentOpFailure("fetchFolders",i),(i?.ok?i.data?.folder:void 0)?.metadata)||!this.userPermissionService?.hasEditAccess({folderId:e.veltFolderId}))return;let n=yield this.callPortableDocumentOp("createFolder","org",{metadata:ri({folderId:e.folderId,clientOrganizationId:e.clientOrganizationId})});n?.ok||this.reportPortableDocumentOpFailure("createFolder",n)}catch(i){this.loggingService.catch("Error in DocService updatePortableFolderMetadata: ",i)}})}updatePortableDocumentMetadata(t,e,i){return A(this,null,function*(){let r=i.map(a=>A(this,[a],function*({document:n,input:s}){try{let o=oi(s),l=si(L(S({},s),{metadata:ni(s),existing:o?this.getDocumentMetadata(n?.documentId??""):void 0}));if(l.refusal&&this.loggingService.catch(Ft(l.refusal,n?.clientDocumentId,e?.folderId)),!l.write||!this.userPermissionService?.hasEditAccess({documentId:n?.documentId??"",folderId:e?.allDocuments&&e?.veltFolderId?e?.veltFolderId:void 0})||!this.isSamePortableSession(t))return;let u=yield this.callPortableDocumentOp("setDocumentMetadata","doc",{organizationId:e.clientOrganizationId,documentId:n.clientDocumentId,metadata:JSON.parse(JSON.stringify(l.metadata))});if(u?.ok){o&&this.isSamePortableSession(t)&&this.setDocumentMetadata(n.documentId,S(S({},this.getDocumentMetadata(n.documentId)??{}),JSON.parse(JSON.stringify(l.metadata))));return}if(Ar(u)){this.loggingService.catch(Ft("folder-mismatch",n?.clientDocumentId,e?.folderId));return}this.reportPortableDocumentOpFailure("setDocumentMetadata",u)}catch(o){this.loggingService.catch("Error in DocService updatePortableDocumentMetadata: ",o)}}));yield Promise.allSettled(r)})}updatePortableDocument(t,e,i){return A(this,null,function*(){try{if(!this.isSamePortableSession(t))return;let r=yield this.callPortableDocumentOp("setDocumentMetadata","doc",{organizationId:i,documentId:e?.clientDocumentId,metadata:JSON.parse(JSON.stringify(e))});if(Ar(r)){this.loggingService.catch(`Error in updateDocuments: document ${e?.clientDocumentId} already exists in a different folder or without one, move this document to folder with REST API`);return}r?.ok||this.reportPortableDocumentOpFailure("setDocumentMetadata",r)}catch(r){this.loggingService.catch("Error in DocService updatePortableDocument: ",r)}})}readPortableStoredDocumentMetadata(t,e,i){return A(this,null,function*(){let r=yield this.fetchPortableDocuments(t,{organizationId:e,documentIds:[i]}),n=Ce(i);return r.find(a=>a?.metadata?.documentId===n)?.metadata??{}})}buildPortableListingBody(t,e){let i={organizationId:t.organizationId};return e&&(i.documentId=e),t.folderId&&(i.folderId=t.folderId),t.documentIds?.length&&!t.allDocuments&&(i.documentIds=t.documentIds.slice(0,h.FIRESTORE_IN_QUERY_LIMIT)),t.allDocuments!==void 0&&(i.allDocuments=t.allDocuments),i}fetchPortableDocuments(t,e){return A(this,null,function*(){try{if(!this.isSamePortableSession(t))return[];let i=yield this.callPortableDocumentOp("fetchDocuments","org",this.buildPortableListingBody(e));if(!this.isSamePortableSession(t))return[];if(!i?.ok)return this.reportPortableDocumentOpFailure("fetchDocuments",i),[];let r=i.data?.documents;return Array.isArray(r)?r:(this.loggingService.log("Tier B fetchDocuments answered ok without a `documents` array; treated as none."),[])}catch(i){return this.loggingService.catch("Error in DocService fetchPortableDocuments: ",i),[]}})}fetchPortableFolders(t,e){return A(this,null,function*(){let i={data:[],parentFolders:[]};try{if(!this.isSamePortableSession(t))return i;let r={organizationId:e.organizationId};e.folderId&&(r.folderId=e.folderId);let n=yield this.callPortableDocumentOp("fetchFolders","org",r);if(!this.isSamePortableSession(t))return i;if(!n?.ok)return this.reportPortableDocumentOpFailure("fetchFolders",n),i;let s=n.data,a=Array.isArray(s?.folders)?s.folders:[];return e.folderId?{data:[s?.folder??{}],parentFolders:a}:{data:a,parentFolders:[]}}catch(r){return this.loggingService.catch("Error in DocService fetchPortableFolders: ",r),i}})}isPortableLocationFetchCurrent(t){return!!t.user&&this.isSamePortableSession(t.user)&&this.documentPaths$.value===t.documentPaths}setPortableLocationMetadata(t,e){return A(this,null,function*(){try{if(!this.isSamePortableSession(t))return;let i=yield this.callPortableDocumentOp("setLocationMetadata","doc",e);i?.ok||this.reportPortableDocumentOpFailure("setLocationMetadata",i)}catch(i){this.loggingService.catch("Error in DocService setPortableLocationMetadata: ",i)}})}fetchPortableLocations(t,e,i){return A(this,null,function*(){try{if(!this.isSamePortableSession(t))return[];let r=this.buildPortableListingBody(e,i?.clientDocumentId),n=yield this.callPortableDocumentOp("fetchLocations","org",r);if(!this.isSamePortableSession(t))return[];if(!n?.ok)return this.reportPortableDocumentOpFailure("fetchLocations",n),[];let s=n.data?.locations;return Array.isArray(s)?s:(this.loggingService.log("Tier B fetchLocations answered ok without a `locations` array; treated as none."),[])}catch(r){return this.loggingService.catch("Error in DocService fetchPortableLocations: ",r),[]}})}reportPortableDocumentOpFailure(t,e){try{let i=e,r=i?.code??"unknown",n=`${tt(i)}${i?.message?` (${i.message})`:""}`,s=r==="failed-precondition"&&qr.has(String(i?.message)),a=Er(e);if(this.loggingService.catch(s?`Tier B ${t} was not sent: ${r}${n}`:a?`Tier B ${t} got no answer, outcome unknown: ${r}${n}`:`Tier B ${t} failed at the gateway: ${r}${n}`,e,void 0,!0),a)return;let o=null;s?o=`Velt [portable backend]: the operation '${t}' was NOT SENT${n}. It is not retried until the next call. This is a client-side precondition \u2014 usually the portable session was not established yet.`:r==="invalid-argument"||r==="unimplemented"?o=`Velt [portable backend]: the operation '${t}' was rejected by the configured backend with '${r}'${n}. The gateway and this SDK disagree about this operation \u2014 check that the deployed gateway release serves it with the body this SDK sends.`:r==="not-found"&&(o=`Velt [portable backend]: the operation '${t}' was answered 'not-found'${n}. On a self-hosted deployment organizations are provisioned out of band, so this is expected until this organization exists on the gateway; the operation is repeated on each call until then. This warning fires once per page load.`);let l=`${t}:${r}`;if(!o||this.reportedPortableDocumentOpFailures.has(l))return;this.reportedPortableDocumentOpFailures.add(l),r==="not-found"?console.warn(o):console.error(o)}catch{}}updateDocumentLocationMetadata(t){return A(this,null,function*(){try{let e=!this.db&&this.isPortableDocumentOpCandidate();if((this.db||e)&&this.authService.getUser()){let i=this.documentPaths$.value;if(i){let r=this.getDocumentIds();r.find(n=>n.documentId===i.documentId)||r.push({documentId:i.documentId??"",clientDocumentId:i.clientDocumentId??""});for(let n of r){let s=e?{}:yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:n?.documentId??"",organizationId:i?.organizationId??"",field:"metadata"}});s?.errorCode&&(s={});let a=[];for(let o of t){let l=new bi;l.locationId=o?.locationId,l.veltLocationId=Qt(o?.location?.id??""),l.location=o?.location,l.pageInfo=Yt(n?.clientDocumentId),l?.pageInfo?.deviceInfo&&delete l?.pageInfo?.deviceInfo;let u=L(S({},s),{[h.FIREBASE_PARTIAL_PATH_LOCATIONS]:L(S({},s[h.FIREBASE_PARTIAL_PATH_LOCATIONS]??{}),{[o?.locationId]:l})});!e&&!this.commonDbService?.shouldUseFirestore()&&a.push(this.commonDbService?.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(u)),properties:{documentId:n?.documentId??"",organizationId:i?.organizationId??""}}));let g=this.locationMetadata$.value;if(g||(g={}),e&&(g=S({},g),g[n.documentId]&&(g[n.documentId]=S({},g[n.documentId]))),o?.location?.id){let f=g?.[n.documentId],d=f?.[o?.location?.id??""];g&&(f||(g[n.documentId]={}),d||(g[n.documentId][o?.location?.id??""]={}),g[n.documentId][o?.location?.id??""]=L(S({},d),{location:o?.location})),Object.keys(g||{}).length>0&&this.locationMetadata$.next(g)}}yield Promise.allSettled(a)}}}}catch(e){this.loggingService.catch("Error in updateDocumentLocationMetadata: ",e)}})}genarateLocationId(t){try{return t&&typeof t=="object"?we(JSON.stringify(vt(t))):0}catch(e){return this.loggingService.catch("Error in genarateLocationId: ",e),0}}removeCustomLocation(t,e="internal"){try{let i=this.genarateLocationId(t),r=this.locations$.value;r[i]&&(delete r[i],this.locations$.next(S({},r)),e!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(n=>n.id!==t.id)))}catch(i){this.loggingService.catch("Error in DocService removeLocation:",i)}}removeCustomLocationId(t,e="internal"){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomLocationId","color: green;");let i=this.locations$.value;Object.entries(i).forEach(([r,n])=>{n.location.id===t&&(delete i[r],this.locations$.next(S({},i)),e!=="internal"&&this.isDocumentIdInDebounceQueue&&(this.draftLocationMap.locations=this.draftLocationMap.locations.filter(s=>s.id!==t)))})}catch(i){this.loggingService.catch("Error in DocService removeCustomLocationId:",i)}}getLocationByClientLocationId(t){try{let e=this.getLocation()?.location;if(e?.id===t)return e;{let i=this.getLocations();Object.keys(i).forEach(r=>{let n=i[r];n.location?.id===t&&(e=n.location)})}return e}catch(e){this.loggingService.catch("Error in DocService getLocationByClientLocationId:",e);return}}removeLocationIfNotInDom(){try{let t=this.locations$.value,e=document.querySelectorAll(`[${h.ATTRIBUTES.VELT_LOCATION}]`),i=[];e.forEach(r=>{let n=r.getAttribute(h.ATTRIBUTES.VELT_LOCATION);if(n){let s=JSON.parse(n),a=this.genarateLocationId(s);i.push(a)}}),Object.keys(t).forEach(r=>{let n=t[r];i.includes(n.locationId)||delete t[r]}),this.locations$.next(S({},t))}catch(t){this.loggingService.catch("Error in DocService removeLocationIfNotInDom:",t)}}getLocations$(){try{return this.locations$.asObservable()}catch(t){return this.loggingService.catch("Error in DocService getLocations$:",t),$({})}}getLocations(){try{return this.locations$.value}catch(t){return this.loggingService.catch("Error in DocService getLocations:",t),{}}}getLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getLocationFromElement","color: green;");let e=null;if(t?.getAttribute(h.ATTRIBUTES.VELT_LOCATION)?e=t:e=t.closest(`[${h.ATTRIBUTES.VELT_LOCATION}]`),e){let i=e?.getAttribute(h.ATTRIBUTES.VELT_LOCATION);if(i){let r=JSON.parse(i);return{locationId:this.genarateLocationId(r),location:r}}}return null}catch(e){return this.loggingService.catch("Error in DocService getLocationFromElement:",e),null}}getElementMapWithLocation(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getElementMapWithLocation","color: green;");let t={};return document.querySelectorAll(`[${h.ATTRIBUTES.VELT_LOCATION}], [${h.ATTRIBUTES.VELT_LOCATION_ID}]`).forEach(i=>{if(i.getAttribute(h.ATTRIBUTES.VELT_LOCATION)){let r=this.getLocationFromElement(i);r?.locationId&&(t[r.locationId]={element:i,location:r})}else if(i.getAttribute(h.ATTRIBUTES.VELT_LOCATION_ID)){let r=i.getAttribute(h.ATTRIBUTES.VELT_LOCATION_ID);if(r){let n=this.getLocationByClientLocationId(r);n?.locationId&&(t[n.locationId]={element:i,location:n});let s={id:r},a=this.genarateLocationId(s);t[r]={element:i,location:{locationId:a,location:s}}}}}),t}catch(t){return this.loggingService.catch("Error in DocService getElementMapWithLocation:",t),{}}}getAdditionLocationFromElement(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: getAdditionLocationFromElement","color: green;");let e;if(e=t?.closest(`[${h.ATTRIBUTES.VELT_LOCATION}], [${h.ATTRIBUTES.VELT_LOCATION_ID}]`),e){if(e?.getAttribute(h.ATTRIBUTES.VELT_LOCATION)){let i=e?.getAttribute(h.ATTRIBUTES.VELT_LOCATION);if(i)return JSON.parse(i)}else if(e?.getAttribute(h.ATTRIBUTES.VELT_LOCATION_ID)){let i=e?.getAttribute(h.ATTRIBUTES.VELT_LOCATION_ID);if(i)return{id:i}}}return null}catch(e){return this.loggingService.catch("Error in DocService getAdditionLocationFromElement:",e),null}}getAdditionalDocumentIdFromElement(t){try{return t?.closest(`[${h.ATTRIBUTES.VELT_DOCUMENT_ID}]`)?.getAttribute(h.ATTRIBUTES.VELT_DOCUMENT_ID)||null}catch(e){return this.loggingService.catch("Error in DocService getAdditionalDocumentIdFromElement:",e),null}}getDocumentMetadata(t){try{return t?this.documentMetadata$.value?.[t]||null:this.documentMetadata$.value?.[this.documentPaths$.value?.documentId??""]||null}catch(e){return this.loggingService.catch("Error in DocService getDocumentMetadata:",e),null}}getAllDocumentMetadata$(t){return this.getAllDocumentMetadataMap$().pipe(k(e=>e?.[t??this.documentPaths$.value?.documentId??""]||null),q(X))}getAllDocumentMetadata(){try{return Object.values(this.documentMetadata$.value||{})}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),[]}}getAllDocumentMetadataMap$(){return this.documentMetadata$.asObservable().pipe(k(t=>t||{}),q(X))}getAllDocumentMetadataMap(){try{return this.documentMetadata$.value||{}}catch(t){return this.loggingService.catch("Error in DocService getAllDocumentMetadata:",t),{}}}getDocumentMetadataOfAvailableDocuments(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentMetadataOfAvailableDocuments","color: green;");let t=this.documentMetadata$.value||{},e={},i=this.documentPaths$.value?.veltFolderId,r=this.documentPaths$.value?.allDocuments;if(i&&r)Object.values(t).forEach(n=>{n?.documentId&&n?.veltFolderId===i&&(e[n.documentId]=n)});else{let n=this.documentIds$.value;if(n?.length)n.forEach(s=>{let a=t?.[s.documentId];a&&(e[s.documentId]=a)});else if(this.documentPaths$.value?.documentId){let s=t?.[this.documentPaths$.value?.documentId];s&&(e[this.documentPaths$.value?.documentId]=s)}}return Object.values(e)}catch(t){return this.loggingService.catch("Error in DocService getDocumentMetadataOfAvailableDocuments:",t),[]}}getDocumentMetadata$(t){return this.documentMetadata$.asObservable().pipe(k(e=>e?.[t??this.documentPaths$.value?.documentId??""]||null),q(X))}setDocumentMetadata(t,e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setDocumentMetadata","color: green;");let i=JSON.parse(JSON.stringify(this.documentMetadata$.value??{}));i[t]=e,this.documentMetadata$.next(i)}catch(i){this.loggingService.catch("Error in DocService setDocumentMetadata:",i)}}setAllDocumentMetadata(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setAllDocumentMetadata","color: green;"),this.documentMetadata$.next(t)}catch(e){this.loggingService.catch("Error in DocService setAllDocumentMetadata:",e)}}getOrganizationMetadata(t){return this.organizationMetadata$.value?.[t]||null}getOrganizationMetadata$(t){return this.organizationMetadata$.asObservable().pipe(k(e=>e?.[t]||null))}getOrganizationMetadataMap$(){return this.organizationMetadata$.asObservable().pipe(k(t=>t||{}),q(X))}getCustomerMetadata(){return this.customerMetadata$.value}getCustomerMetadata$(){return this.customerMetadata$.asObservable()}getOrganizationConfig$(){return this.organizationConfig$.asObservable().pipe(q(X))}getOrganizationConfig(){return this.organizationConfig$.value}setOrganizationConfig(t){try{this.loggingService.log("%c[WB] Calling FUNCTION: setOrganizationConfig","color: green;");let e=JSON.parse(JSON.stringify(t));this.organizationConfig$.next(e)}catch(e){return this.loggingService.catch("Error in DocService setOrganizationConfig:",e),!1}return!0}getMetadataFromType(t,e){try{switch(t){case"area":return;case"comment":return e?.multiThreadAnnotationId?this.commentService?.getMultiThreadAnnotationById(e.multiThreadAnnotationId)?.metadata:void 0;case"reaction":case"recorder":return e?.commentAnnotationId?this.commentService?.getAnnotationById(e.commentAnnotationId)?.metadata:void 0;default:return}}catch(i){this.loggingService.catch("Error in DocService getMetadataFromType:",i);return}}getDefaultMetadata({clientDocumentId:t,documentId:e}){try{let i=this.documentPaths$.value;if(!i)return;let r=t||i.clientDocumentId,n=e||i.documentId,s=this.getDocumentMetadata(n),a=n===i.documentId,o=s?s.folderId:a?i.folderId:void 0,l=s?s.veltFolderId:a?i.veltFolderId:void 0;return S(S({apiKey:this.configService.getApiKey()??void 0,clientDocumentId:r,clientOrganizationId:i.clientOrganizationId,documentId:n,organizationId:i.organizationId},o?{folderId:o}:{}),l?{veltFolderId:l}:{})}catch(i){this.loggingService.catch("Error in DocService getDefaultMetadata:",i);return}}getBaseMetadata(t,e){try{let i,r;e?.element?i=this.getAdditionalDocumentIdFromElement(e.element)||void 0:e?.clientDocumentId&&(i=e.clientDocumentId),i&&(r=this.generateDocumentId(i));let n=this.getMetadataFromType(t,e),s=this.getDefaultMetadata({clientDocumentId:i,documentId:r}),a=n||s||{};return a.sdkVersion=ke(),a}catch(i){return this.loggingService.catch("Error in DocService getBaseMetadata:",i),{}}}getServerId({documentId:t,organizationId:e}){try{return t&&(t=this.generateDocumentId(t)),e&&(e=this.generateOrganizationId(e)),{documentId:t,organizationId:e}}catch(i){return this.loggingService.catch("Error in DocService getServerId:",i),null}}fetchDocuments(t){return A(this,null,function*(){try{let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchDocuments: organizationId is required"),[];if(this.isPortableDocumentOpCandidate()){let n=JSON.parse(JSON.stringify(t));if(yield this.resolvePortableDocumentOps())return this.fetchPortableDocuments(e,n)}if(t?.folderId){let n=Ee(t?.folderId);i.push(ge("metadata.veltFolderId","==",n))}return t?.documentIds?.length&&!t?.allDocuments&&i.push(ge("metadata.documentId","in",t?.documentIds?.map(n=>this.generateDocumentId(n)).slice(0,h.FIRESTORE_IN_QUERY_LIMIT))),yield this.commonDbService?.queryData({feature:"allDocuments",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(e){return this.loggingService.catch("Error in DocService fetchDocuments:",e),[]}})}fetchLocations(t){return A(this,null,function*(){try{let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!t?.organizationId)return this.commonDbService?.shouldUseFirestore()&&this.loggingService.catch("Error in fetchLocations: organizationId is required"),[];if(this.isPortableDocumentOpCandidate()){let n=JSON.parse(JSON.stringify(t)),s=this.documentPaths$.value;if(yield this.resolvePortableDocumentOps())return this.fetchPortableLocations(e,n,s)}if(t?.folderId){let n=Ee(t?.folderId);i.push(ge("metadata.veltFolderId","==",n))}return t?.documentIds?.length&&!t?.allDocuments&&i.push(ge("metadata.documentId","in",t?.documentIds?.map(n=>this.generateDocumentId(n)).slice(0,h.FIRESTORE_IN_QUERY_LIMIT))),yield this.commonDbService?.queryData({feature:"allLocations",properties:{firestoreQuery:i,apiKey:this.apiKey??"",organizationId:this.generateOrganizationId(t?.organizationId)??this.documentPaths$.value?.organizationId,documentId:this.documentPaths$.value?.documentId}})}catch(e){return this.loggingService.catch("Error in DocService fetchLocations:",e),[]}})}updateDocuments(t){return A(this,null,function*(){try{typeof t=="object"&&(t=JSON.parse(JSON.stringify(t??{})));let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,documents:r,folderId:n}=t;if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateDocuments: organizationId is required"),[];let s=Be(i);if(!r||r.length===0)return this.loggingService.catch("Error in updateDocuments: documents is required"),[];let a=[],o=this.isPortableDocumentOpCandidate(),l=o?{}:this.documentMetadata$.value??{},u=this.documentPaths$.value?.folderId,g=o&&(yield this.resolvePortableDocumentOps()),f=()=>o?u:this.documentPaths$.value?.folderId;for(let d of r)if(d?.documentId){d.organizationId=s,d.clientOrganizationId=i,d.clientDocumentId=d.documentId;let m=Ce(d.documentId);d.documentId=m,d.apiKey=this.configService.getApiKey()??void 0,(n||f())&&(d.folderId=n||f(),d.veltFolderId=Ee(n||f()||""));let O=()=>{if(n&&f()&&n!==f())return;let U=l?.[m];U?l[m]=S(S({},U),d):l[m]=d},D=g?yield this.readPortableStoredDocumentMetadata(e,i,d.clientDocumentId):yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:m,organizationId:s,field:"metadata"}});if(D?.errorCode&&(D={}),D&&D.apiKey&&D.folderId&&n&&D.folderId!=d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists with different folderId: ${D.folderId}`);continue}if(D&&D.apiKey&&!D.folderId&&d.folderId){this.loggingService.catch(`Error in updateDocuments: document ${d.clientDocumentId} already exists, move this document to folder with REST API`);continue}O(),d&&this.commonDbService&&this.userPermissionService?.hasEditAccess({documentId:d?.documentId??""})&&a.push(g?this.updatePortableDocument(e,d,i):this.commonDbService.updateData({feature:"documentMetadata",data:JSON.parse(JSON.stringify(d)),properties:{organizationId:s,documentId:m}}))}if(yield Promise.all(a),g&&!this.isSamePortableSession(e))return;if(o){let d=S({},this.documentMetadata$.value??{});Object.entries(l).forEach(([m,O])=>{d[m]=d[m]?S(S({},d[m]),O):O}),this.setAllDocumentMetadata(d)}else this.setAllDocumentMetadata(l)}catch(e){return this.loggingService.catch("Error in DocService updateDocuments:",e),[]}})}updateLocations(t){return A(this,null,function*(){try{let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let{organizationId:i,locations:r,documentIds:n}=t;if((!n||n.length===0)&&(n=this.documentIds$.value.map(g=>g.clientDocumentId)??[],n.length===0))return this.loggingService.catch("Error in updateLocations: documentId is required"),[];if(!i&&(i=this.documentPaths$.value?.clientOrganizationId,!i))return this.loggingService.catch("Error in updateLocations: organizationId is required"),[];if(!r||r.length===0)return this.loggingService.catch("Error in updateLocations: locations is required"),[];let s=n.map(g=>Ce(g)),a=this.isPortableDocumentOpCandidate(),o=a&&(yield this.resolvePortableDocumentOps());if(a&&(!o||!this.isSamePortableSession(e)))return this.authService.getUser()?.userId===e.userId&&this.loggingService.catch("Velt [portable backend]: updateLocations was not sent \u2014 the portable backend did not become active in time.",void 0,void 0,!0),[];let l=[],u=o?JSON.parse(JSON.stringify(this.locationMetadata$.value??{})):this.locationMetadata$.value;if(u||(u={}),s.forEach((g,f)=>{r.forEach(d=>{let m=this.location$.value;if(d?.id===m?.location?.id&&this.location$.next({locationId:m?.locationId,location:d}),d?.id){delete d?.metadata;let O=Qt(d.id),D=u?.[g],U=D?.[d.id];u&&(D||(u[g]={}),U||(u[g][d.id]={}),u[g][d.id]=L(S({},U),{location:d}));let y=JSON.parse(JSON.stringify({location:d}));d&&o?l.push(this.setPortableLocationMetadata(e,{organizationId:i,documentId:n[f],locationId:O,data:y})):d&&this.commonDbService&&l.push(this.commonDbService.updateData({feature:"locationMetadata",data:y,properties:{organizationId:Be(i),documentId:g,id:O}}))}})}),yield Promise.all(l),o&&!this.isSamePortableSession(e))return;Object.keys(u||{}).length>0&&this.locationMetadata$.next(u)}catch(e){return this.loggingService.catch("Error in DocService updateLocations:",e),[]}})}fetchFolders(t){return A(this,null,function*(){try{let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),[];let i=[];if(!t?.organizationId)return this.loggingService.catch("Error in fetchFolders: organizationId is required"),{data:[],parentFolders:[]};if(this.isPortableDocumentOpCandidate()){let s={organizationId:t.organizationId,folderId:t.folderId};if(yield this.resolvePortableDocumentOps())return this.fetchPortableFolders(e,s)}let r=[],n=this.generateOrganizationId(t?.organizationId);if(t?.folderId){let s=Ee(t?.folderId);i=yield this.commonDbService?.getData({feature:"folder",properties:{folderId:s,apiKey:this.apiKey??"",organizationId:n,documentId:this.documentPaths$.value?.documentId}}),i&&(i=[i]),r=yield this.commonDbService?.queryData({feature:"allFolders",properties:{firestoreQuery:[ge("metadata.veltParentFolderId","==",s)],folderId:s,apiKey:this.apiKey??"",organizationId:n,documentId:this.documentPaths$.value?.documentId}})}else i=yield this.commonDbService?.queryData({feature:"allFolders",properties:{apiKey:this.apiKey??"",organizationId:n,documentId:this.documentPaths$.value?.documentId}});return{data:i,parentFolders:r}}catch(e){return this.loggingService.catch("Error in DocService getFoldersRequest:",e),{data:[],parentFolders:[]}}})}getDocumentIam$(){return this.authService.getUser$().pipe(se(t=>t?this.documentPaths$.pipe(se(e=>e?.documentIam?this.commonDbService?.dbListener({feature:"documentIam",properties:{documentId:e.documentId,organizationId:e.organizationId,isCollection:!1}}).pipe(k(i=>i?.data?.docIamConfig??i?.data),q((i,r)=>JSON.stringify(i??{})===JSON.stringify(r??{}))):$(null))):$(null)))}getDocumentAccessType(t){try{return t&&t.features&&t.features.all?t.features.all.restricted?Fe.RESTRICTED:Fe.PUBLIC:t&&t.documentAccessType?t.documentAccessType:Fe.PUBLIC}catch(e){return this.loggingService.catch("Error in DocService getDocumentAccessType:",e),Fe.PUBLIC}}changeDocumentAccessType(t){return A(this,null,function*(){try{let e=this.documentPaths$.value;if(e){let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e?.documentId??"",organizationId:e?.organizationId??"",field:"docIamConfig"}});if(i?.errorCode)return;switch(delete i.documentAccessType,i.features||(i.features={}),i.features.all||(i.features.all={}),t){case Fe.PUBLIC:i.features.all.restricted=!1;break;case Fe.RESTRICTED:i.features.all.restricted=!0,i.features.all.guestMode=!1;break;default:break}this.commonDbService?.updateData({feature:"documentAccessType",data:JSON.parse(JSON.stringify(i)),properties:{documentId:e?.documentId??"",organizationId:e?.organizationId??""}})}}catch(e){this.loggingService.catch("Error in DocService changeDocumentAccessType:",e)}})}getUserIdForAnalytics(){try{return this.authService?.getAuthUser()?.uid||""}catch(t){return this.loggingService.catch("Error in DocService getUserIdForAnalytics:",t),""}}setUIState(t){try{this.uiState.next(S(S({},this.uiState.value),t))}catch(e){this.loggingService.catch("Error in DocService setUIState:",e)}}getUIState$(){return this.uiState.asObservable()}};c.PORTABLE_ACTIVATION_WAIT_MS=1e4,c.\u0275fac=function(e){return new(e||c)(T(oe),T(Ae),T(Nt),T(qi),T(_e),T(B),T(me),T(Re),T(Pe),T(H),T(ze),T(Ne))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();var Rr=Symbol("portable-directory-unserved"),qt=class{constructor(c,z){this.users=c,this.unansweredUserIds=z}},K=(()=>{let c=class c{constructor(t,e,i,r,n){this.analyticsService=t,this.authService=e,this.coreActionsService=i,this.docService=r,this.loggingService=n,this.resolveOrganizationUsers=new P(!0),this.resolveFolderUsers=new P(!0),this.resolveDocumentUsers=new P(!0),this.unresolvedUsers=new P([]),this.resolveTimeout=60*1e3,this.resolveAttempts=new Map,this.subscriptions=new ui,this.userDataProvider$=new P(null),this.anonymousUserDataProvider$=new P(null),this.userIdByEmailCache={},this.userById$=new P({}),this.customContactUserById$=new P({}),this.userByIdCalled$=new P({}),this.userDirectoryUnanswerableWarned=!1,this.portableDirectoryUnserved=!1,this.resolvedUsersGeneration=0,this.getUserById=s=>{try{let a=this.userById$.value?.[s],o=this.customContactUserById$.value?.[s];return o?a?S(S({},a),o):o:a}catch(a){this.loggingService.catch("Error in UsersService getUserById:",a);return}};try{this.docService.setUsersService(this),this.analyticsService.setUserService(this),this.authService.setUsersService(this),this.subscribeToIdentityChanges(),this.docService.getDocumentPaths$().pipe(Ie(s=>!!s),se(()=>this.getUnresolvedUsers$().pipe(Ie(s=>s.length>0),Ii(300),$e(20),se(s=>{let a=this.docService.getOrganizationConfig()?.organizationId;return this.commonDbService?this.commonDbService?.dbListener({feature:"allOrganizationUsers",properties:{organizationId:a,isCollection:!0,useQuery:!0,firestoreQuery:[bt(ge("user.userId","in",s.slice(0,20)))]}}).pipe(k(o=>o?.data),dt(o=>{if(o&&typeof o=="object"){delete o.undefined,delete o.null;let l=Object.values(o??{}),u=l.map(f=>f?.user).filter(f=>!!f&&(!!f.name||!!f.email||!!f.photoUrl));u.length>0&&this.setUserByIds(u);let g=s.filter(f=>!l.some(d=>d.user.userId===f));g.length!==s.length&&this.setUnresolvedUsers(g)}})):$([])})))).subscribe()}catch(s){this.loggingService.catch("Error in UsersService constructor:",s)}}subscribeToIdentityChanges(){try{let t=this.authService.getUser$?.(),e=this.docService.getOrganizationConfig$?.();if(!t||!e)return;this.subscriptions.add(Ve([t.pipe(k(i=>i?.userId??null)),e.pipe(k(i=>i?.organizationId??null))]).pipe(q((i,r)=>i[0]===r[0]&&i[1]===r[1]),Ai()).subscribe(([[i,r],[n,s]])=>{(i!==null&&i!==n||r!==null&&r!==s)&&this.resetResolvedUsers()}))}catch(t){this.loggingService.catch("Error in UsersService subscribeToIdentityChanges:",t)}}resetResolvedUsers(){try{this.resolvedUsersGeneration++,this.userById$.next({}),this.userByIdCalled$.next({}),this.unresolvedUsers.next([]),this.resolveAttempts.clear(),this.userIdByEmailCache={}}catch(t){this.loggingService.catch("Error in UsersService resetResolvedUsers:",t)}}setCommonDbService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCommonDbService","color: green;"),this.commonDbService=t}catch(e){this.loggingService.catch("Error in UsersService setCommonDbService:",e)}}setContactService(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactService","color: green;"),this.contactService=t}catch(e){this.loggingService.catch("Error in UsersService setContactService:",e)}}ngOnDestroy(){try{this.subscriptions.unsubscribe(),this.resolveAttempts.clear()}catch(t){this.loggingService.catch("Error in UsersService ngOnDestroy:",t)}}isResolverForFeatureDisabled(t){let e=this.userDataProvider$.getValue();try{switch(t){case"allOrganizationUsers":return e?!this.resolveOrganizationUsers.value:!0;case"allFolderUsers":return e?!this.resolveFolderUsers.value:!0;case"allDocumentUsers":return e?!this.resolveDocumentUsers.value:!0;default:return!1}}catch(i){return this.loggingService.catch("Error in UsersService isResolverForFeatureDisabled:",i),!1}}resolveUsers(o){return A(this,arguments,function*({userIds:t,forceResolve:e,feature:i,organizationId:r,skipUserCheck:n=!1,uniqueId:s,moduleName:a}){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUsers","color: green;");let l=!1;if(i&&(l=this.isResolverForFeatureDisabled(i)),l)return{};{let u={},g=[],f={};if(t?.forEach(d=>{let m=this.getUserById(d);m?u[d]=m:this.userByIdCalled$.getValue()[d]?e&&g.push(d):(g.push(d),this.userByIdCalled$.next(L(S({},this.userByIdCalled$.getValue()),{[d]:!0})))}),g.length>0&&this.isUserDirectoryUnanswerable())return this.answerFromOwnProfileOnly(g,u);if(g.length>0){let d=s||b();this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:d,moduleName:a,methodName:ce.RESOLVE_USERS,source:"internal",payload:{userIds:g,organizationId:r,feature:i,forceResolve:e,skipUserCheck:n,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}});let m={},O=!1,D=!1,U=new Set,y=new Set,R=this.resolvedUsersGeneration,p=!1;try{let C,_=new Promise((V,ie)=>{C=setTimeout(()=>{ie(new Error("User resolution timeout"))},this.userDataProvider$.getValue()?.config?.resolveTimeout||this.userDataProvider$.getValue()?.resolveTimeout||this.resolveTimeout)}),Q=yield Promise.race([this.getUsersFromDB({userIds:g,organizationId:r,skipUserCheck:n}).finally(()=>{clearTimeout(C)}),_]);Q===Rr?D=!0:Q==null?O=!0:Q instanceof qt?(m=Q.users,U=Q.unansweredUserIds):m=Q,this.analyticsService.trackEvent(v.Events.Resolver.USER_RESOLVER_GET,{sourceMethod:"resolveUsers",source:"sdk",userIds:g}),this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:d,methodName:ce.RESOLVE_USERS,moduleName:a,source:"internal",payload:{result:m,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}catch(C){O=!0,this.loggingService.catch("Error in UsersService resolveUsers getUsers:",C,{userIds:g}),this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:d,methodName:ce.RESOLVE_USERS,moduleName:a,source:"internal",payload:{error:C,userIds:g,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}})}finally{p=R!==this.resolvedUsersGeneration}if(p)return this.loggingService.log("[WB] UsersService resolveUsers: dropped an answer that outlived its user/organization."),{};{let C=this.authService.getProvidedOrCurrentUserId?.();(D?[]:g)?.forEach(_=>{if(!m[_]){let Q=new Set([...this.getUnresolvedUsers(),_]);this.unresolvedUsers.next(Array.from(Q));let V=O||U.has(_);if(V&&this.clearUserByIdCalledFlag(_),C&&_===C)return;m[_]={userId:_,name:`User ${_}`},V&&y.add(_)}})}if(Object.entries(m).forEach(([C,_])=>{_&&(u[C]=m?.[C],y.has(C)||(f[C]=m?.[C]))}),y.size>0&&this.authService.setOptionalPropertiesToUsers(Array.from(y).map(C=>m[C]).filter(Boolean)),D)return this.answerFromOwnProfileOnly(g,u)}return Object.keys(f).length>0&&(this.authService.setOptionalPropertiesToUsers(Object.values(f)),this.mergeUsersIntoStore(Object.values(f)),Object.keys(f).forEach(d=>{let m=this.getUserById(d);m&&(u[d]=m)})),u}}catch(l){this.loggingService.catch("Error in UsersService resolveUsers:",l);let u=s||b();return this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.USER_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:u,methodName:ce.RESOLVE_USERS,moduleName:a,source:"internal",payload:{error:l,userIds:t,externalUserDataProviderAvailable:this.externalUserDataProviderAvailable()}}),{}}})}isUserDirectoryUnanswerable(){try{return!this.userDataProvider$.getValue()&&this.commonDbService?.isPortableSession?.()===!0&&(this.portableDirectoryUnserved||this.commonDbService?.canAskPortableOrganizationUsers?.()!==!0)}catch(t){return this.loggingService.catch("Error in UsersService isUserDirectoryUnanswerable:",t),!1}}answerFromOwnProfileOnly(t,e){try{let r=this.authService.getUser();if(r?.userId&&t.includes(r.userId)){let i=JSON.parse(JSON.stringify(r)),{contacts:s,isAdmin:a}=i,o=at(i,["contacts","isAdmin"]);this.mergeUsersIntoStore([o]);let l=this.getUserById(r.userId);l&&(e[r.userId]=l)}let n=t.filter(s=>s!==r?.userId);n.forEach(s=>this.clearUserByIdCalledFlag(s)),n.length>0&&this.portableDirectoryUnserved&&!this.userDirectoryUnanswerableWarned&&(this.userDirectoryUnanswerableWarned=!0,console.warn("Velt [Tier B]: this deployment has no user directory the SDK can read yet (the gateway does not serve getOrganizationUsers yet), so names and avatars of OTHER users are not available on rows that store only a user id; they appear once the gateway serves it. Set a user data provider to supply them meanwhile. This warning fires once per session."))}catch(r){this.loggingService.catch("Error in UsersService answerFromOwnProfileOnly:",r)}return e}clearUserByIdCalledFlag(t){try{let e=this.userByIdCalled$.getValue();if(e?.[t]){let i=S({},e);delete i[t],this.userByIdCalled$.next(i)}}catch(e){this.loggingService.catch("Error in UsersService clearUserByIdCalledFlag:",e)}}getUnresolvedUsers$(){return this.unresolvedUsers.asObservable()}getUnresolvedUsers(){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUnresolvedUsers","color: green;");try{return JSON.parse(JSON.stringify(this.unresolvedUsers.getValue()))}catch(t){return this.loggingService.catch("Error in UsersService getUnresolvedUsers:",t),[]}}setUnresolvedUsers(t){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUnresolvedUsers","color: green;");try{if(Array.isArray(t)){let e=JSON.parse(JSON.stringify(t));this.unresolvedUsers.next(e)}}catch(e){this.loggingService.catch("Error in UsersService setUnresolvedUsers:",e)}}getUsersFromDB(r){return A(this,arguments,function*({userIds:t,organizationId:e,skipUserCheck:i=!1}){this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUsersFromDB","color: green;");try{let n=this.userDataProvider$.getValue();if(n){if(n.config?.getConfig?.url){if(e||(e=this.docService.getDocumentPaths()?.clientOrganizationId??this.docService.getOrganizationConfig()?.clientOrganizationId),!e)return this.loggingService.catch("Error in getUsersFromDB: organizationId is required when using getConfig"),null;let l={organizationId:e,userIds:t},u=yield J(n.config.getConfig.url,n.config.getConfig.headers,l,!0,n.config.getConfig.credentials);return u.statusCode!==200?(this.loggingService.catch(`Error in getUsersFromDB: config-based request failed with statusCode ${u.statusCode}. Message: ${u.message||"Unknown error"}`),null):u.data??{}}let o=yield n.get(t);if(o&&typeof o=="object"&&"success"in o&&"statusCode"in o&&typeof o.success=="boolean"&&typeof o.statusCode=="number"){let l=o;return l.statusCode===200&&l.data?l.data:(this.loggingService.catch(`Error in getUsersFromDB: provider returned error response with statusCode ${l.statusCode}`),null)}return o}if(this.commonDbService?.isPortableSession?.()===!0&&this.commonDbService?.canAskPortableOrganizationUsers?.()===!0)return this.getUsersFromPortableDirectory(t,e);if(e||(e=this.docService.getOrganizationConfig()?.organizationId),!e)return null;let s=(yield this.getUsersFromDBWithBatching({userIds:t,organizationId:e,skipUserCheck:i}))??[];this.contactService?.setResolvedUsers(s.flat());let a={};return s.forEach(o=>{o.forEach(l=>{l?.user?.userId&&(a[l.user.userId]=l.user)})}),a}catch(n){return this.loggingService.catch("Error in UsersService getUsersFromDB:",n),null}})}getUsersFromPortableDirectory(t,e){return A(this,null,function*(){let i=e??this.docService.getOrganizationConfig()?.clientOrganizationId??this.docService.getDocumentPaths()?.clientOrganizationId;if(!i)return null;let r=[];for(let g=0;g<t.length;g+=h.FIRESTORE_IN_QUERY_LIMIT)r.push(t.slice(g,g+h.FIRESTORE_IN_QUERY_LIMIT));let n=yield Promise.all(r.map(g=>this.commonDbService.getPortableOrganizationUsers({organizationId:i,userIds:g})));if(n.some(g=>Xi(g)))return this.portableDirectoryUnserved=!0,Rr;let s=n.find(g=>!g?.ok);if(s){let g=s;this.loggingService.catch("Velt [portable backend]: getOrganizationUsers was refused by the gateway: ",{code:g?.code,message:g?.message})}let a=n.filter(g=>g?.ok);if(a.length===0)return null;let o=a.flatMap(g=>g.data?.users??[]);this.contactService?.setResolvedUsers(o);let l={};if(o.forEach(g=>{g?.user?.userId&&(l[g.user.userId]=g.user)}),!s)return l;let u=new Set(r.filter((g,f)=>!n[f]?.ok).flat());return new qt(l,u)})}getUsersFromDBWithBatching(r){return A(this,arguments,function*({userIds:t,organizationId:e,skipUserCheck:i=!1}){try{if(!t?.length)return[];let n=[];for(let o=0;o<t.length;o+=h.FIRESTORE_IN_QUERY_LIMIT)n.push(t.slice(o,o+h.FIRESTORE_IN_QUERY_LIMIT));let s=n.map((o,l)=>A(this,null,function*(){try{return(yield this.commonDbService?.queryData({feature:"allOrganizationUsers",properties:{organizationId:e,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ge("user.userId","in",o)],skipUserCheck:i}}))||[]}catch(u){return this.loggingService.catch(`Error in batch ${l+1}:`,u),[]}}));return yield Promise.all(s)}catch(n){return this.loggingService.catch("Error in getUsersFromDBWithBatching:",n),[]}})}getTemporaryUsersFromDBWithBatching(r){return A(this,arguments,function*({userIds:t,organizationId:e,resourceIds:i}){try{if(!t?.length||!i?.length)return[];let n=[];for(let d=0;d<t.length;d+=h.FIRESTORE_IN_QUERY_LIMIT)n.push(t.slice(d,d+h.FIRESTORE_IN_QUERY_LIMIT));let s=[];for(let d=0;d<i.length;d+=h.FIRESTORE_IN_QUERY_LIMIT)s.push(i.slice(d,d+h.FIRESTORE_IN_QUERY_LIMIT));let a=[],o=0,l=(d,m)=>A(this,null,function*(){try{return((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:e,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[bt(ge("userId","in",d),ge("veltResourceId","in",m))]}}))??[])||[]}catch(O){return this.loggingService.catch(`Error in batch ${o+1}:`,O),[]}});for(let d of n)for(let m of s)a.push(l(d,m)),o++;return(yield Promise.all(a)).flat().filter((d,m,O)=>m===O.findIndex(D=>D.userId===d.userId&&D.resourceId===d.resourceId))}catch(n){return this.loggingService.catch("Error in getTemporaryUsersFromDBWithBatching:",n),[]}})}getResolveOrganizationUsers$(){return this.resolveOrganizationUsers.asObservable()}getResolveFolderUsers$(){return this.resolveFolderUsers.asObservable()}getResolveDocumentUsers$(){return this.resolveDocumentUsers.asObservable()}getUserById$(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: getUserById$","color: green;"),Ve([this.userById$,this.customContactUserById$]).pipe(k(([t,e])=>this.applyContactOverlay(t,e)),q(X))}catch(t){return this.loggingService.catch("Error in UsersService getUserById$:",t),$({})}}applyContactOverlay(t,e){let i=S({},t??{});return Object.entries(e??{}).forEach(([r,n])=>{i[r]=S(S({},i[r]??{}),n)}),i}setUserByIds(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserByIds","color: green;"),this.mergeUsersIntoStore(t)}catch(e){this.loggingService.catch("Error in UsersService setUserByIds:",e)}}setContactListUsers(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setContactListUsers","color: green;");let e={};(t??[]).forEach(i=>{let r=i?.userId;r&&(e[r]=JSON.parse(JSON.stringify(i)))}),this.customContactUserById$.next(e)}catch(e){this.loggingService.catch("Error in UsersService setContactListUsers:",e)}}getContactListUser(t){try{return this.customContactUserById$.value?.[t]}catch(e){this.loggingService.catch("Error in UsersService getContactListUser:",e);return}}mergeUsersIntoStore(t){try{let e=JSON.parse(JSON.stringify(this.userById$.getValue()??{}));(t??[]).forEach(i=>{let r=i?.userId;r&&(e[r]=S(S({},e?.[r]??{}),i))}),this.userById$.next(e)}catch(e){this.loggingService.catch("Error in UsersService mergeUsersIntoStore:",e)}}setUserDataProvider(t){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setUserDataProvider","color: green;");let e=t.config?.getConfig?.url,i="get"in t&&typeof t.get=="function";if(!e&&!i){this.loggingService.catch("DataProviders.user is invalid. The get method is missing or is not a function (and no getConfig provided).");return}this.userDataProvider$.next(t),t.config?.resolveUsersConfig?.organization===!1?this.resolveOrganizationUsers.next(!1):this.resolveOrganizationUsers.next(!0),t.config?.resolveUsersConfig?.folder===!1?this.resolveFolderUsers.next(!1):this.resolveFolderUsers.next(!0),t.config?.resolveUsersConfig?.document===!1?this.resolveDocumentUsers.next(!1):this.resolveDocumentUsers.next(!0)}catch(e){this.loggingService.catch("Error in UsersService setUserDataProvider:",e)}}setAnonymousUserDataProvider(t){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setAnonymousUserDataProvider","color: green;"),!("resolveUserIdsByEmail"in t)||typeof t.resolveUserIdsByEmail!="function"){this.loggingService.catch("setAnonymousUserDataProvider is invalid. The resolveUserIdsByEmail method is missing or is not a function.");return}this.anonymousUserDataProvider$.next(t)}catch(e){this.loggingService.catch("Error in UsersService setAnonymousUserDataProvider:",e)}}resolveUserIdsByEmail(i){return A(this,arguments,function*({emails:t,uniqueId:e}){try{if(this.loggingService.log("%c[WB] Calling UsersService FUNCTION: resolveUserIdsByEmail","color: green;"),!t?.length)return{};let r=this.anonymousUserDataProvider$.getValue();if(!r||typeof r.resolveUserIdsByEmail!="function")return{};let n=[...new Set(t.filter(y=>!!y))];if(n.length===0)return{};let s={},a=[];if(n.forEach(y=>{let R=this.userIdByEmailCache[y];R?s[y]=R:a.push(y)}),a.length===0)return s;let o=this.docService.getOrganizationConfig()?.clientOrganizationId||"",l=this.docService.getDocumentPaths()?.clientDocumentId||"",u=this.docService.getDocumentPaths()?.folderId||"",g={organizationId:o,documentId:l,folderId:u,emails:a},f=e||b();this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.EMAIL_USER_ID_RESOLUTION_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:f,methodName:ce.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{emails:a,organizationId:o,documentId:l,folderId:u}});let d=r.config?.resolveTimeout||this.resolveTimeout,m,O=new Promise((y,R)=>{m=setTimeout(()=>{R(new Error("resolveUserIdsByEmail timeout"))},d)}),D=r.config?.getRetryConfig||{retryCount:0,retryDelay:0},U=A(this,null,function*(){try{let y=yield G(()=>r.resolveUserIdsByEmail(g),"resolveUserIdsByEmail",D);return y?.statusCode===200&&y?.data?y.data:(this.loggingService.catch(`Error in resolveUserIdsByEmail: provider returned statusCode ${y?.statusCode}. Message: ${y?.message||"Unknown error"}`),{})}finally{clearTimeout(m)}});try{let y=yield Promise.race([U,O]);return Object.entries(y).forEach(([R,p])=>{p&&(this.userIdByEmailCache[R]=p,s[R]=p,this.externalUserDataProviderAvailable()||this.docService.addUserInfoToOrganization({organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??"",user:{userId:p,name:R,email:R},currentUserId:this.authService.getUser()?.userId??""}).catch(C=>{this.loggingService.catch("Error in UsersService resolveUserIdsByEmail addUserInfoToOrganization:",C)}))}),this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.EMAIL_USER_ID_RESOLUTION_RESULT,timestamp:new Date().getTime(),uniqueId:f,methodName:ce.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{result:y,emails:a}}),s}catch(y){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail (timeout/race):",y),this.coreActionsService.triggerAction(E.USER_RESOLVER,{event:v.Events.Resolver.EMAIL_USER_ID_RESOLUTION_ERROR,timestamp:new Date().getTime(),uniqueId:f,methodName:ce.RESOLVE_USER_IDS_BY_EMAIL,source:"internal",payload:{error:y,emails:a}}),s}}catch(r){return this.loggingService.catch("Error in UsersService resolveUserIdsByEmail:",r),{}}})}userResolverConfigured(){try{return!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService userResolverConfigured:",t),!1}}externalUserDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: externalUserDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()&&!!this.userDataProvider$.getValue()}catch(t){return this.loggingService.catch("Error in UsersService externalUserDataProviderAvailable:",t),!1}}userDataProviderAvailable(){try{return this.loggingService.log("%c[WB] Calling UsersService FUNCTION: userDataProviderAvailable","color: green;"),!!this.commonDbService?.shouldUseFirestore()}catch(t){return this.loggingService.catch("Error in UsersService userDataProviderAvailable:",t),!1}}};c.\u0275fac=function(e){return new(e||c)(T(oe),T(Ae),T(H),T(qe),T(B))},c.\u0275prov=F({token:c,factory:c.\u0275fac,providedIn:"root"});let I=c;return I})();export{Ji as a,ln as b,dn as c,hn as d,un as e,gn as f,Ki as g,Lt as h,Zi as i,Xi as j,K as k,me as l,Ge as m,zt as n,Re as o,Pe as p,xt as q,Wt as r,Ht as s,ar as t,Gt as u,ur as v,Er as w,kr as x,us as y,qr as z,qe as A};