UNPKG

@veltdev/sdk

Version:

Velt is an SDK to add collaborative features to your product within minutes. Example: Comments like Figma, Frame.io, Google docs or sheets, Recording like Loom, Huddles like Slack and much more.

1 lines 124 kB
import{a as Qt}from"./chunk-LCAQRCEE.js";import{t as Jt}from"./chunk-BACKCNIG.js";import"./chunk-JFNRCHYR.js";import"./chunk-U4YN7DB7.js";import{a as Ht}from"./chunk-3HGEDPEP.js";import"./chunk-JDLRIKAZ.js";import{A as W,B as V,y as Vt}from"./chunk-3J52NZMN.js";import{a as Wt}from"./chunk-4ACOV475.js";import{b as re}from"./chunk-WTYACTR5.js";import{a as Kt}from"./chunk-6E3N35RF.js";import{a as zt}from"./chunk-KEM6PWSD.js";import{a as Mt}from"./chunk-UJRDSNTY.js";import{da as U,ea as tt,fa as te,ga as it}from"./chunk-KU45CEXD.js";import{$ as Ae,Ae as K,Cf as Ie,Dh as wt,E as k,Ed as Lt,Ee as ee,Ei as Bt,Fa as h,G as Be,Gc as B,Hi as jt,I as je,Ib as at,Ii as Gt,J as Te,Kb as Tt,L as ne,Lc as Dt,M as Et,Nb as X,Nf as lt,Of as Qe,Pa as E,Pb as Z,Pc as Ot,Q as ft,T as y,Ta as _t,Te as ze,Ua as q,Ue as xt,Va as It,W as Ge,Ya as $,Zf as Rt,_a as S,_b as He,a as f,aa as Ct,ag as pe,ai as kt,b as A,bc as x,be as Je,bi as Ye,ca as L,cc as j,ce as Se,cf as Ut,ch as Nt,ci as Xe,df as Ke,dh as Pt,di as c,ei as Ft,fc as G,g as Q,ha as le,i as mt,ia as de,jh as Ee,ji as Ze,k as ot,kc as J,l as Y,lb as v,lc as z,li as De,mb as R,mi as Oe,nb as N,ob as Ve,oe as ct,p as st,pc as At,qa as We,r as p,rh as ae,sb as b,t as ht,tb as _,ti as qt,u as St,ua as bt,ub as yt,v as D,vb as ge,vh as m,w as pt,wa as F,xb as ue,yi as $t,z as Le,zb as g,zi as et}from"./chunk-GR3NESUB.js";var nt=(()=>{let r=class r{constructor(e,t){this.analyticsService=e,this.loggingService=t,this.actionSubjects=new Map,this.subscriptions=[]}onAccessRequested(e){try{this.triggerAction(Se.ACCESS_REQUESTED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_ACCESS_REQUESTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequested: ",t)}}onAccessRequestCanceled(e){try{this.triggerAction(Se.ACCESS_REQUEST_CANCELED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_ACCESS_REQUEST_CANCELED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequestCanceled: ",t)}}onAccessAccepted(e){try{this.triggerAction(Se.ACCESS_ACCEPTED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_ACCESS_ACCEPTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessAccepted: ",t)}}onAccessRejected(e){try{this.triggerAction(Se.ACCESS_REJECTED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_ACCESS_REJECTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRejected: ",t)}}onEditorAssigned(e){try{this.triggerAction(Se.EDITOR_ASSIGNED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_EDITOR_ASSIGNED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorAssigned: ",t)}}onEditorOnDifferentTabDetected(e){try{this.triggerAction(Se.EDITOR_ON_DIFFERENT_TAB_DETECTED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_EDITOR_ON_DIFFERENT_TAB_DETECTED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorOnDifferentTabDetected: ",t)}}onViewerAssigned(e){try{this.triggerAction(Se.VIEWER_ASSIGNED,e),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_VIEWER_ASSIGNED,{viewerUserId:e?.viewer?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onViewerAssigned: ",t)}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new ot),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in LiveStateActionsService triggerAction: ",i)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new ot),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in LiveStateActionsService onAction: ",t),p(null)}}};r.\u0275fac=function(t){return new(t||r)(L(Xe),L(c))},r.\u0275prov=Ae({token:r,factory:r.\u0275fac,providedIn:"root"});let n=r;return n})();var Zt=(()=>{let r=class r{constructor(e,t,i,s,l){this.authService=e,this.coreActionsService=t,this.domService=i,this.loggingService=s,this.usersService=l}findOldestActiveSessionFromHeartbeats(e){try{if(!e||e.length===0)return null;let t=this.authService.getUser(),i=this.domService.getTabId(),s=e.filter(d=>d.lastUpdatedTimestamp>Date.now()-1e4);return s.length===0?null:[...s].sort((d,a)=>d.createdTimestamp-a.createdTimestamp)[0]??null}catch(t){return this.loggingService.catch("Error in findOldestActiveSessionFromHeartbeats: ",t),null}}determineEditorStatus(e){return Q(this,null,function*(){try{let{singleEditorModeData:t,heartbeatData:i,externalUserPresence:s,currentUser:l,currentTabId:u}=e,d=JSON.parse(JSON.stringify(t||{})),a={steps:[],timestamp:Date.now()},C=()=>Q(this,null,function*(){let ie=s?.userIds?.[0],se;if(ie){let ke=Qe(),Fe=xt.GET_SINGLE_EDITOR_USERS;this.coreActionsService.triggerAction(Je.USER_RESOLVER,{event:m.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:ke,moduleName:Fe,methodName:ze.SET_SINGLE_EDITOR_MODE_LIVE_STATE_DATA_FOR_DIFFERENT_USER_PRESENT_ON_TAB,source:"internal",payload:{userIds:[ie],forceResolve:!0}}),yield this.usersService.resolveUsers({userIds:[ie],forceResolve:!0,uniqueId:ke,moduleName:Fe}),se=this.usersService.getUserById(ie)}se?(d.editor=se,d.tabId=`differentUserPresentOnTab_${u}`):(d.editor={userId:`anonymous_${l?.userId}`,name:"Anonymous"},d.tabId=`differentUserPresentOnTab_${u}`)}),P=()=>{d.editor=l,d.tabId=`sameUserPresentOnTab_${u}`},O=!1;if(t?.editor){if(a.steps?.push("SingleEditorModeData: Editor is available."),i?.length){a.steps?.push("Heartbeat data is available.");let ie=i?.find(se=>se.userId===t?.editor?.userId&&se.tabId===t?.tabId);if(ie&&ie.lastUpdatedTimestamp>Date.now()-1e4)a.steps?.push("Editor user heartbeat is recent.");else{a.steps?.push("Editor user heartbeat is not available or not recent.");let se=this.findOldestActiveSessionFromHeartbeats(i);se&&se.userId===l.userId&&se.tabId===u?(a.steps?.push("Current user is the oldest active session."),O=!0):a.steps?.push("Current user is not the oldest active session.")}}!i?.length&&!s&&a.steps?.push("No heartbeat data and no external user presence is available.")}else{if(a.steps?.push("SingleEditorModeData: Editor not available."),i?.length){a.steps?.push("Heartbeat data is available.");let ie=this.findOldestActiveSessionFromHeartbeats(i);ie&&ie.userId===l.userId&&ie.tabId===u?(a.steps?.push("Current user is the oldest active session."),O=!0):a.steps?.push("Current user is not the oldest active session.")}else s&&(a.steps?.push("External user presence is available."),s.differentUserPresentOnTab?(a.steps?.push("External user presence: Different user is present on the tab."),yield C(),O=!1):s.sameUserPresentOnTab?(a.steps?.push("External user presence: Same user is present on the tab."),P(),O=!1):(a.steps?.push("External user presence: No user is present on the tab."),O=!0));!i?.length&&!s&&(a.steps?.push("No heartbeat data and no external user presence is available."),O=!0)}let w;return O?w={shouldSetUndefined:!0}:w={data:d},a.singleEditorModeData=t,a.singleEditorModeDataEditorAvailable=!!t?.editor,a.heartbeatData=i,a.externalUserPresence=s,a.currentUser=l,a.currentTabId=u,a.returnValue=w,a.shouldSetUndefined=O,a.steps?.push("Execution completed."),a=this.cleanStats(a),A(f({},w),{stats:a})}catch(t){return this.loggingService.catch("Error in determineEditorStatus: ",t),{data:e?.singleEditorModeData??void 0}}})}cleanStats(e){try{let t=e&&typeof e=="object"?JSON.parse(JSON.stringify(e)):e;return t?.singleEditorModeData?.editor&&(t.singleEditorModeData=A(f({},t.singleEditorModeData),{editor:{userId:t.singleEditorModeData?.editor?.userId}})),t?.returnValue?.data?.editor&&(t.returnValue.data=A(f({},t.returnValue.data),{editor:{userId:t.returnValue.data?.editor?.userId}})),t}catch{return e}}};r.\u0275fac=function(t){return new(t||r)(L(Oe),L(Ze),L(De),L(c),L(et))},r.\u0275prov=Ae({token:r,factory:r.\u0275fac,providedIn:"root"});let n=r;return n})();var T=(()=>{let r=class r{constructor(e,t,i,s,l,u,d,a,C,P,O,w,ie,se,ke,Fe,ui,vi){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=s,this.coreActionsService=l,this.databaseService=u,this.docService=d,this.domService=a,this.heartbeatService=C,this.iamService=P,this.loggingService=O,this.commonDbService=w,this.liveStateActionsService=ie,this.liveStateUtilsService=se,this.usersService=ke,this.singleEditorDecisionEngine=Fe,this.serviceBook=ui,this.realtimeAdapter=vi,this.db=null,this.liveStateAutoSyncStateData$=new Y(null),this.liveStateDataMapDraft={},this.singleEditorMode$=new Y(!1),this.singleEditorModeConfig$=new Y(null),this.singleEditorLiveStateData$=new Y(null),this.singleEditorLiveStateData={},this.editorAccessTimeout$=new Y(ee.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME),this.editorAccessTransferOnTimeOut$=new Y(!0),this.defaultSingleEditorUIEnabled$=new Y(!0),this.editorAccessTimer$=new Y(new Ke),this.autoSyncState$=new Y(!1),this.serverConnectionState$=new Y(K.PENDING_INIT),this.externalUserPresence$=new Y(null),this.heartbeat$=new Y(!0),this.user=null,this.keydownSubscription=null,this.isEditor$=new Y(null),this.preventEventsOnElementMap={},this.PREVENT_EVENTS=["click","mouseup","mousedown"],this.autoSyncStateHistory=null,this.singleEditorModeContainerIds$=new Y([]),this.inputChangeSubscriptionMap={},this.childListMutationSubscription=null,this.tabId=this.domService.getTabId(),this.heartbeatRestart$=new Y(void 0),this.connectionListenerUnsubscribe=null,this.offlineTimer=null;try{this.loggingService.log("%c[WB] Creating CLASS: LiveStateService","color: blue;"),pt([this.getSingleEditorMode$(),this.heartbeat$]).subscribe(([I,M])=>{I&&M?this.heartbeatService.enableHeartbeat():this.heartbeatService.disableHeartbeat()}),this.databaseService.getDb().pipe(k(I=>!!I),Te(1)).subscribe(I=>{I&&(this.db=I,this.getUser(),this.getDocumentPaths(),this.subscribeLiveStateData().subscribe(),this.subscribeAutoSyncState().subscribe(),this.singleEditorMode$.subscribe(M=>{M&&this.detectKeydownOnInput()}),this.autoSyncState$.subscribe(M=>{M?(this.detectLiveSyncInputs(),this.observeElementAddedOnDom()):(this.unsubscribeInputChanges(),this.childListMutationSubscription?.unsubscribe(),this.childListMutationSubscription=null)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},M=>{this.loggingService.catch("Error in LiveStateService constructor updateOnDatabaseDisconnect: ",M)}),this.updateServerStateOnDatabaseDisconnect().subscribe(()=>{},M=>{this.loggingService.catch("Error in LiveStateService constructor updateServerStateOnDatabaseDisconnect: ",M)}))},I=>{this.loggingService.catch("Error in LiveStateService getDb subscription: ",I)}),this.liveStateAutoSyncStateData$.pipe(k(I=>Object.keys(I||{}).length>0),ne((I,M)=>JSON.stringify(I||{})===JSON.stringify(M||{}))).subscribe(I=>{I&&(this.getAutoSyncState()&&(!this.autoSyncStateHistory&&I?.history&&this.updateLiveStateSyncInputDataLocally(I.history),I?.current&&this.updateLiveStateSyncInputDataLocally({[I.current.liveStateDataId]:I.current})),!this.autoSyncStateHistory&&I?.history&&(this.autoSyncStateHistory=I.history))}),this.docService.addPreDocumentIdChangeFunction("live-state-service",I=>(this.updateExternalUserPresence(null),this.isUserEditor()?.isEditor&&(!this.getSingleEditorModeConfig()?.singleTabEditor||this.isUserEditor()?.isEditorOnCurrentTab)?this.removeEditorAccess({metadata:{from:"addPreDocumentIdChangeFunction-liveStateService",reason:"Document id changed"},documentPaths:I}):Promise.resolve())),this.authService.addPreSignOutFuction("live-state-signout",this.signOutUser.bind(this)),this.singleEditorLiveStateData$.pipe(Et()).subscribe(([I,M])=>{try{let ve=M?.requestEditorAccess?.status,be=I?.requestEditorAccess?.status,qe=this.authService.getUser(),$e=this.getPresenceData();if(ve==="pending"){if(qe?.userId===M?.editor?.userId){let _e=f({viewer:ae(M?.requestEditorAccess?.user)??void 0,editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),status:"requested"},$e);this.liveStateActionsService?.onAccessRequested(_e)}return}if(ve==="cancelled"){if(qe?.userId===M?.editor?.userId){let _e=f({viewer:ae(M?.requestEditorAccess?.user)??void 0,editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),status:"canceled"},$e);this.liveStateActionsService?.onAccessRequestCanceled(_e)}return}if(be==="pending"&&!ve){if(I?.requestEditorAccess?.user?.userId===M?.editor?.userId){if(I?.requestEditorAccess?.user?.userId===qe?.userId){let _e=f({viewer:ae(I?.editor)??void 0,editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),status:"accepted"},$e);this.liveStateActionsService?.onAccessAccepted(_e)}return}if(I?.requestEditorAccess?.user?.userId!==M?.editor?.userId){if(I?.requestEditorAccess?.user?.userId===qe?.userId){let _e=f({viewer:ae(I?.requestEditorAccess?.user)??void 0,editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),status:"rejected"},$e);this.liveStateActionsService?.onAccessRejected(_e)}return}}}catch(ve){this.loggingService.catch("Error in LiveStateService singleEditorLiveStateData$ subscription: ",ve)}}),this.isUserEditor$().pipe(ne(Ee)).subscribe(I=>{try{if(I){this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_USER_EDITOR_STATS,{isEditor:I?.isEditor,isEditorOnCurrentTab:I?.isEditorOnCurrentTab});let M=this.singleEditorLiveStateData$.value,ve=this.getPresenceData();if(I?.isEditor)if(I?.isEditorOnCurrentTab){let be=f({editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),role:"editor"},ve);this.liveStateActionsService?.onEditorAssigned(be)}else{let be=f({editor:ae(M?.editor)??void 0,timestamp:new Date().getTime(),role:"editorOnDifferentTab"},ve);this.liveStateActionsService?.onEditorOnDifferentTabDetected(be)}else{let be=f({viewer:ae(this.authService.getUser())??void 0,timestamp:new Date().getTime(),role:"viewer"},ve);this.liveStateActionsService?.onViewerAssigned(be)}}}catch(M){this.loggingService.catch("Error in LiveStateService isUserEditor$ subscription: ",M)}})}catch(I){this.loggingService.catch("Error in LiveStateService constructor: ",I)}}getPresenceData(){try{let t=this.serviceBook.get(wt)?.getPresenceUsers();return{totalUsers:t?.length,presenceSnippylyUserIds:t?.map(i=>i.userSnippylyId).filter(i=>!!i),presenceClientUserIds:t?.map(i=>i.userId)}}catch(e){return this.loggingService.catch("Error in LiveStateService getPresenceData: ",e),{}}}observeElementAddedOnDom(){try{this.loggingService.log("%c[WB] Calling FUNCTION: observeElementAddedOnDom","color: green;"),this.childListMutationSubscription&&(this.childListMutationSubscription.unsubscribe(),this.childListMutationSubscription=null),this.childListMutationSubscription=this.domService.getChildListMutation$().subscribe(e=>{e?.length&&e.forEach(t=>{let i=Array.from(t.addedNodes||[]).filter(s=>s instanceof HTMLElement);i?.forEach(s=>{Nt(s,!0)?.forEach(d=>{typeof d?.getAttribute=="function"&&d?.getAttribute(ee.ATTRIBUTES.VELT_SYNC_STATE)&&this.subscribeInputChanges(d)})}),i?.length&&this.isEditor$?.value?.isEditor===!1&&(this.disableInputElements(),this.disableElementEvents())})},e=>{this.loggingService.catch("Error in LiveStateService domService getChildListMutation$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService observeElementAddedOnDom: ",e)}}detectKeydownOnInput(){try{this.loggingService.log("%c[WB] Calling FUNCTION: detectKeydownOnInput","color: green;"),this.unsubscribeKeydownSubscription(),this.keydownSubscription=this.domService.onWindowKeydown$().pipe(k(e=>e?.target instanceof HTMLInputElement||e?.target instanceof HTMLTextAreaElement||e?.target instanceof HTMLSelectElement),k(e=>!!this.isElementInsideSingleEditorModeContainerElements(e?.target)),Te(1)).subscribe(e=>{this.unsubscribeKeydownSubscription(),this.getSingleEditorModeConfig()?.customMode||this.setUserAsEditor({skipEditorCheck:!0})},e=>{this.loggingService.catch("Error in LiveStateService detectKeydownOnInput subscription: ",e)})}catch(e){this.loggingService.catch("Error in LiveStateService detectKeydownOnInput: ",e)}}unsubscribeKeydownSubscription(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeKeydownSubscription","color: green;"),this.keydownSubscription&&(this.keydownSubscription.unsubscribe(),this.keydownSubscription=null)}catch(e){this.loggingService.catch("Error in LiveStateService unsubscribeKeydownSubscription: ",e)}}getDocumentPaths(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().subscribe(e=>{this.documentPaths=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getDocumentPaths: ",e)}}getUser(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().subscribe(e=>{this.user=e,this.updateLiveStateDataFromDraft()})}catch(e){this.loggingService.catch("Error in LiveStateService getUser: ",e)}}updateLiveStateDataFromDraft(){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateLiveStateDataFromDraft","color: green;"),this.liveStateDataMapDraft?.custom&&this.user&&this.documentPaths&&(Object.keys(this.liveStateDataMapDraft.custom).forEach(e=>{this.setLiveStateData(e,this.liveStateDataMapDraft.custom[e])}),this.liveStateDataMapDraft={})}catch(e){this.loggingService.catch("Error in LiveStateService updateLiveStateDataFromDraft: ",e)}}getActiveHeartbeatStream$(e){return this.heartbeatRestart$.pipe(Te(50),y(()=>{let t=this.heartbeatService.getHeartbeatData({documentId:this.documentPaths?.documentId}).pipe(Te(1),y(i=>{let s=this.singleEditorDecisionEngine.findOldestActiveSessionFromHeartbeats(i);return s?this.monitorSession$(s.userId,s.tabId):p(null)}));return!e?.userId||!e?.tabId?t:this.heartbeatService.getSpecificHeartbeat({userId:e.userId,tabId:e.tabId,documentId:this.documentPaths?.documentId}).pipe(Te(1),y(i=>!i?.id||Date.now()-i?.lastUpdatedTimestamp>1e4?t:this.monitorSession$(e.userId,e.tabId)))}),ne((t,i)=>this.isHeartbeatSimilar(t,i)))}monitorSession$(e,t){return this.heartbeatService.getSpecificHeartbeat({userId:e,tabId:t,documentId:this.documentPaths?.documentId}).pipe(y(s=>s?.id?p(s):(this.heartbeatRestart$.next(),st)),St({each:1e4,with:()=>(this.heartbeatRestart$.next(),st)}))}isHeartbeatSimilar(e,t){try{return!e&&!t?!0:!e||!t?!1:e?.userId===t?.userId&&e?.tabId===t?.tabId}catch{return!1}}subscribeLiveStateData(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),this.authService.getAuthState$().pipe(k(e=>!!e),y(e=>this.isFeatureAllowed({firebaseUser:e,liveStateData:{}})),y(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(D(t=>(e.featureAllowed=t,e))):p(e)),y(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(D(t=>(e.featureAllowed=!t,e))):p(e)),y(e=>e.featureAllowed?p(e).pipe(y(t=>this.docService.getDocumentPaths$().pipe(D(i=>(this.documentPaths=i,t.documentPaths=i,t)))),y(t=>t?.documentPaths?p(t).pipe(Ge(i=>{this.serverConnectionState$?.value===K.PENDING_INIT&&i?.documentPaths?.liveState&&this.serverConnectionState$.next(K.PENDING_DATA)}),y(i=>this.domService.onNetworkStatusChange$().pipe(k(s=>s),D(()=>i))),y(i=>this.getDataFromDocumentId().pipe(D(s=>(i.singleEditorModeData=s,f({},i))))),y(i=>this.getSingleEditorMode$().pipe(D(()=>i))),D(i=>([K.ONLINE,K.OFFLINE].includes(this.serverConnectionState$?.value)||this.serverConnectionState$.next(K.ONLINE),i)),y(i=>this.getSingleEditorMode()?this.getExternalUserPresence$().pipe(D(s=>A(f({},i),{externalUserPresence:s}))):p(i))):p(A(f({},t),{liveStateData:{}}))),y(t=>this.getSingleEditorMode()?this.heartbeatService.getHeartbeatEnabled$().pipe(y(i=>{if(i){let s=t?.singleEditorModeData?.editor,l=t?.singleEditorModeData?.tabId;return this.getActiveHeartbeatStream$({userId:s?.userId,tabId:l}).pipe(D(u=>{let d=u?.id?[u]:null;return A(f({},t),{heartbeatData:d})}))}else return p(A(f({},t),{heartbeatData:null}))})):p(t)),y(t=>{if(this.getSingleEditorMode()){let i=[];if(!(Object.keys(t?.singleEditorModeData||{}).length>0)){let l=this.singleEditorLiveStateData$.value&&typeof this.singleEditorLiveStateData$.value=="object"?JSON.parse(JSON.stringify(this.singleEditorLiveStateData$.value)):this.singleEditorLiveStateData$.value;i.push({eventName:m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_EMPTY_DATA_STATS,properties:{previousSingleEditorModeData:l,currentSingleEditorModeData:t?.singleEditorModeData}})}return this.updateSingleEditorLiveSyncData(t?.singleEditorModeData||{},t?.externalUserPresence??null,t?.heartbeatData??null,t,i),p(t)}else return p(t)})):p({})))}updateSingleEditorLiveSyncData(e,t,i,s,l){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateSingleEditorLiveSyncData","color: green;"),pe(e,{})&&!this.keydownSubscription&&this.detectKeydownOnInput();let u=JSON.parse(JSON.stringify(e)),d=yield this.singleEditorDecisionEngine.determineEditorStatus({singleEditorModeData:u,externalUserPresence:t,heartbeatData:i,currentUser:this.authService.getUser(),currentTabId:this.tabId});d?.stats&&l?.push({eventName:m.Events.LiveStateSync.SEM_SINGLE_EDITOR_DETERMINE_EDITOR_STATUS,properties:{stats:d?.stats}});let a;if(this.domService.getNetworkStatus()||(a=null),e=d?.data??{},d?.shouldSetUndefined||(a=null),(s?s?.documentPaths:this.docService.getDocumentPaths())||(a=null),e&&!e?.editor&&this.isEditor$?.value!==a&&this.isEditor$.next(a),pe(this.singleEditorLiveStateData,e))return;{t&&this.compareServerAndExternalData(u,t),l&&l?.length>0&&l.forEach(O=>{O?.eventName&&this.analyticsService.trackEvent(O.eventName,O.properties)}),this.singleEditorLiveStateData=e,this.singleEditorLiveStateData$.next(e);let P;if(this.singleEditorLiveStateData&&typeof this.singleEditorLiveStateData=="object"&&(P=this.liveStateUtilsService.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(this.singleEditorLiveStateData)))),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_STATS,{singleEditorLiveStateData:P}),this.singleEditorLiveStateData?.editor){let O=this.authService.getUser();this.singleEditorLiveStateData?.editor?.userId!==O?.userId?this.makeReader():this.makeEditor()}else this.isEditor$?.value!==a&&this.isEditor$.next(a),this.enableInputElements(),this.enableElementEvents();this.editorAccessTimerInterval&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"&&this.clearEditorAccessTimerInterval(),this.requestAccessTimer&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"?this.clearRequestAccessTimer():this.singleEditorLiveStateData?.requestEditorAccess?.status==="pending"&&this.isUserEditor()?.isEditor&&this.isUserEditor()?.isEditorOnCurrentTab&&this.setRequestAccessTimer(this.singleEditorLiveStateData?.requestEditorAccess?.editorAccessTimeout||ee.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME)}}catch{}})}updateSingleEditorLiveSyncDataOld(s,l){return Q(this,arguments,function*(e,t,i=[]){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: updateSingleEditorLiveSyncData","color: green;"),pe(e,{})){let a=yield this.fetchSingleEditorLiveStateDataFromDatabase();if(!pe(a,e)&&(i.push({eventName:m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_MISMATCH,properties:{serverData:a,localData:e}}),a&&typeof a=="object")){let C=yield this.liveStateUtilsService.resolveAndMergeSingleEditorLiveStateDataWithUser(JSON.parse(JSON.stringify(a)));e=JSON.parse(JSON.stringify(C))}}pe(e,{})&&!this.keydownSubscription&&this.detectKeydownOnInput();let u=e&&typeof e=="object"?JSON.parse(JSON.stringify(e)):e;if(t&&(e&&typeof e=="object"&&(e=JSON.parse(JSON.stringify(e))),!e?.editor)){let a=this.authService.getUser();if(t?.sameUserPresentOnTab)e.editor=a,e.tabId=`sameUserPresentOnTab_${this.tabId}`;else if(t?.differentUserPresentOnTab){let C=t?.userIds?.[0],P;if(C){let O=Qe();this.coreActionsService.triggerAction(Je.USER_RESOLVER,{event:m.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:O,methodName:ze.GET_SINGLE_EDITOR_MODE_DATA,source:"internal",payload:{userIds:[C],forceResolve:!0}}),yield this.usersService.resolveUsers({userIds:[C],forceResolve:!0,uniqueId:O}),P=this.usersService.getUserById(C)}P?(e.editor=P,e.tabId=`differentUserPresentOnTab_${this.tabId}`):(e.editor={userId:`anonymous_${a?.userId}`,name:"Anonymous"},e.tabId=`differentUserPresentOnTab_${this.tabId}`)}}let d;if(this.domService.getNetworkStatus()||(d=null),e&&!e?.editor&&this.isEditor$?.value!==d&&!t?.sameUserPresentOnTab&&!t?.differentUserPresentOnTab&&this.isEditor$.next(d),pe(this.singleEditorLiveStateData,e))return;{t&&this.compareServerAndExternalData(u,t),i?.length>0&&i.forEach(C=>{C?.eventName&&this.analyticsService.trackEvent(C.eventName,C.properties)}),this.singleEditorLiveStateData=e,this.singleEditorLiveStateData$.next(e);let a;if(this.singleEditorLiveStateData&&typeof this.singleEditorLiveStateData=="object"&&(a=this.liveStateUtilsService.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(this.singleEditorLiveStateData)))),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_STATS,{singleEditorLiveStateData:a}),this.singleEditorLiveStateData?.editor){let C=this.authService.getUser();this.singleEditorLiveStateData?.editor?.userId!==C?.userId?this.makeReader():this.makeEditor()}else this.isEditor$?.value!==d&&this.isEditor$.next(d),this.enableInputElements(),this.enableElementEvents();this.editorAccessTimerInterval&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"&&this.clearEditorAccessTimerInterval(),this.requestAccessTimer&&this.singleEditorLiveStateData?.requestEditorAccess?.status!=="pending"?this.clearRequestAccessTimer():this.singleEditorLiveStateData?.requestEditorAccess?.status==="pending"&&this.isUserEditor()?.isEditor&&this.isUserEditor()?.isEditorOnCurrentTab&&this.setRequestAccessTimer(this.singleEditorLiveStateData?.requestEditorAccess?.editorAccessTimeout||ee.LIVE_STATE_REQUEST_EDITOR_ACCESS_WAIT_TIME)}}catch{}})}compareServerAndExternalData(e,t){try{if(t){let i=this.authService.getUser(),s={isEditor:e?.editor?.userId===i?.userId,isEditorOnCurrentTab:e?.editor?.userId===i?.userId&&e?.tabId===this.tabId},l={isEditor:t?.sameUserPresentOnTab&&!t?.differentUserPresentOnTab,isEditorOnCurrentTab:!1};pe(s,l)||this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_SINGLE_EDITOR_DATA_MISMATCH_WITH_EXTERNAL,{serverUserEditorAccess:s,externalUserEditorAccess:l,serverData:e,externalData:t})}}catch(i){this.loggingService.catch("Error in LiveStateService compareServerAndExternalData: ",i)}}isFeatureAllowed(e){return this.configService.getConfig$().pipe(k(t=>!!t),D(t=>A(f({},e),{config:t})),y(t=>this.authService.getUser$().pipe(D(i=>A(f({},t),{user:i})))),y(t=>lt(t.config,t.user,ct.LIVE_STATE_SYNC)?p(A(f({},t),{featureAllowed:!0})):(this.loggingService.warn("Live state sync feature is not allowed."),p(A(f({},t),{featureAllowed:!1})))),ne((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(k(t=>!!t),y(t=>(this.db=t,this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:"liveStateSingleEditorMode",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(k(i=>!!i?.data),D(i=>i?.data&&typeof i?.data=="object"?JSON.parse(JSON.stringify(i?.data)):i?.data),Be(i=>(this.loggingService.catch("Error in LiveStateService getDataFromDocumentId: ",i),p({})))):p({}))),ne(Ee))}getLiveStateData$(e,t){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveStateData$","color: green;"),this.authService.getAuthState$().pipe(k(i=>!!i),y(i=>this.isFeatureAllowed({firebaseUser:i,liveStateData:{}})),y(i=>i.featureAllowed?this.iamService.isUserAllowed$().pipe(D(s=>(i.featureAllowed=s,i))):p(i)),y(i=>i.featureAllowed?this.authService.isPlanExpired$().pipe(D(s=>(i.featureAllowed=!s,i))):p(i)),y(i=>i.featureAllowed?p(i).pipe(y(s=>this.docService.getDocumentPaths$().pipe(D(l=>(this.documentPaths=l,s.documentPaths=l,s)))),y(s=>{let l=t?.listenToNewChangesOnly?1:0;return this.getLiveStateDataFromDatabase$(e).pipe(ne(Ee),ft(l))}),D(s=>{if(s)if(e){let l=Ie(e+""),u=s?.[l];if(u){let d=u?.data;if(u?.tabId&&this.tabId&&u?.tabId===this.tabId)return;if(u?.isDataStringified&&typeof d=="string")try{d=JSON.parse(d)}catch{}return d}else return}else{let l={};return Object.keys(s||{}).forEach(u=>{if(s[u]?.liveStateDataId){let d=s[u],a=d?.data;if(d?.isDataStringified&&typeof a=="string")try{a=JSON.parse(a)}catch{}l[d.liveStateDataId]=a}}),l}return s})):p(void 0).pipe(k(Boolean))),ne((i,s)=>JSON.stringify(i||{})===JSON.stringify(s||{})),k(i=>i!==void 0),D(i=>i))}catch(i){return this.loggingService.catch("Error in LiveStateService getLiveStateData$: ",i),p(null)}}getLiveStateDataFromDatabase$(e){try{return this.databaseService.getDb().pipe(k(t=>!!t),y(t=>{this.db=t;let i=e?Ie(e+""):void 0;return this.configService?.getApiKey()&&this.documentPaths?.liveState?this.commonDbService.dbListener({feature:i?"liveStateCustom":"allLiveStateCustoms",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:i,skipFirestore:!0}}).pipe(k(s=>!!s?.data),D(s=>s?.data),D(s=>{if(s)return i?{[i]:s}:s}),Be(s=>(this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",s),p(null)))):p(void 0)}))}catch(t){return this.loggingService.catch("Error in LiveStateService getLiveStateDataFromDatabase$: ",t),p(void 0)}}fetchLiveStateData(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: fetchLiveStateData","color: green;");let t=this.databaseService.getDbValue(),i=this.authService.getUser(),s=this.docService.getDocumentPaths(),l=e?.liveStateDataId&&typeof e?.liveStateDataId=="string"?Ie(e.liveStateDataId):void 0,u=lt(this.configService.getConfig(),i,ct.LIVE_STATE_SYNC);if(this.authService.isPlanExpired()&&(u=!1),t&&i&&s?.liveState&&u){let a=yield this.commonDbService.getData({feature:l?"liveStateCustom":"allLiveStateCustoms",properties:{documentId:s?.documentId,organizationId:s?.organizationId,id:l,skipFirestore:!0}}).then(C=>C?l?{[l]:C}:C:null);if(a)if(l){let C=a?.[l];if(C){let P=C?.data;if(C?.isDataStringified&&typeof P=="string")try{P=JSON.parse(P)}catch{}return P}else return null}else{let C={};return Object.keys(a||{}).forEach(P=>{if(a[P]?.liveStateDataId){let O=a[P],w=O?.data;if(O?.isDataStringified&&typeof w=="string")try{w=JSON.parse(w)}catch{}C[O.liveStateDataId]=w}}),C}}return null}catch(t){return this.loggingService.catch("Error in LiveStateService fetchLiveStateData: ",t),null}})}setLiveStateData(e,t,i){return Q(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setLiveStateData","color: green;");try{let s=this.authService.getUser();if(e&&this.documentPaths?.liveState&&s){let l=Ie(e+""),u=!1;try{if(i?.merge&&typeof t=="object"){let a=yield this.commonDbService.getData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:l,skipFirestore:!0}});if(a?.isDataStringified){let C=JSON.parse(a?.data);typeof t=="object"&&(t=f(f({},C),t))}}}catch{}try{typeof t=="object"&&(t=JSON.stringify(t),u=!0)}catch{}let d={id:l,lastUpdated:this.timestamp,liveStateDataId:e,data:t,updatedBy:s,tabId:this.tabId,isDataStringified:u};yield this.commonDbService.setData({feature:"liveStateCustom",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:l,skipFirestore:!0},data:JSON.parse(JSON.stringify(d))})}else this.loggingService.warn("liveStateDataId or documentPaths or user is null"),this.liveStateDataMapDraft?.custom||(this.liveStateDataMapDraft.custom={}),e&&(this.liveStateDataMapDraft.custom[e]=t)}catch(s){this.loggingService.catch("Error in LiveStateService _setLiveStateData: ",s)}})}getFormElements(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getInputElements","color: green;"),document.querySelectorAll("input, textarea, select, button, [contenteditable]")}catch(e){return this.loggingService.catch("Error in LiveStateService getInputElements: ",e),null}}disableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableInputElements","color: green;"),this.getFormElements()?.forEach(t=>{if(this.isElementInsideSingleEditorModeContainerElements(t)&&!this.isSingleEditorModeDisabledForElement(t)&&!Rt(t)){let i=t?.hasAttribute("disabled");t?.hasAttribute("contenteditable")&&(i=t?.getAttribute("contenteditable")==="false"),i||(t.setAttribute("disabled","true"),t.setAttribute(ee.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO,"true"),t?.hasAttribute("contenteditable")&&t.setAttribute("contenteditable","false"))}})}catch(e){this.loggingService.catch("Error in LiveStateService disableInputElements: ",e)}}enableInputElements(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableInputElements","color: green;"),this.getFormElements()?.forEach(t=>{t?.hasAttribute(ee.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO)&&(t.removeAttribute("disabled"),t.removeAttribute(ee.ATTRIBUTES.VELT_SYNC_ACCESS_AUTO),t?.getAttribute("contenteditable")&&t.setAttribute("contenteditable","true"))})}catch(e){this.loggingService.catch("Error in LiveStateService enableInputElements: ",e)}}disableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableElementEvents","color: green;"),document.querySelectorAll(`[${ee.ATTRIBUTES.VELT_SYNC_ACCESS}]`)?.forEach(t=>{let i=this.domService.getXPath(t);i&&!this.preventEventsOnElementMap[i]&&(this.preventEventsOnElementMap[i]={element:t,events:{}},this.PREVENT_EVENTS.forEach(s=>{let l=Le(t,s,{capture:!0}).subscribe(u=>{try{u.preventDefault(),u.stopPropagation()}catch(d){this.loggingService.catch("Error in LiveStateService disableElementEvents subscription: ",d)}});this.preventEventsOnElementMap[i]?.events[s]?.unsubscribe(),this.preventEventsOnElementMap[i].events[s]=l}))})}catch(e){this.loggingService.catch("Error in LiveStateService disableElementClicks: ",e)}}enableElementEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableElementEvents","color: green;"),Object.keys(this.preventEventsOnElementMap).forEach(e=>{let t=this.preventEventsOnElementMap[e];Object.keys(t.events||{}).forEach(i=>{t?.events[i]?.unsubscribe()})}),this.preventEventsOnElementMap={}}catch(e){this.loggingService.catch("Error in LiveStateService enableElementClicks: ",e)}}setUserAsEditor(e){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUserAsEditor","color: green;"),this.user&&this.documentPaths?.liveStateSingleEditorMode){if(this.analyticsService.trackEvent(m.Events.LiveStateSync.SET_USER_AS_EDITOR_TRIGGERED,{editorUserId:this.user?.userSnippylyId,tabId:this.tabId}),!e?.skipEditorCheck){let i=yield this.fetchSingleEditorLiveStateDataFromDatabase();if(i?.editor?.userId&&i?.tabId){let s=yield ht(this.heartbeatService.getSpecificHeartbeat({userId:i?.editor?.userId,tabId:i?.tabId,documentId:this.documentPaths?.documentId})),l=null;s&&(l=this.singleEditorDecisionEngine.findOldestActiveSessionFromHeartbeats([s])),l||(i=null)}else i=null;if(i?.editor){let s=this.authService.getUser(),l=null;s?.userId===i?.editor?.userId?i?.tabId===this.tabId?l={code:"same_user_editor_current_tab",message:"Same user is already editor in current tab.",source:"setUserAsEditor"}:l={code:"same_user_editor_different_tab",message:"Same user is already editor in different tab.",source:"setUserAsEditor"}:l={code:"another_user_editor",message:"Another user is already editor.",source:"setUserAsEditor"};let u;return i&&typeof i=="object"&&(u=this.liveStateUtilsService.formatLiveStateSingleEditorModeData(JSON.parse(JSON.stringify(i)))),this.analyticsService.trackEvent(m.Events.LiveStateSync.SET_USER_AS_EDITOR_ERROR,{error:l,singleEditorLiveStateData:u}),{error:l}}}let t={editor:this.user,tabId:this.tabId,editorAt:this.timestamp};this.commonDbService.setData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in LiveStateService setUserAsEditor: ",t)}})}fetchSingleEditorLiveStateDataFromDatabase(){return Q(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: fetchSingleEditorLiveStateDataFromDatabase","color: green;"),yield this.commonDbService.getData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}})}catch(e){return this.loggingService.catch("Error in LiveStateService fetchSingleEditorLiveStateDataFromDatabase: ",e),null}})}setRequestAccessTimer(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRequestAccessTimer","color: green;"),this.requestAccessTimer||(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.acceptEditorAccessRequest(),this.clearRequestAccessTimer()},e*1e3),this.setEditorAccessTimerInterval(e))}catch(t){this.loggingService.catch("Error in LiveStateService setRequestAccessTimer: ",t)}}clearRequestAccessTimer(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearRequestAccessTimer","color: green;"),this.requestAccessTimer&&(clearTimeout(this.requestAccessTimer),this.requestAccessTimer=null)}catch(e){this.loggingService.catch("Error in LiveStateService clearRequestAccessTimer: ",e)}}requestEditorAccess(){this.loggingService.log("%c[WB] Calling FUNCTION: requestEditorAccess","color: green;");try{return this.serverConnectionState$.value===K.OFFLINE?(this.loggingService.catch("User is offline."),p(null)):(this.analyticsService.trackEvent(m.Events.LiveStateSync.REQUEST_EDITOR_ACCESS_TRIGGERED),new mt(e=>{let t=null;try{if(this.user&&this.documentPaths?.liveStateSingleEditorMode){let i=this.getEditorAccessTimeout(),s=this.realtimeAdapter.rtdbRef(this.db,`${this.documentPaths?.liveStateSingleEditorMode}`),l={requestEditorAccess:{user:this.user,requestedAt:this.timestamp,status:"pending",editorAccessTimeout:i,tabId:this.tabId}};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},errorCallback:u=>{this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",u),e.next(null),e.complete()},callback:()=>{i&&(this.requestAccessTimer=setTimeout(()=>{this.getEditorAccessTransferOnTimeOut()&&this.setUserAsEditor({skipEditorCheck:!0})},(i+3)*1e3),this.setEditorAccessTimerInterval(i+3)),t=this.getSingleEditorLiveStateData$().subscribe(u=>{u&&(u?.requestEditorAccess?u?.requestEditorAccess?.status==="cancelled"&&(e.next(null),e.complete()):u?.editor?.userId===this.user?.userId?(e.next(!0),e.complete()):(e.next(!1),e.complete()))})},data:JSON.parse(JSON.stringify(l))})}else e.next(!1),e.complete()}catch(i){this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",i),e.next(null),e.complete()}return()=>{t&&t?.unsubscribe()}}))}catch(e){return this.loggingService.catch("Error in LiveStateService requestEditorAccess: ",e),p(null)}}makeEditor(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeEditor","color: green;");let e=this.singleEditorLiveStateData?.tabId===this.tabId;this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_MAKE_EDITOR_TRIGGERED,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!0,isEditorOnCurrentTab:e}),this.isEditor$.next({isEditor:!0,isEditorOnCurrentTab:e}),this.getSingleEditorModeConfig()?.customMode||(!this.getSingleEditorModeConfig()?.singleTabEditor||e?(this.enableInputElements(),this.enableElementEvents()):(this.disableInputElements(),this.disableElementEvents())),this.fetchSingleEditorLiveStateDataFromDatabase().then(t=>{this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_ON_MAKE_EDITOR,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!0,isEditorOnCurrentTab:e,singleEditorLiveStateDataOnServer:t})}).catch(t=>{})}catch(e){this.loggingService.catch("Error in LiveStateService makeEditor: ",e)}}makeReader(){try{this.loggingService.log("%c[WB] Calling FUNCTION: makeReader","color: green;"),this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_MAKE_READER_TRIGGERED,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!1,isEditorOnCurrentTab:!1}),this.isEditor$.next({isEditor:!1,isEditorOnCurrentTab:!1}),this.getSingleEditorModeConfig()?.customMode||(this.disableInputElements(),this.disableElementEvents()),this.fetchSingleEditorLiveStateDataFromDatabase().then(e=>{this.analyticsService.trackEvent(m.Events.LiveStateSync.SEM_SINGLE_EDITOR_LIVE_STATE_DATA_ON_MAKE_READER,{editorUserId:this.singleEditorLiveStateData?.editor?.userId,tabId:this.tabId,editorTabId:this.singleEditorLiveStateData?.tabId,isEditor:!1,isEditorOnCurrentTab:!1,singleEditorLiveStateDataOnServer:e})}).catch(e=>{})}catch(e){this.loggingService.catch("Error in makeReader: ",e)}}acceptEditorAccessRequest(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: acceptEditorAccessRequest","color: green;"),this.serverConnectionState$.value===K.OFFLINE){this.loggingService.catch("User is offline.");return}if(this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e=this.singleEditorLiveStateData?.requestEditorAccess?.user,t=this.singleEditorLiveStateData?.requestEditorAccess?.tabId;if(e&&t){let i={editor:e,requestEditorAccess:null,tabId:t,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(i))}),this.analyticsService.trackEvent(m.Events.LiveStateSync.ACCEPT_EDITOR_ACCESS_REQUEST_TRIGGERED,{editorUserId:e?.userSnippylyId,tabId:t})}}}catch(e){this.loggingService.catch("Error in acceptEditorAccessRequest: ",e)}})}rejectEditorAccessRequest(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: rejectEditorAccessRequest","color: green;"),this.serverConnectionState$.value===K.OFFLINE){this.loggingService.catch("User is offline.");return}if(this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.isUserEditor()?.isEditor&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:null};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(m.Events.LiveStateSync.REJECT_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService rejectEditorAccessRequest: ",e)}})}cancelEditorAccessRequest(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: cancelEditorAccessRequest","color: green;"),this.serverConnectionState$.value===K.OFFLINE){this.loggingService.catch("User is offline.");return}if(this.user&&this.singleEditorLiveStateData?.requestEditorAccess&&this.documentPaths?.liveStateSingleEditorMode){let e={requestEditorAccess:A(f({},this.singleEditorLiveStateData?.requestEditorAccess),{status:"cancelled"})};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(e))}),e={requestEditorAccess:null},this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(m.Events.LiveStateSync.CANCEL_EDITOR_ACCESS_REQUEST_TRIGGERED)}}catch(e){this.loggingService.catch("Error in LiveStateService cancelEditorAccessRequest: ",e)}})}editCurrentTab(){return Q(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: editCurrentTab","color: green;"),this.serverConnectionState$.value===K.OFFLINE){this.loggingService.catch("User is offline.");return}if(this.user&&this.isUserEditor()?.isEditor&&!this.isUserEditor()?.isEditorOnCurrentTab&&this.documentPaths?.liveStateSingleEditorMode){let e={tabId:this.tabId,editor:this.user,editorAt:this.timestamp};this.commonDbService.updateData({feature:"liveStateSingleEditorMode",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0,rtdbTransaction:!0},data:JSON.parse(JSON.stringify(e))}),this.analyticsService.trackEvent(m.Events.LiveStateSync.EDIT_CURRENT_TAB_TRIGGERED,{tabId:this.tabId})}}catch(e){this.loggingService.catch("Error in LiveStateService editCurrentTab: ",e)}})}isUserEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor$","color: green;"),this.isEditor$.asObservable().pipe(ne(Ee))}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor$: ",e),p(null)}}isUserEditor(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isUserEditor","color: green;"),this.isEditor$.value}catch(e){return this.loggingService.catch("Error in LiveStateService isUserEditor: ",e),null}}getEditor$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getEditor$","color: green;"),this.getSingleEditorLiveStateData$().pipe(D(e=>e?.editor||null),ne())}catch(e){return this.loggingService.catch("Error in LiveStateService getEditor$: ",e),p(null)}}isEditorAccessRequested$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: isEditorAccessRequested$","color: green;"),this.isUserEditor$().pipe(y(e=>e?.isEditor?this.singleEditorLiveStateData$.pipe(D(t=>t?.requestEditorAccess?{requestStatus:"requested",requestedBy:t?.requestEditorAccess?.user}:null)):p(null)),ne((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}catch(e){return this.loggingService.catch("Error in LiveStateService isEditorAccessRequested$: ",e),p(null)}}removeEditorAccess(e){return Q(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeEditorAccess","color: green;"),this.analyticsService.trackEvent(m.Events.LiveStateSync.REMOVE_EDITOR_ACCESS,{removeEditorAccessMetadata:e?.metadata});let t=e?.documentPaths??this.documentPaths;(this.user||this.authService.getAuthUser())&&t?.liveStateSingleEditorMode&&(yield this.commonDbService.deleteData({feature:"liveStateSingleEditorMode",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",skipFirestore:!0}}))}catch(t){this.loggingService.catch("Error in LiveStateService removeEditorAccess: ",t)}})}getSingleEditorLiveStateData$(){return this.singleEditorLiveStateData$.asObservable().pipe(ne(Ee))}subscribeAutoSyncState(){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),this.authService.getAuthState$().pipe(k(e=>!!e),y(e=>this.isFeatureAllowed({firebaseUser:e,liveStateData:{}})),y(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(D(t=>(e.featureAllowed=t,e))):p(e)),y(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(D(t=>(e.featureAllowed=!t,e))):p(e)),y(e=>e.featureAllowed?p(e).pipe(y(t=>this.docService.getDocumentPaths$().pipe(k(i=>!!i),D(i=>(this.documentPaths=i,t.documentPaths=i,t)))),y(t=>this.domService.onNetworkStatusChange$().pipe(k(i=>i),D(()=>t))),y(t=>this.getLiveStateAutoSyncStateDataFromDocumentId().pipe(D(i=>(t.liveStateData=i,f({},t))))),D(t=>{if(t.liveStateData)this.liveStateAutoSyncStateData