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.

2 lines (1 loc) 34.4 kB
import{a as de}from"./chunk-6E3N35RF.js";import{$ as _,$h as te,Cf as p,E as O,Ge as Q,Gi as se,H as $,I as M,Ii as ae,Of as z,Pc as q,T as k,Ta as G,Va as Y,W,Wd as f,Zh as ee,a as w,aa as x,b as R,bi as A,ca as b,ci as re,di as h,ei as ie,fe as V,g as v,je as J,k as P,l as H,li as ce,mi as ne,r as E,vf as K,vh as X,wf as j,yh as Z,yi as oe}from"./chunk-GR3NESUB.js";var F=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,r){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new P),this.actionSubjects.get(e)?.next(r)}catch(n){this.loggingService.catch("Error in CrdtActionsService triggerAction: ",n)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new P);let r=this.actionSubjects.get(e);return r?r.asObservable():E(null)}catch(r){return this.loggingService.catch("Error in CrdtActionsService onAction: ",r),E(null)}}};o.\u0275fac=function(r){return new(r||o)(b(h))},o.\u0275prov=_({token:o,factory:o.\u0275fac,providedIn:"root"});let y=o;return y})();var I=(()=>{let o=class o{static generateKey(){return v(this,null,function*(){try{return yield window.crypto.subtle.generateKey({name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"])}catch(e){return f.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,r){return v(this,null,function*(){try{if(!r){let t=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));r=new Uint8Array(t).slice(0,this.SALT_LENGTH)}let n=new TextEncoder().encode(e),i=yield window.crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits","deriveKey"]);return{key:yield window.crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},i,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:r}}catch(n){return f.catch("Failed to derive key from password: ",n),null}})}static resolveKey(e){return v(this,null,function*(){try{if(e.customKey){if(e.customKey instanceof CryptoKey)return{key:e.customKey};if(typeof e.customKey=="string"){let n=yield this.deriveKeyFromPassword(e.customKey,e.customSalt);if(!n)return f.catch("Failed to derive key from password"),null;let{key:i,salt:c}=n;return{key:i,salt:c}}}let r=yield this.generateKey();return r?{key:r}:(f.catch("Failed to generate key"),null)}catch(r){return f.catch("Failed to resolve key: ",r),null}})}static encrypt(n){return v(this,arguments,function*(e,r={}){try{if(r.customEncryptCallback)try{return yield r.customEncryptCallback(e)}catch(g){return f.catch("Custom encryption callback failed: ",g),""}let i=yield this.resolveKey(r);if(!i)return f.catch("Failed to resolve key"),"";let{key:c,salt:t}=i,s;if(r.customIV){if(r.customIV.length!==this.IV_LENGTH)return f.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";s=r.customIV}else s=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let a=new TextEncoder().encode(e),d={name:"AES-GCM",iv:s,tagLength:128};r.additionalData&&(d.additionalData=r.additionalData);try{let g=yield window.crypto.subtle.encrypt(d,c,a),u=new Uint8Array(s.length+g.byteLength);u.set(s,0),u.set(new Uint8Array(g),s.length);let m=8192,C=[];for(let D=0;D<u.length;D+=m){let T=u.slice(D,Math.min(D+m,u.length)),U="";for(let N=0;N<T.length;N++)U+=String.fromCharCode(T[N]);C.push(U)}return btoa(C.join(""))}catch(g){return f.catch("Encryption failed: ",g),""}}catch(i){return f.catch("Failed to encrypt: ",i),null}})}static decrypt(n){return v(this,arguments,function*(e,r={}){try{if(r.customDecryptCallback)try{return yield r.customDecryptCallback(e)}catch(g){return f.catch("Custom decryption callback failed: ",g),""}let i=yield this.resolveKey(r);if(!i)return f.catch("Failed to resolve key"),"";let{key:c}=i,t=new Uint8Array(atob(e).split("").map(g=>g.charCodeAt(0)));if(t.length<this.IV_LENGTH)return f.catch("Invalid encrypted data: Too short"),"";let s;if(r.customIV){if(r.customIV.length!==this.IV_LENGTH)return f.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";s=r.customIV}else s=t.slice(0,this.IV_LENGTH);let a=t.slice(this.IV_LENGTH),d={name:"AES-GCM",iv:s,tagLength:128};r.additionalData&&(d.additionalData=r.additionalData);try{let g=yield window.crypto.subtle.decrypt(d,c,a);return new TextDecoder().decode(g)}catch(g){return f.catch("Decryption failed: ",g),""}}catch(i){return f.catch("Failed to decrypt: ",i),""}})}static encryptData(n){return v(this,arguments,function*(e,r={}){try{let i=JSON.stringify(e);return(yield this.encrypt(i,r))??""}catch(i){return f.catch("Failed to encrypt data: ",i),""}})}static decryptData(n){return v(this,arguments,function*(e,r={}){try{let i=yield this.decrypt(e,r);return JSON.parse(i)}catch(i){return f.catch("Failed to decrypt data: ",i),null}})}};o.IV_LENGTH=12,o.SALT_LENGTH=16,o.PBKDF2_ITERATIONS=1e5,o.KEY_LENGTH=256;let y=o;return y})();var S=(()=>{let o=class o{constructor(e,r,n,i,c,t,s,a,d,g){this.analyticsService=e,this.authService=r,this.commonDbService=n,this.commonDbUtilsService=i,this.configService=c,this.crdtActionsService=t,this.docService=s,this.domService=a,this.loggingService=d,this.serviceBook=g,this.MIN_WEBHOOK_DEBOUNCE_TIME=5*1e3,this.webhookDebounceTime=this.MIN_WEBHOOK_DEBOUNCE_TIME,this.updateDataWebhookTrigger$=new P,this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null,this.webhookEnabled$=new H(!1),this.lastCrdtDataUpdatedId=null,this.MIN_ACTIVITY_DEBOUNCE_TIME=10*1e3,this.activityDebounceTime=600*1e3,this.editorEditTrackers=new Map,this.activityService=null,this.notificationService=null;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;"),this.serviceBook.observe(ee).subscribe(u=>{this.activityService=u}),this.serviceBook.observe(Z).subscribe(u=>{this.notificationService=u}),this.setupUpdateDataWebhookDebounce(),this.docService.addPreDocumentIdChangeFunction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve())),this.authService.addPreSignOutFuction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve()))}catch(u){this.loggingService.catch("Error in CrdtService constructor: ",u)}}trackCrdtDataUpdated(e){try{if(this.lastCrdtDataUpdatedId===e)return;this.lastCrdtDataUpdatedId=e,this.analyticsService.trackEvent(X.Events.Crdt.CRDT_DATA_UPDATED,{id:e})}catch(r){this.loggingService.catch("Error in CrdtService trackCrdtDataUpdated: ",r)}}setupUpdateDataWebhookDebounce(){try{this.updateDataWebhookDebounceSubscription&&(this.updateDataWebhookDebounceSubscription.unsubscribe(),this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null),this.updateDataWebhookDebounceSubscription=this.updateDataWebhookTrigger$.pipe(W(e=>{this.pendingWebhookEvent=e}),M(this.webhookDebounceTime)).subscribe(e=>{this.pendingWebhookEvent=null,this.webhookEnabled$.value&&e&&this.triggerUpdateDataWebhook(e)},e=>{this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce subscription: ",e)})}catch(e){this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce: ",e)}}setWebhookDebounceTime(e){try{e<this.MIN_WEBHOOK_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: Value must be at least "+this.MIN_WEBHOOK_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_WEBHOOK_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_WEBHOOK_DEBOUNCE_TIME),this.pendingWebhookEvent&&this.webhookEnabled$.value&&(this.triggerUpdateDataWebhook(this.pendingWebhookEvent),this.pendingWebhookEvent=null),this.webhookDebounceTime=e,this.setupUpdateDataWebhookDebounce()}catch(r){this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: ",r)}}updateData(i){return v(this,arguments,function*({id:e,state:r,data:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let c=this.docService.getDocumentPaths(),t=this.authService.getUser(),s=this.domService.getTabId();if(t?.userId&&c){let a=p(e),d=t.userId,g=p(t.userId),u=new Date().toISOString(),m=null,C=this.configService.getEncryptionProvider();if(C?.encrypt&&typeof C.encrypt=="function")m=yield C.encrypt({data:r});else{let N={};N.customKey=a,m=yield I.encryptData(r,N)}let D={id:e,veltId:a,encryptedState:m,lastUpdate:u,lastUpdatedBy:d,lastUpdatedByVeltUserId:g,sessionId:s},T={methodName:j.UPDATE_DATA,uniqueId:z(),timestamp:new Date().getTime(),source:K.INTERNAL,payload:{id:e,data:n,lastUpdatedBy:d,sessionId:s,lastUpdate:u}},U=yield this.commonDbService.updateData({feature:"crdtData",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:a,skipFirestore:!0},data:D});return this.crdtActionsService.triggerAction(V.UPDATE_DATA,T),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(T?.payload),this.trackEditForActivity(e),U}return Promise.resolve(null)}catch(c){return this.loggingService.catch("Error in CrdtService updateData: ",c),Promise.resolve(null)}})}triggerUpdateDataWebhook(e){try{this.updateNotificationsDatabase(e,J.UPDATE_DATA)}catch(r){this.loggingService.catch("Error in CrdtService triggerUpdateDataWebhook: ",r)}}onDataChange({id:e,callback:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let n=p(e),i=this.docService.getDocumentPaths$().pipe(k(c=>c?this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:n,skipFirestore:!0}}).pipe(k(t=>v(this,null,function*(){try{if(t?.data){if(t.data.encryptedState){let s=null,a=this.configService.getEncryptionProvider();if(a?.decrypt&&typeof a.decrypt=="function")s=yield a.decrypt({data:t.data.encryptedState});else{let d={};d.customKey=n,s=yield I.decryptData(t.data.encryptedState,d)}t.data.state=s,delete t.data?.encryptedState}return t}else{if(t?.encryptedState){let s=null,a=this.configService.getEncryptionProvider();if(a?.decrypt&&typeof a.decrypt=="function")s=yield a.decrypt({data:t.encryptedState});else{let d={};d.customKey=n,s=yield I.decryptData(t.encryptedState,d)}t.state=s,delete t?.encryptedState}return t}}catch(s){return this.loggingService.catch("Error in CrdtService onDataChange subscription: ",s),null}}))):E(null))).subscribe(c=>{c&&(c.data?r(c.data):r(c))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onDataChange: ",n),()=>{}}}getData(r){return v(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getData","color: green;");let n=this.docService.getDocumentPaths();if(n){let i=p(e),c=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});if(c?.encryptedState){let t=null,s=this.configService.getEncryptionProvider();if(s?.decrypt&&typeof s.decrypt=="function")t=yield s.decrypt({data:c.encryptedState});else{let a={};a.customKey=i,t=yield I.decryptData(c.encryptedState,a)}c.state=t,delete c?.encryptedState}return c}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getData: ",n),Promise.resolve(null)}})}onStateChange({id:e,callback:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let n=p(e),i=this.docService.getDocumentPaths$().pipe(k(c=>c?this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:n,skipFirestore:!0}}).pipe(k(t=>v(this,null,function*(){try{if(t?.data){if(t.data.encryptedState){let s=null,a=this.configService.getEncryptionProvider();if(a?.decrypt&&typeof a.decrypt=="function")s=yield a.decrypt({data:t.data.encryptedState});else{let d={};d.customKey=n,s=yield I.decryptData(t.data.encryptedState,d)}t.data.state=s,delete t.data?.encryptedState}return t}else{if(t?.encryptedState){let s=null,a=this.configService.getEncryptionProvider();if(a?.decrypt&&typeof a.decrypt=="function")s=yield a.decrypt({data:t.encryptedState});else{let d={};d.customKey=n,s=yield I.decryptData(t.encryptedState,d)}t.state=s,delete t?.encryptedState}return t}}catch(s){return this.loggingService.catch("Error in CrdtService onStateChange subscription: ",s),null}}))):E(null))).subscribe(c=>{c&&(c.data?r(c.data):r(c))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onStateChange: ",n),()=>{}}}updateState(n){return v(this,arguments,function*({id:e,state:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let i=this.docService.getDocumentPaths(),c=this.authService.getUser(),t=this.domService.getTabId();if(c?.userId&&i){let s=p(e),a=c.userId,d=p(a),g=null,u=this.configService.getEncryptionProvider();if(u?.encrypt&&typeof u.encrypt=="function")g=yield u.encrypt({data:r});else{let m={};m.customKey=s,g=yield I.encryptData(r,m)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:s,skipFirestore:!0},data:{id:e,veltId:s,encryptedState:g,lastUpdate:new Date().toISOString(),lastUpdatedBy:a,lastUpdatedByVeltUserId:d,sessionId:t}})}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService updateState: ",i),Promise.resolve(null)}})}registerSyncUser(r){return v(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: registerSyncUser","color: green;");let n=this.authService.getUser(),i=this.docService.getDocumentPaths(),c=this.configService.getApiKey(),t=p(e),s=this.domService.getTabId();if(n?.userId&&i&&c){let a=n.userId,d=p(a),g={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:t,userId:d,apiKey:c,skipFirestore:!0},u={userId:a,veltUserId:d,status:"online",lastSeen:Date.now(),sessionId:s};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:g,data:u});let m=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:g,defaultDocumentPaths:i,apiKey:c});m&&(yield this.commonDbService.setupOnDisconnect(m,{status:"offline",lastSeen:new Date().getTime(),sessionId:s}))}}catch(n){this.loggingService.catch("Error in CrdtService registerSyncUser: ",n)}})}onRegisteredUserChange({id:e,callback:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let n=p(e),i=this.docService.getDocumentPaths$().pipe(k(c=>c?this.commonDbService.dbListener({feature:"allCrdtSyncPresence",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:n,skipFirestore:!0}}).pipe(W(t=>{try{t?.data?r(t.data):r(t)}catch(s){this.loggingService.catch("Error in CrdtService onRegisteredUserChange subscription: ",s)}})):E(null))).subscribe(()=>{});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",n),()=>{}}}setPresence(r){return v(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: setPresence","color: green;");let n=this.authService.getUser(),i=this.docService.getDocumentPaths(),c=this.configService.getApiKey(),t=p(e),s=this.domService.getTabId();if(n?.userId&&i&&c){let a=n.userId,d=p(a),g={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:t,userId:d,apiKey:c,skipFirestore:!0},u={userId:a,veltUserId:d,status:"online",lastSeen:Date.now(),sessionId:s};yield this.commonDbService.setData({feature:"crdtPresence",properties:g,data:u});let m=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:g,defaultDocumentPaths:i,apiKey:c});m&&(yield this.commonDbService.setupOnDisconnect(m,{status:"offline",lastSeen:new Date().getTime(),sessionId:s}))}}catch(n){this.loggingService.catch("Error in CrdtService setPresence: ",n)}})}onPresenceChange({id:e,callback:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let n=p(e),i=this.docService.getDocumentPaths$().pipe(k(c=>c?this.commonDbService.dbListener({feature:"allCrdtPresence",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:n,skipFirestore:!0}}).pipe(W(t=>{try{t?.data?r(t.data):r(t)}catch(s){this.loggingService.catch("Error in CrdtService onPresenceChange subscription: ",s)}})):E(null))).subscribe(()=>{});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",n),()=>{}}}saveVersion(c){return v(this,arguments,function*({id:e,versionId:r,versionName:n,state:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let t=this.docService.getDocumentPaths();if(t){let s=p(e),a="",d=this.configService.getEncryptionProvider();if(d?.encrypt&&typeof d.encrypt=="function")a=yield d.encrypt({data:i});else{let u={};u.customKey=s,a=yield I.encryptData(i,u)}let g={versionId:r,versionName:n,encryptedState:a,timestamp:new Date().getTime()};return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:s,versionId:r,skipFirestore:!0},data:w({id:e},g)})}return Promise.resolve(null)}catch(t){return this.loggingService.catch("Error in CrdtService saveVersion: ",t),Promise.resolve(null)}})}getVersion(n){return v(this,arguments,function*({id:e,versionId:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersion","color: green;");let i=this.docService.getDocumentPaths();if(i){let c=p(e),t=yield this.commonDbService.getData({feature:"crdtVersion",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:c,versionId:r,skipFirestore:!0}});if(t?.encryptedState){let s=null,a=this.configService.getEncryptionProvider();if(a?.decrypt&&typeof a.decrypt=="function")s=yield a.decrypt({data:t.encryptedState});else{let d={};d.customKey=c,s=yield I.decryptData(t.encryptedState,d)}t.state=s,delete t.encryptedState}return t}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getVersion: ",i),Promise.resolve(null)}})}getVersions(r){return v(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersions","color: green;");let n=this.docService.getDocumentPaths();if(n){let i=p(e),c=yield this.commonDbService.getData({feature:"crdtVersions",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}}),t=null;if(c){t=[];for(let s of Object.values(c))if(s?.encryptedState){let a=null,d=this.configService.getEncryptionProvider();if(d?.decrypt&&typeof d.decrypt=="function")a=yield d.decrypt({data:s.encryptedState});else{let u={};u.customKey=i,a=yield I.decryptData(s.encryptedState,u)}let g=R(w({},s),{state:a});delete g?.encryptedState,t.push(g)}else t.push(s)}return t}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getVersions: ",n),Promise.resolve(null)}})}encryptCrdtData(e,r){return v(this,null,function*(){try{let n=this.configService.getEncryptionProvider();if(n?.encrypt&&typeof n.encrypt=="function")return yield n.encrypt({data:e});let i={};return i.customKey=r,yield I.encryptData(e,i)}catch(n){return this.loggingService.catch("Error in CrdtService encryptCrdtData: ",n),null}})}decryptCrdtData(e,r){return v(this,null,function*(){try{let n=this.configService.getEncryptionProvider();if(n?.decrypt&&typeof n.decrypt=="function")return yield n.decrypt({data:e});let i={};return i.customKey=r,yield I.decryptData(e,i)}catch(n){return this.loggingService.catch("Error in CrdtService decryptCrdtData: ",n),null}})}pushMessage(d){return v(this,arguments,function*({id:e,data:r,yjsClientId:n,messageType:i,eventData:c,type:t,contentKey:s,source:a}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pushMessage","color: green;");let g=this.docService.getDocumentPaths(),u=this.authService.getUser();if(u?.userId&&g){let m=p(e),C=yield this.encryptCrdtData(r,m);if(C==null)return;let D=u.userId,T=p(u.userId),U=this.domService.getTabId();if(yield this.commonDbService.pushData({feature:"crdtMessages",properties:{documentId:g?.documentId??"",organizationId:g?.organizationId??"",id:m,skipFirestore:!0},data:{id:e,veltId:m,encryptedData:C,yjsClientId:n,messageType:i??null,type:t??null,contentKey:s??null,source:a??"unknown",updatedByUserId:D,updatedByVeltUserId:T,sessionId:U,timestamp:this.commonDbService.getServerTimestamp()}}),i==="sync"){let N=new Date().toISOString(),L={methodName:j.UPDATE_DATA,uniqueId:z(),timestamp:new Date().getTime(),source:K.INTERNAL,payload:{id:e,data:c,lastUpdatedBy:D,sessionId:U,lastUpdate:N}};this.crdtActionsService.triggerAction(V.UPDATE_DATA,L),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(L?.payload),this.trackEditForActivity(e)}}}catch(g){this.loggingService.catch("Error in CrdtService pushMessage: ",g)}})}onMessage({id:e,callback:r,afterTs:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onMessage","color: green;");let i=p(e),c=this.docService.getDocumentPaths$().pipe(k(t=>t?this.commonDbService.streamChildAdded({feature:"crdtMessages",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:i,skipFirestore:!0},afterTs:n}):E(null))).pipe(O(t=>!!t),$(t=>v(this,null,function*(){try{if(t.encryptedData){let s=yield this.decryptCrdtData(t.encryptedData,i);if(s==null)return null;t.data=s,delete t.encryptedData}else if(!t.data)return null;return t}catch(s){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",s),null}})),O(t=>!!t)).subscribe(t=>{try{r(t)}catch(s){this.loggingService.catch("Error in CrdtService onMessage subscription: ",s)}});return()=>c.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onMessage: ",i),()=>{}}}getMessages(n){return v(this,arguments,function*({id:e,afterTs:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getMessages","color: green;");let i=this.docService.getDocumentPaths();if(i){let c=p(e),t=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:c,skipFirestore:!0}});if(!t||typeof t!="object"||t?.errorCode)return[];let s=[];for(let a of Object.keys(t)){let d=t[a];if(!(!d||typeof d!="object")&&!(r!=null&&d.timestamp!=null&&d.timestamp<=r))if(d.encryptedData){let g=yield this.decryptCrdtData(d.encryptedData,c);if(g==null)continue;s.push({data:g,yjsClientId:d.yjsClientId,timestamp:d.timestamp})}else d.data&&s.push({data:d.data,yjsClientId:d.yjsClientId,timestamp:d.timestamp})}return s.sort((a,d)=>a.timestamp-d.timestamp),s}return[]}catch(i){return this.loggingService.catch("Error in CrdtService getMessages: ",i),[]}})}getSnapshot(r){return v(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getSnapshot","color: green;");let n=this.docService.getDocumentPaths();if(n){let i=p(e),c=yield this.commonDbService.getData({feature:"crdtSnapshot",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});if(!c||typeof c!="object"||Object.keys(c).length===0||c?.errorCode)return null;if(c?.encryptedState){let t=yield this.decryptCrdtData(c.encryptedState,i);if(t==null)return null;c.state=t,delete c?.encryptedState}if(c?.encryptedVector){let t=yield this.decryptCrdtData(c.encryptedVector,i);if(t==null)return null;c.vector=t,delete c?.encryptedVector}return c}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getSnapshot: ",n),Promise.resolve(null)}})}saveSnapshot(s){return v(this,arguments,function*({id:e,state:r,vector:n,type:i,contentKey:c,source:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveSnapshot","color: green;");let a=this.docService.getDocumentPaths(),d=this.authService.getUser();if(d?.userId&&a){let g=p(e),u=yield this.encryptCrdtData(r,g),m=yield this.encryptCrdtData(n,g);if(u==null||m==null)return;let C=d.userId,D=p(d.userId),T=this.domService.getTabId();yield this.commonDbService.setData({feature:"crdtSnapshot",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:g,skipFirestore:!0},data:{id:e,veltId:g,encryptedState:u,encryptedVector:m,type:i??null,contentKey:c??null,source:t??"unknown",updatedByUserId:C,updatedByVeltUserId:D,sessionId:T,timestamp:this.commonDbService.getServerTimestamp()}})}}catch(a){this.loggingService.catch("Error in CrdtService saveSnapshot: ",a)}})}pruneMessages(n){return v(this,arguments,function*({id:e,beforeTs:r}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pruneMessages","color: green;");let i=this.docService.getDocumentPaths();if(i){let c=p(e),t=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:c,skipFirestore:!0}});if(t&&typeof t=="object"&&!t?.errorCode){let s=[];for(let a of Object.keys(t)){let d=t[a];d?.timestamp!=null&&d.timestamp<r&&s.push(this.commonDbService.deleteData({feature:"crdtMessage",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:c,messageId:a,skipFirestore:!0}}))}yield Promise.all(s)}}}catch(i){this.loggingService.catch("Error in CrdtService pruneMessages: ",i)}})}updateNotificationsDatabase(e,r,n={}){try{let i=w({crdtData:e,actionType:r,notificationSource:"crdt"},n);this.notificationService?.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in CrdtService updateNotificationsDatabase: ",i)}}enableWebhook(){try{if(this.webhookEnabled$.value===!0)return;this.webhookEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CrdtService enableWebhook: ",e)}}disableWebhook(){try{if(this.webhookEnabled$.value===!1)return;this.webhookEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CrdtService disableWebhook: ",e)}}trackEditForActivity(e){try{let r=this.editorEditTrackers.get(e);if(!r){let n=new P,i=n.pipe(M(this.activityDebounceTime)).subscribe(()=>{this.flushEditorActivity(e)});r={count:0,subject$:n,subscription:i},this.editorEditTrackers.set(e,r)}r.count++,r.subject$.next()}catch(r){this.loggingService.catch("Error in CrdtService trackEditForActivity: ",r)}}flushEditorActivity(e){try{let r=this.editorEditTrackers.get(e);if(!r||r.count===0)return;let n=r.count;r.count=0;let i={featureType:"crdt",actionType:Q.EDITOR_EDIT,targetEntityId:e,entityData:{editCount:n}};this.activityService?.createActivity(i)}catch(r){this.loggingService.catch("Error in CrdtService flushEditorActivity: ",r)}}setActivityDebounceTime(e){try{e<this.MIN_ACTIVITY_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setActivityDebounceTime: Value must be at least "+this.MIN_ACTIVITY_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_ACTIVITY_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_ACTIVITY_DEBOUNCE_TIME),this.flushAllEditorActivities(),this.activityDebounceTime=e}catch(r){this.loggingService.catch("Error in CrdtService setActivityDebounceTime: ",r)}}flushAllEditorActivities(){try{for(let[e,r]of this.editorEditTrackers)r.count>0&&this.flushEditorActivity(e),r.subject$.complete(),r.subscription.unsubscribe();this.editorEditTrackers.clear()}catch(e){this.loggingService.catch("Error in CrdtService flushAllEditorActivities: ",e)}}};o.\u0275fac=function(r){return new(r||o)(b(re),b(ne),b(ae),b(se),b(ie),b(F),b(oe),b(ce),b(h),b(A))},o.\u0275prov=_({token:o,factory:o.\u0275fac,providedIn:"root"});let y=o;return y})();var B=class extends de{constructor(o){super(o),this.getService(h).log("%c[WB] Creating CLASS: CrdtElement","color: blue;"),this.updateData=this._updateData,this.onDataChange=this._onDataChange,this.getData=this._getData,this.onStateChange=this._onStateChange,this.updateState=this._updateState,this.registerSyncUser=this._registerSyncUser,this.onRegisteredUserChange=this._onRegisteredUserChange,this.setPresence=this._setPresence,this.onPresenceChange=this._onPresenceChange,this.saveVersion=this._saveVersion,this.getVersion=this._getVersion,this.getVersions=this._getVersions,this.pushMessage=this._pushMessage,this.onMessage=this._onMessage,this.getMessages=this._getMessages,this.getSnapshot=this._getSnapshot,this.saveSnapshot=this._saveSnapshot,this.pruneMessages=this._pruneMessages,this.enableWebhook=this._enableWebhook,this.disableWebhook=this._disableWebhook,this.setWebhookDebounceTime=this._setWebhookDebounceTime,this.setActivityDebounceTime=this._setActivityDebounceTime,this.on=this._on}_updateData(o){this.getService(h).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(S).updateData(o)}catch(l){return this.getService(h).catch("Error in updateData: ",l),Promise.resolve(null)}}_onDataChange(o){this.getService(h).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(S).onDataChange(o)}catch(l){return this.getService(h).catch("Error in onDataChange: ",l),()=>{}}}_getData(o){this.getService(h).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(S).getData(o)}catch(l){return this.getService(h).catch("Error in getData: ",l),Promise.resolve(null)}}_onStateChange(o){this.getService(h).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(S).onStateChange(o)}catch(l){return this.getService(h).catch("Error in onStateChange: ",l),()=>{}}}_updateState(o){this.getService(h).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(S).updateState(o)}catch(l){return this.getService(h).catch("Error in updateState: ",l),Promise.resolve(null)}}_registerSyncUser(o){this.getService(h).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(S).registerSyncUser(o)}catch(l){return this.getService(h).catch("Error in registerSyncUser: ",l),Promise.resolve()}}_onRegisteredUserChange(o){this.getService(h).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(S).onRegisteredUserChange(o)}catch(l){return this.getService(h).catch("Error in onRegisteredUserChange: ",l),()=>{}}}_setPresence(o){this.getService(h).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(S).setPresence(o)}catch(l){return this.getService(h).catch("Error in setPresence: ",l),Promise.resolve()}}_onPresenceChange(o){this.getService(h).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(S).onPresenceChange(o)}catch(l){return this.getService(h).catch("Error in onPresenceChange: ",l),()=>{}}}_saveVersion(o){this.getService(h).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(S).saveVersion(o)}catch(l){return this.getService(h).catch("Error in saveVersion: ",l),Promise.resolve(null)}}_getVersion(o){this.getService(h).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(S).getVersion(o)}catch(l){return this.getService(h).catch("Error in getVersion: ",l),Promise.resolve(null)}}_getVersions(o){this.getService(h).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(S).getVersions(o)}catch(l){return this.getService(h).catch("Error in getVersions: ",l),Promise.resolve(null)}}_pushMessage(o){this.getService(h).log("%c[WB] Calling FUNCTION: pushMessage","color: green;");try{return this.getService(S).pushMessage(o)}catch(l){return this.getService(h).catch("Error in pushMessage: ",l),Promise.resolve()}}_onMessage(o){this.getService(h).log("%c[WB] Calling FUNCTION: onMessage","color: green;");try{return this.getService(S).onMessage(o)}catch(l){return this.getService(h).catch("Error in onMessage: ",l),()=>{}}}_getMessages(o){this.getService(h).log("%c[WB] Calling FUNCTION: getMessages","color: green;");try{return this.getService(S).getMessages(o)}catch(l){return this.getService(h).catch("Error in getMessages: ",l),Promise.resolve([])}}_getSnapshot(o){this.getService(h).log("%c[WB] Calling FUNCTION: getSnapshot","color: green;");try{return this.getService(S).getSnapshot(o)}catch(l){return this.getService(h).catch("Error in getSnapshot: ",l),Promise.resolve(null)}}_saveSnapshot(o){this.getService(h).log("%c[WB] Calling FUNCTION: saveSnapshot","color: green;");try{return this.getService(S).saveSnapshot(o)}catch(l){return this.getService(h).catch("Error in saveSnapshot: ",l),Promise.resolve()}}_pruneMessages(o){this.getService(h).log("%c[WB] Calling FUNCTION: pruneMessages","color: green;");try{return this.getService(S).pruneMessages(o)}catch(l){return this.getService(h).catch("Error in pruneMessages: ",l),Promise.resolve()}}_enableWebhook(){this.getService(h).log("%c[WB] Calling FUNCTION: enableWebhook","color: green;");try{return this.getService(S).enableWebhook()}catch(o){this.getService(h).catch("Error in enableWebhook: ",o);return}}_disableWebhook(){this.getService(h).log("%c[WB] Calling FUNCTION: disableWebhook","color: green;");try{return this.getService(S).disableWebhook()}catch(o){this.getService(h).catch("Error in disableWebhook: ",o);return}}_setWebhookDebounceTime(o){this.getService(h).log("%c[WB] Calling FUNCTION: setWebhookDebounceTime","color: green;");try{!isNaN(o)&&o>0?this.getService(S).setWebhookDebounceTime(o):this.getService(h).catch("Error in setWebhookDebounceTime: ","Provided value must be a positive number greater than zero.")}catch(l){this.getService(h).catch("Error in setWebhookDebounceTime: ",l)}}_setActivityDebounceTime(o){this.getService(h).log("%c[WB] Calling FUNCTION: setActivityDebounceTime","color: green;");try{!isNaN(o)&&o>=1e4?this.getService(S).setActivityDebounceTime(o):this.getService(h).catch("Error in setActivityDebounceTime: ","Provided value must be a number >= 10000ms (10 seconds).")}catch(l){this.getService(h).catch("Error in setActivityDebounceTime: ",l)}}_on(o){this.getService(h).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(F).onAction(o)}catch(l){return this.getService(h).catch("Error in on: ",l),E(null)}}};var ge=(()=>{let o=class o{};o.\u0275fac=function(r){return new(r||o)},o.\u0275mod=Y({type:o}),o.\u0275inj=x({imports:[q]});let y=o;return y})();function ve(y){return y.get(h).log("%c[WB] Loading CRDT feature chunk","color: blue;"),y.get(A).set(te,y.get(S)),G(ge,y),new B(y)}export{ve as default};