@veltdev/sdk-dev 6.0.18 → 6.0.20

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 (61) hide show
  1. package/app/models/data/comment-utils.data.model.d.ts +19 -0
  2. package/app/models/element/comment-element.model.d.ts +10 -3
  3. package/{chunk-T7KP622G.js → chunk-2K4M4I5G.js} +1 -1
  4. package/{chunk-TQYZX2M7.js → chunk-3EAHY5AQ.js} +1 -1
  5. package/{chunk-VXHKBDMP.js → chunk-4LTEANME.js} +1 -1
  6. package/{chunk-6TEVC4VB.js → chunk-4NYZ7Q5F.js} +1 -1
  7. package/{chunk-MIPUERB4.js → chunk-4PAKODQF.js} +1 -1
  8. package/{chunk-2IJ3Z5ZV.js → chunk-4WU3OMP2.js} +1 -1
  9. package/{chunk-DR75AZG3.js → chunk-5FPHCROD.js} +1 -1
  10. package/{chunk-3IPAYZ7Y.js → chunk-6KHIJTYE.js} +1 -1
  11. package/{chunk-BKZUXK5Q.js → chunk-7CGDY3KI.js} +1 -1
  12. package/{chunk-4I63DKJ7.js → chunk-CLK24UPS.js} +1 -1
  13. package/{chunk-HKOM6NRJ.js → chunk-D3WKAG4L.js} +1 -1
  14. package/{chunk-PKCY7NTA.js → chunk-E4QNS7VC.js} +1 -1
  15. package/{chunk-XMTWJMU7.js → chunk-ENQ42YAR.js} +1 -1
  16. package/{chunk-TT7PKTGG.js → chunk-GSCT27LN.js} +1 -1
  17. package/{chunk-JFPFA27E.js → chunk-GY5ZVUQW.js} +1 -1
  18. package/{chunk-FL7TUF6U.js → chunk-I24IAAR4.js} +1 -1
  19. package/chunk-IH7GHE67.js +1 -0
  20. package/{chunk-P3UR2XTS.js → chunk-J3PDCLKW.js} +1 -1
  21. package/{chunk-BOHOH3YV.js → chunk-KV2F6ZIJ.js} +1 -1
  22. package/{chunk-NXVDUKNP.js → chunk-LYIFCKA6.js} +1 -1
  23. package/{chunk-4YYL5LBM.js → chunk-MHSBCVFV.js} +1 -1
  24. package/{chunk-EVKWK3QF.js → chunk-MVAJQILF.js} +1 -1
  25. package/{chunk-D6IQX3MS.js → chunk-N2YYT47V.js} +1 -1
  26. package/{chunk-76EHFLIO.js → chunk-OBUNJ4HX.js} +1 -1
  27. package/{chunk-JPR7TB3V.js → chunk-PF5MHE5Q.js} +1 -1
  28. package/{chunk-WN7NM6YW.js → chunk-RBFBB2SC.js} +1 -1
  29. package/{chunk-TZAGYSHE.js → chunk-UMIDGOUI.js} +1 -1
  30. package/{chunk-6YDKDS43.js → chunk-VWOXXP3V.js} +1 -1
  31. package/{chunk-2NGUPIJA.js → chunk-VXMLF2G3.js} +1 -1
  32. package/{chunk-GXA7WFCW.js → chunk-XI2QEQ25.js} +1 -1
  33. package/chunk-XNDAIOIN.js +174 -0
  34. package/{chunk-BDVYEZ5H.js → chunk-Y6Q4SFD6.js} +1 -1
  35. package/{chunk-YFUTJBEE.js → chunk-Z7RCORHX.js} +1 -1
  36. package/{chunk-UV3WG5EA.js → chunk-ZJUF7S5H.js} +1 -1
  37. package/{chunk-RBD735AI.js → chunk-ZQSDSZOY.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 +2 -2
  60. package/chunk-LFLSU76Z.js +0 -1
  61. package/chunk-MV36YVGA.js +0 -174
package/velt-crdt.js CHANGED
@@ -1 +1 @@
1
- import{a as Fe}from"./chunk-4I63DKJ7.js";import{A as _e,j as Ae,v as Ne,w as re,x as Ue,y as Ve,z as Oe}from"./chunk-LFLSU76Z.js";import{Ci as fe,D as ge,Dj as W,E as j,Fj as M,Gj as B,H as Y,J,Jj as Te,Me as be,Oj as we,Pj as ke,Rc as ye,Rf as Z,Sf as ee,V as O,Va as ve,Xa as Se,Y as X,Yd as y,Zf as m,a as E,b as N,ba as L,bj as Ie,ca as pe,dj as De,ea as I,fj as x,g as v,gj as Ee,hj as g,i as le,ie as Q,ij as Pe,k as V,l as he,me,r as P,sg as te,w as ue,zi as Ce}from"./chunk-MV36YVGA.js";var q=(()=>{let r=class r{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new V),this.actionSubjects.get(e)?.next(t)}catch(n){this.loggingService.catch("Error in CrdtActionsService triggerAction: ",n)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new V);let t=this.actionSubjects.get(e);return t?t.asObservable():P(null)}catch(t){return this.loggingService.catch("Error in CrdtActionsService onAction: ",t),P(null)}}};r.\u0275fac=function(t){return new(t||r)(I(g))},r.\u0275prov=L({token:r,factory:r.\u0275fac,providedIn:"root"});let c=r;return c})();var T=(()=>{let r=class r{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 y.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,t){return v(this,null,function*(){try{if(!t){let s=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));t=new Uint8Array(s).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:t,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},i,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:t}}catch(n){return y.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 y.catch("Failed to derive key from password"),null;let{key:i,salt:o}=n;return{key:i,salt:o}}}let t=yield this.generateKey();return t?{key:t}:(y.catch("Failed to generate key"),null)}catch(t){return y.catch("Failed to resolve key: ",t),null}})}static encrypt(n){return v(this,arguments,function*(e,t={}){try{if(t.customEncryptCallback)try{return yield t.customEncryptCallback(e)}catch(h){return y.catch("Custom encryption callback failed: ",h),""}let i=yield this.resolveKey(t);if(!i)return y.catch("Failed to resolve key"),"";let{key:o,salt:s}=i,d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return y.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let l=new TextEncoder().encode(e),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let h=yield window.crypto.subtle.encrypt(u,o,l),p=new Uint8Array(d.length+h.byteLength);p.set(d,0),p.set(new Uint8Array(h),d.length);let S=8192,C=[];for(let f=0;f<p.length;f+=S){let w=p.slice(f,Math.min(f+S,p.length)),k="";for(let D=0;D<w.length;D++)k+=String.fromCharCode(w[D]);C.push(k)}return btoa(C.join(""))}catch(h){return y.catch("Encryption failed: ",h),""}}catch(i){return y.catch("Failed to encrypt: ",i),null}})}static decrypt(n){return v(this,arguments,function*(e,t={}){try{if(t.customDecryptCallback)try{return yield t.customDecryptCallback(e)}catch(h){return y.catch("Custom decryption callback failed: ",h),""}let i=yield this.resolveKey(t);if(!i)return y.catch("Failed to resolve key"),"";let{key:o}=i,s=new Uint8Array(atob(e).split("").map(h=>h.charCodeAt(0)));if(s.length<this.IV_LENGTH)return y.catch("Invalid encrypted data: Too short"),"";let d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return y.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=s.slice(0,this.IV_LENGTH);let l=s.slice(this.IV_LENGTH),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let h=yield window.crypto.subtle.decrypt(u,o,l);return new TextDecoder().decode(h)}catch(h){return y.catch("Decryption failed: ",h),""}}catch(i){return y.catch("Failed to decrypt: ",i),""}})}static encryptData(n){return v(this,arguments,function*(e,t={}){try{let i=JSON.stringify(e);return(yield this.encrypt(i,t))??""}catch(i){return y.catch("Failed to encrypt data: ",i),""}})}static decryptData(n){return v(this,arguments,function*(e,t={}){try{let i=yield this.decrypt(e,t);return JSON.parse(i)}catch(i){return y.catch("Failed to decrypt data: ",i),null}})}};r.IV_LENGTH=12,r.SALT_LENGTH=16,r.PBKDF2_ITERATIONS=1e5,r.KEY_LENGTH=256;let c=r;return c})();var ie=16777216;function ne(c){try{let r=new TextEncoder().encode(JSON.stringify(c)),a="";for(let e=0;e<r.length;e+=32768)a+=String.fromCharCode(...r.subarray(e,e+32768));return btoa(a)}catch(r){return y.catch("Error in wrapCrdtPayload: ",r),null}}function Me(c){try{let r=atob(c),a=new Uint8Array(r.length);for(let t=0;t<r.length;t++)a[t]=r.charCodeAt(t);let e=JSON.parse(new TextDecoder().decode(a));return e!==null&&typeof e=="object"?e:null}catch{return null}}var z=class{constructor(){this.log=[],this.logSeqs=new Set,this.fullReplayInProgress=!1,this.composite=null,this.compositeUptoSeq=0,this.listeners=new Set,this.snapshotListeners=new Set,this.denied=!1,this.primed=!1,this.primedWaiters=[],this.deliveredSeq=new Map,this.foldUnsafe=!1}ingest(r){try{if(this.denied)return;if(r?.type==="removed"){r.snapshot==="full"&&this.beginFullReplay();return}if(r?.snapshot==="full"?this.beginFullReplay():this.fullReplayInProgress=!1,r?.id==="snapshot"){let i=r.data,o=typeof i?.payloadB64=="string"?Me(i.payloadB64):null;if(o&&o.version===1&&o.editors&&typeof o.editors=="object"?this.composite=o:o!==null?(this.foldUnsafe=!0,y.catch("CrdtPortableChannelStore: unrecognized composite snapshot shape \u2014 ignored (folds disabled)",void 0)):typeof i?.payloadB64=="string"&&(this.foldUnsafe=!0),this.compositeUptoSeq=Number.isInteger(i?.uptoSeq)?i.uptoSeq:0,this.composite)for(let s of this.snapshotListeners)try{s(this.composite,this.compositeUptoSeq)}catch(d){y.catch("Error in CrdtPortableChannelStore snapshot listener: ",d)}return}let a=Number.isInteger(r?.seq)?r.seq:Number(r?.id);if(!Number.isFinite(a)){this.foldUnsafe=!0;return}if(this.logSeqs.has(a))return;let e=r.data?.payloadB64,t=typeof e=="string"?Me(e):null;if(t===null){this.foldUnsafe=!0,y.catch(`CrdtPortableChannelStore: dropping malformed crdt item seq=${a} (folds disabled)`,void 0);return}(typeof t.veltId!="string"||t.veltId.length===0)&&(this.foldUnsafe=!0);let n={seq:a,envelope:t};this.insertInSeqOrder(n);for(let i of this.listeners)try{i(n)}catch(o){y.catch("Error in CrdtPortableChannelStore listener: ",o)}}catch(a){y.catch("Error in CrdtPortableChannelStore ingest: ",a)}}markDenied(){this.denied=!0,this.fullReplayInProgress=!1,this.resetLog(),this.composite=null,this.compositeUptoSeq=0,this.markPrimed()}beginEpoch(){this.primed=!1,this.denied=!1,this.fullReplayInProgress=!1}markPrimed(r){r?.full===!0&&this.beginFullReplay(),this.primed=!0,this.fullReplayInProgress=!1;let a=this.primedWaiters;this.primedWaiters=[];for(let e of a)try{e()}catch(t){y.catch("Error in CrdtPortableChannelStore primed waiter: ",t)}}awaitPrimed(){return this.primed?Promise.resolve():new Promise(r=>this.primedWaiters.push(r))}markDelivered(r,a){Number.isFinite(a)&&a>(this.deliveredSeq.get(r)??0)&&this.deliveredSeq.set(r,a)}getDeliveredSeq(r){return this.deliveredSeq.get(r)??0}planFold(r,a,e){if(this.denied||!this.primed||this.foldUnsafe)return null;let t=1/0;for(let n of this.log)if(n.seq>this.compositeUptoSeq&&n.envelope.veltId!==r){t=n.seq-1;break}return{composite:{version:1,editors:N(E({},this.composite?.editors??{}),{[r]:a})},uptoSeq:Math.max(this.compositeUptoSeq,Math.min(e,t))}}adoptFold(r){this.denied||r.uptoSeq<this.compositeUptoSeq||(this.composite=r.composite,this.compositeUptoSeq=r.uptoSeq)}listen(r){return this.listeners.add(r),()=>this.listeners.delete(r)}listenSnapshot(r){return this.snapshotListeners.add(r),()=>this.snapshotListeners.delete(r)}entriesFor(r,a){return this.log.filter(e=>e.envelope.veltId===r&&(a===void 0||typeof e.envelope.timestamp!="number"||e.envelope.timestamp>a))}snapshotFor(r){return this.composite?.editors?.[r]??null}beginFullReplay(){this.fullReplayInProgress||(this.fullReplayInProgress=!0,this.resetLog(),this.composite=null,this.compositeUptoSeq=0)}insertInSeqOrder(r){this.logSeqs.add(r.seq);let a=this.log.length;for(;a>0&&this.log[a-1].seq>r.seq;)a--;this.log.splice(a,0,r)}resetLog(){this.log=[],this.logSeqs.clear()}};function oe(c,r){return{id:c.id,veltId:c.veltId,encryptedData:c.encryptedData,yjsClientId:c.yjsClientId,messageType:c.messageType??null,type:c.type??null,contentKey:c.contentKey??null,source:c.source??"unknown",updatedByUserId:c.updatedByUserId,updatedByVeltUserId:c.updatedByVeltUserId,sessionId:c.sessionId,timestamp:r}}function se(c,r){return{id:c.id,veltId:c.veltId,encryptedState:c.encryptedState,encryptedVector:c.encryptedVector,type:c.type??null,contentKey:c.contentKey??null,source:c.source??"unknown",updatedByUserId:c.updatedByUserId,updatedByVeltUserId:c.updatedByVeltUserId,sessionId:c.sessionId,timestamp:r}}function ae(c,r){return v(this,null,function*(){if(c.encryptedData){let a=yield r(c.encryptedData);if(a==null)return null;c.data=a,delete c.encryptedData}else if(!c.data)return null;return c})}function ce(c,r){return v(this,null,function*(){if(c.encryptedData){let a=yield r(c.encryptedData);return a==null?null:{data:a,yjsClientId:c.yjsClientId,timestamp:c.timestamp}}return c.data?{data:c.data,yjsClientId:c.yjsClientId,timestamp:c.timestamp}:null})}function Be(c,r){return{id:c.id,versionId:c.versionId,versionName:c.versionName,encryptedState:c.encryptedState,timestamp:r}}function Re(c,r){return v(this,null,function*(){let a=c;if(a?.encryptedState){let e=yield r(a.encryptedState);a.state=e,delete a.encryptedState}return c})}function Ke(c,r){return v(this,null,function*(){let a=null;if(c){a=[];for(let e of Object.values(c))if(e?.encryptedState){let t=yield r(e.encryptedState),n=N(E({},e),{state:t});delete n.encryptedState,a.push(n)}else a.push(e)}return a})}var ze=/^-?(0*)\d{1,10}$/,$e=-2147483648,He=2147483647,Ge=/^(0|[1-9]\d*)$/;function Ye(c){if(ze.test(c)){let r=Number(c);if(r>=$e&&r<=He)return r}return null}function Je(c,r,a,e){return c===a?0:r!==null?e!==null?r-e===0?c.length-a.length:r-e:-1:e!==null?1:c<a?-1:1}function Xe(c){if(c.length===0)return!1;for(let r=0;r<c.length;r++){if(!(r in c))return!1;let a=c[r];if(a==null||typeof a=="object")return!1}return!0}function de(c){if(c==null)return null;if(typeof c!="object"||Array.isArray(c)&&Xe(c))return c;let r=c,a=[],e=!0,t=0;for(let i of Object.keys(r)){let o=de(r[i]);o!==null&&(a.push({key:i,asInt:Ye(i),value:o}),e&&Ge.test(i)?t=Math.max(t,Number(i)):e=!1)}if(a.length===0)return null;if(e&&t<2*a.length){let i=[];for(let o of a)i[Number(o.key)]=o.value;return i}a.sort((i,o)=>Je(i.key,i.asInt,o.key,o.asInt));let n={};for(let i of a)Object.defineProperty(n,i.key,{value:i.value,enumerable:!0,writable:!0,configurable:!0});return n}var b=(()=>{let r=class r{constructor(e,t,n,i,o,s,d,l,u,h,p){this.adapterSelectorService=e,this.analyticsService=t,this.authService=n,this.commonDbService=i,this.commonDbUtilsService=o,this.configService=s,this.crdtActionsService=d,this.docService=l,this.domService=u,this.loggingService=h,this.serviceBook=p,this.MIN_WEBHOOK_DEBOUNCE_TIME=5*1e3,this.webhookDebounceTime=this.MIN_WEBHOOK_DEBOUNCE_TIME,this.updateDataWebhookTrigger$=new V,this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null,this.webhookEnabled$=new he(!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,this.portableCrdtChannels=new Map,this.portableCrdtChannelInvalidator=null;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;"),this.serviceBook.observe(Ie).subscribe(S=>{this.activityService=S}),this.serviceBook.observe(fe).subscribe(S=>{this.notificationService=S}),this.setupUpdateDataWebhookDebounce(),this.docService.addPreDocumentIdChangeFunction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve())),this.authService.addPreSignOutFuction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve()))}catch(S){this.loggingService.catch("Error in CrdtService constructor: ",S)}}trackCrdtDataUpdated(e){try{if(this.lastCrdtDataUpdatedId===e)return;this.lastCrdtDataUpdatedId=e,this.analyticsService.trackEvent(Ce.Events.Crdt.CRDT_DATA_UPDATED,{id:e})}catch(t){this.loggingService.catch("Error in CrdtService trackCrdtDataUpdated: ",t)}}setupUpdateDataWebhookDebounce(){try{this.updateDataWebhookDebounceSubscription&&(this.updateDataWebhookDebounceSubscription.unsubscribe(),this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null),this.updateDataWebhookDebounceSubscription=this.updateDataWebhookTrigger$.pipe(X(e=>{this.pendingWebhookEvent=e}),J(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(t){this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: ",t)}}updateData(i){return v(this,arguments,function*({id:e,state:t,data:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let o=this.docService.getDocumentPaths(),s=this.authService.getUser(),d=this.domService.getTabId();if(s?.userId&&o){let l=m(e),u=s.userId,h=m(s.userId),p=new Date().toISOString(),S=null,C=this.configService.getEncryptionProvider();if(C?.encrypt&&typeof C.encrypt=="function")S=yield C.encrypt({data:t});else{let D={};D.customKey=l,S=yield T.encryptData(t,D)}let f={id:e,veltId:l,encryptedState:S,lastUpdate:p,lastUpdatedBy:u,lastUpdatedByVeltUserId:h,sessionId:d},w={methodName:ee.UPDATE_DATA,uniqueId:te(),timestamp:new Date().getTime(),source:Z.INTERNAL,payload:{id:e,data:n,lastUpdatedBy:u,sessionId:d,lastUpdate:p}},k=yield this.commonDbService.updateData({feature:"crdtData",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:l,skipFirestore:!0},data:f});return this.crdtActionsService.triggerAction(Q.UPDATE_DATA,w),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(w?.payload),this.trackEditForActivity(e),k}return Promise.resolve(null)}catch(o){return this.loggingService.catch("Error in CrdtService updateData: ",o),Promise.resolve(null)}})}triggerUpdateDataWebhook(e){try{this.updateNotificationsDatabase(e,me.UPDATE_DATA)}catch(t){this.loggingService.catch("Error in CrdtService triggerUpdateDataWebhook: ",t)}}onDataChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let n=m(e),i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:n,skipFirestore:!0}}).pipe(O(s=>v(this,null,function*(){try{if(s?.data){if(s.data.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.data.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.data.encryptedState,u)}s.data.state=d,delete s.data?.encryptedState}return s}else{if(s?.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.encryptedState,u)}s.state=d,delete s?.encryptedState}return s}}catch(d){return this.loggingService.catch("Error in CrdtService onDataChange subscription: ",d),null}}))):P(null))).subscribe(o=>{o&&(o.data?t(o.data):t(o))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onDataChange: ",n),()=>{}}}getData(t){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=m(e),o=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});if(o?.encryptedState){let s=null,d=this.configService.getEncryptionProvider();if(d?.decrypt&&typeof d.decrypt=="function")s=yield d.decrypt({data:o.encryptedState});else{let l={};l.customKey=i,s=yield T.decryptData(o.encryptedState,l)}o.state=s,delete o?.encryptedState}return o}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getData: ",n),Promise.resolve(null)}})}onStateChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let n=m(e),i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:n,skipFirestore:!0}}).pipe(O(s=>v(this,null,function*(){try{if(s?.data){if(s.data.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.data.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.data.encryptedState,u)}s.data.state=d,delete s.data?.encryptedState}return s}else{if(s?.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.encryptedState,u)}s.state=d,delete s?.encryptedState}return s}}catch(d){return this.loggingService.catch("Error in CrdtService onStateChange subscription: ",d),null}}))):P(null))).subscribe(o=>{o&&(o.data?t(o.data):t(o))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onStateChange: ",n),()=>{}}}updateState(n){return v(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let i=this.docService.getDocumentPaths(),o=this.authService.getUser(),s=this.domService.getTabId();if(o?.userId&&i){let d=m(e),l=o.userId,u=m(l),h=null,p=this.configService.getEncryptionProvider();if(p?.encrypt&&typeof p.encrypt=="function")h=yield p.encrypt({data:t});else{let S={};S.customKey=d,h=yield T.encryptData(t,S)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:d,skipFirestore:!0},data:{id:e,veltId:d,encryptedState:h,lastUpdate:new Date().toISOString(),lastUpdatedBy:l,lastUpdatedByVeltUserId:u,sessionId:s}})}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService updateState: ",i),Promise.resolve(null)}})}registerSyncUser(t){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(),o=this.configService.getApiKey(),s=m(e),d=this.domService.getTabId();if(n?.userId&&i&&o){let l=n.userId,u=m(l),h={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:s,userId:u,apiKey:o,skipFirestore:!0},p={userId:l,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:h,data:p});let S=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:h,defaultDocumentPaths:i,apiKey:o});S&&(yield this.commonDbService.setupOnDisconnect(S,{status:"offline",lastSeen:new Date().getTime(),sessionId:d},"crdtSyncPresence",h))}}catch(n){this.loggingService.catch("Error in CrdtService registerSyncUser: ",n)}})}onRegisteredUserChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let n=m(e);return this.subscribeCrdtRosterFeed("allCrdtSyncPresence","onRegisteredUserChange",n,t)}catch(n){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",n),()=>{}}}subscribeCrdtRosterFeed(e,t,n,i){let o=new le(d=>M(()=>d.next(null))),s=ue([this.docService.getDocumentPaths$(),ge(P(null),o)]).pipe(O(([d])=>d?this.commonDbService.dbListener({feature:e,properties:{documentId:d?.documentId??"",organizationId:d?.organizationId??"",id:n,skipFirestore:!0}}).pipe(X(l=>{try{l?.data?i(l.data):i(l)}catch(u){this.loggingService.catch(`Error in CrdtService ${t} subscription: `,u)}})):P(null))).subscribe(()=>{});return()=>s.unsubscribe()}setPresence(t){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(),o=this.configService.getApiKey(),s=m(e),d=this.domService.getTabId();if(n?.userId&&i&&o){let l=n.userId,u=m(l),h={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:s,userId:u,apiKey:o,skipFirestore:!0},p={userId:l,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtPresence",properties:h,data:p});let S=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:h,defaultDocumentPaths:i,apiKey:o});S&&(yield this.commonDbService.setupOnDisconnect(S,{status:"offline",lastSeen:new Date().getTime(),sessionId:d},"crdtPresence",h))}}catch(n){this.loggingService.catch("Error in CrdtService setPresence: ",n)}})}onPresenceChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let n=m(e);return this.subscribeCrdtRosterFeed("allCrdtPresence","onPresenceChange",n,t)}catch(n){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",n),()=>{}}}saveVersion(o){return v(this,arguments,function*({id:e,versionId:t,versionName:n,state:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let s=this.authService.getUser()?.userId,d=this.isPortableCrdtActive()||this.shouldAwaitPortableActivation(),l=this.docService.getDocumentPaths();if(l){let u=m(e),h="",p=this.configService.getEncryptionProvider();if(p?.encrypt&&typeof p.encrypt=="function")h=yield p.encrypt({data:i});else{let C={};C.customKey=u,h=yield T.encryptData(i,C)}let S=Be({id:e,versionId:t,versionName:n,encryptedState:h},new Date().getTime());if(this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),d&&this.crdtVersionCallerChangedDuringWait("saveCrdtVersion",s))return;if(d&&this.shouldAwaitPortableActivation()){this.saveCrdtVersionOnActivation(l,u,t,S,s);return}return this.isPortableCrdtActive()?this.saveCrdtVersionOnPortable(l,u,t,S,s):this.writeCrdtVersionToCommonDb(l,u,t,S)}return Promise.resolve(null)}catch(s){return this.loggingService.catch("Error in CrdtService saveVersion: ",s),Promise.resolve(null)}})}writeCrdtVersionToCommonDb(e,t,n,i){return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:e?.documentId??"",organizationId:e?.organizationId??"",id:t,versionId:n,skipFirestore:!0},data:i})}saveCrdtVersionOnPortable(e,t,n,i,o){return v(this,null,function*(){if((yield this.callPortableCrdtVersionOp("saveCrdtVersion",N(E({},this.buildPortableCrdtVersionIdentity(e,t)),{versionId:n,record:i}),o)).outcome==="unserved")return this.writeCrdtVersionToCommonDb(e,t,n,i)})}saveCrdtVersionOnActivation(e,t,n,i,o){let s=null;s=M(()=>{if(s?.(),s=null,this.crdtVersionCallerChangedDuringWait("saveCrdtVersion",o))return;(this.isPortableCrdtActive()?this.saveCrdtVersionOnPortable(e,t,n,i,o):this.writeCrdtVersionToCommonDb(e,t,n,i)).catch(l=>this.loggingService.catch("Error in CrdtService saveVersion (sent on activation): ",l))}),this.loggingService.log(`Velt [portable backend]: CRDT named version '${n}' queued \u2014 it is sent when the portable transport registers`)}getVersion({id:e,versionId:t}){return this.readNamedCrdtVersion("getVersion",e,{op:"getCrdtVersion",feature:"crdtVersion",responseKey:"record",versionId:t},(n,i)=>Re(n,o=>this.decryptCrdtDataOrThrow(o,i)),()=>({}))}getVersions({id:e}){return this.readNamedCrdtVersion("getVersions",e,{op:"listCrdtVersions",feature:"crdtVersions",responseKey:"records"},(t,n)=>Ke(t,i=>this.decryptCrdtDataOrThrow(i,n)),()=>[])}readNamedCrdtVersion(e,t,n,i,o){return v(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: "+e,"color: green;");let s=this.authService.getUser()?.userId,d=this.isPortableCrdtActive()||this.shouldAwaitPortableActivation(),l=this.docService.getDocumentPaths();if(l){let u=m(t),h=!1;this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS),h=!0);let p=h&&this.crdtVersionCallerChangedDuringWait(n.op,s)?{}:yield this.readCrdtVersionSource(n,l,u,s),S=yield i(p,u);return d&&this.crdtVersionAnswerOutlivedCaller(n.op,s)?o():S}return Promise.resolve(null)}catch(s){return this.loggingService.catch(`Error in CrdtService ${e}: `,s),Promise.resolve(null)}})}readCrdtVersionSource(e,t,n,i){return v(this,null,function*(){let o=e.op==="getCrdtVersion";if(this.isPortableCrdtActive()){let s=this.buildPortableCrdtVersionIdentity(t,n),d=yield this.callPortableCrdtVersionOp(e.op,o?N(E({},s),{versionId:e.versionId}):s,i);if(d.outcome!=="unserved")return(d.outcome==="ok"?de(d.data?.[e.responseKey]):null)??{}}return this.commonDbService.getData({feature:e.feature,properties:N(E({documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:n},o?{versionId:e.versionId}:{}),{skipFirestore:!0})})})}buildPortableCrdtVersionIdentity(e,t){return{organizationId:e.clientOrganizationId,documentId:e.clientDocumentId,veltId:t}}callPortableCrdtVersionOp(e,t,n){return v(this,null,function*(){try{if(this.hasCrdtVersionCallerChanged(n))return this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' not sent \u2014 the signed-in user changed before it could go out`),{outcome:"stale"};let i=this.adapterSelectorService.resolveDbAdapter(),o=i[e];if(typeof o!="function")return{outcome:"unserved"};let s=yield o.call(i,{scope:"doc",data:t});if(this.hasCrdtVersionCallerChanged(n))return this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' answer discarded \u2014 the signed-in user changed while it was in flight`),{outcome:"stale"};if(s?.ok)return{outcome:"ok",data:s.data};if(Ae(s))return{outcome:"unserved"};let d=s,l=re(s)?"got no answer from the gateway, so its outcome is unknown":d?.code==="failed-precondition"&&Oe.has(String(d?.message))?"was not sent":"failed at the gateway";return this.loggingService.catch(`Velt [portable backend]: CRDT named-version operation '${e}' ${l}: `,{code:d?.code,message:d?.message}),{outcome:"refused"}}catch(i){return this.loggingService.catch(`Error in CrdtService ${e}: `,i),{outcome:"refused"}}})}crdtVersionCallerChangedDuringWait(e,t){return this.hasCrdtVersionCallerChanged(t)?(this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' not sent \u2014 the signed-in user changed during the activation wait`),!0):!1}crdtVersionAnswerOutlivedCaller(e,t){return this.hasCrdtVersionCallerChanged(t)?(this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' answer discarded \u2014 the signed-in user changed during decryption`),!0):!1}hasCrdtVersionCallerChanged(e){return(this.authService.getUser()?.userId??null)!==(e??null)}encryptCrdtData(e,t){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=t,yield T.encryptData(e,i)}catch(n){return this.loggingService.catch("Error in CrdtService encryptCrdtData: ",n),null}})}decryptCrdtData(e,t){return v(this,null,function*(){try{return yield this.decryptCrdtDataOrThrow(e,t)}catch(n){return this.loggingService.catch("Error in CrdtService decryptCrdtData: ",n),null}})}decryptCrdtDataOrThrow(e,t){return v(this,null,function*(){let n=this.configService.getEncryptionProvider();if(n?.decrypt&&typeof n.decrypt=="function")return yield n.decrypt({data:e});let i={};return i.customKey=t,yield T.decryptData(e,i)})}isPortableCrdtActive(){try{return this.adapterSelectorService.isPortableBackendActive()}catch(e){return this.loggingService.catch("Error in CrdtService isPortableCrdtActive: ",e),!1}}shouldAwaitPortableActivation(){try{return this.adapterSelectorService.isPortableBackendPending()===!0}catch(e){return this.loggingService.catch("Error in CrdtService shouldAwaitPortableActivation: ",e),!1}}buildPortableCrdtChannelKey(e){try{let t=e===void 0?this.docService.getDocumentPaths():e,n=this.configService.getApiKey();return!t?.documentId||!n?null:{scope:"doc",feature:"crdt",apiKey:n,organizationId:t.organizationId!=null&&t.organizationId!==""?String(t.organizationId):void 0,documentId:String(t.documentId)}}catch(t){return this.loggingService.catch("Error in CrdtService buildPortableCrdtChannelKey: ",t),null}}static portableCrdtChannelMapKey(e){return`${e.apiKey}:${e.organizationId??""}:${e.documentId}`}peekPortableCrdtChannel(){try{let e=this.buildPortableCrdtChannelKey(),t=e?this.portableCrdtChannels.get(r.portableCrdtChannelMapKey(e)):void 0;return e&&t?{key:e,store:t.store}:null}catch(e){return this.loggingService.catch("Error in CrdtService peekPortableCrdtChannel: ",e),null}}awaitPortableCrdtPrimedForFold(e){return v(this,null,function*(){let t;try{return yield Promise.race([e.awaitPrimed().then(()=>!0),new Promise(n=>{t=setTimeout(()=>n(!1),r.PORTABLE_ACTIVATION_WAIT_MS)})])}finally{clearTimeout(t)}})}resolvePortableCrdtFoldChannel(e){try{let t=this.buildPortableCrdtChannelKey(e),n=this.buildPortableCrdtChannelKey();if(!t||!n)return null;if(r.portableCrdtChannelMapKey(t)!==r.portableCrdtChannelMapKey(n))return this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the document changed while the snapshot was being encrypted (compaction pauses; content is unaffected)"),null;let i=this.ensurePortableCrdtChannel();return i?{key:n,store:i}:null}catch(t){return this.loggingService.catch("Error in CrdtService resolvePortableCrdtFoldChannel: ",t),null}}reportPortableCrdtFoldFailure(e){try{let t=e;if(re(e)){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold sent but not answered (${t?.message}): outcome unknown \u2014 not adopted; the log replay stays authoritative`);return}if(Ue(e)){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold not sent (${t?.message}) \u2014 compaction pauses; content is unaffected`);return}this.loggingService.catch("Velt [portable backend]: crdt snapshot fold rejected (log NOT trimmed; feed unaffected): ",e)}catch{}}ensurePortableCrdtChannel(){try{let e=this.buildPortableCrdtChannelKey();if(!e)return null;this.portableCrdtChannelInvalidator||(this.portableCrdtChannelInvalidator=M(()=>this.resubscribePortableCrdtChannels()));let t=r.portableCrdtChannelMapKey(e),n=this.portableCrdtChannels.get(t);if(n)return n.store;let i=new z,o=W("crdt")?.mode??"persistent",s=this.adapterSelectorService.resolveRealtimeAdapter().subscribe(e,o,d=>i.ingest(d),{onError:()=>i.markDenied(),onSnapshotComplete:d=>i.markPrimed(d)});return this.portableCrdtChannels.set(t,{store:i,sub:s,key:e}),i}catch(e){return this.loggingService.catch("Error in CrdtService ensurePortableCrdtChannel: ",e),null}}resubscribePortableCrdtChannels(){try{let e=W("crdt")?.mode??"persistent";for(let[t,n]of Array.from(this.portableCrdtChannels.entries())){try{n.sub?.unsubscribe()}catch(i){this.loggingService.catch("Error unsubscribing a portable CRDT channel: ",i)}try{n.store.beginEpoch(),n.sub=this.adapterSelectorService.resolveRealtimeAdapter().subscribe(n.key,e,i=>n.store.ingest(i),{onError:()=>n.store.markDenied(),onSnapshotComplete:i=>n.store.markPrimed(i)})}catch(i){this.loggingService.catch("Error re-subscribing a portable CRDT channel: ",i),n.sub=null}}}catch(e){this.loggingService.catch("Error in CrdtService resubscribePortableCrdtChannels: ",e)}}getPortableServerTimestamp(){return v(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveRealtimeAdapter().getServerTimeOffset();return Date.now()+(e??0)}catch(e){return this.loggingService.catch("Error in CrdtService getPortableServerTimestamp: ",e),Date.now()}})}decryptSnapshotRecord(e,t){return v(this,null,function*(){if(e?.encryptedState){let n=yield this.decryptCrdtData(e.encryptedState,t);if(n==null)return null;e.state=n,delete e?.encryptedState}if(e?.encryptedVector){let n=yield this.decryptCrdtData(e.encryptedVector,t);if(n==null)return null;e.vector=n,delete e?.encryptedVector}return e})}pushMessage(u){return v(this,arguments,function*({id:e,data:t,yjsClientId:n,messageType:i,eventData:o,type:s,contentKey:d,source:l}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pushMessage","color: green;");let h=this.docService.getDocumentPaths(),p=this.authService.getUser();if(p?.userId&&h){let S=m(e),C=yield this.encryptCrdtData(t,S);if(C==null)return;let f=p.userId,w=m(p.userId),k=this.domService.getTabId(),D={id:e,veltId:S,encryptedData:C,yjsClientId:n,messageType:i,type:s,contentKey:d,source:l,updatedByUserId:f,updatedByVeltUserId:w,sessionId:k};if(this.isPortableCrdtActive()){let A=this.buildPortableCrdtChannelKey(),U=oe(D,yield this.getPortableServerTimestamp()),_=A?ne(U):null;if(!A||_===null)return;let H=W("crdt")?.mode??"persistent",R=yield this.adapterSelectorService.resolveRealtimeAdapter().publish(A,H,{payloadB64:_});if(!R.ok){console.error("Velt [portable backend]: crdt update dropped: ",R);return}}else yield this.commonDbService.pushData({feature:"crdtMessages",properties:{documentId:h?.documentId??"",organizationId:h?.organizationId??"",id:S,skipFirestore:!0},data:oe(D,this.commonDbService.getServerTimestamp())});if(i==="sync"){let A=new Date().toISOString(),U={methodName:ee.UPDATE_DATA,uniqueId:te(),timestamp:new Date().getTime(),source:Z.INTERNAL,payload:{id:e,data:o,lastUpdatedBy:f,sessionId:k,lastUpdate:A}};this.crdtActionsService.triggerAction(Q.UPDATE_DATA,U),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(U?.payload),this.trackEditForActivity(e)}}}catch(h){this.loggingService.catch("Error in CrdtService pushMessage: ",h)}})}onMessage(e){return this.bindOnMessageInternal(e)}bindOnMessageInternal({id:e,callback:t,afterTs:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onMessage","color: green;");let i=m(e);if(this.isPortableCrdtActive())return this.subscribePortableCrdtMessages(i,t,n);let o=!1,s=this.subscribeFirebaseCrdtMessages(i,t,n),d=null;return d=M(()=>{try{if(o||!this.isPortableCrdtActive())return;d?.(),d=null,s(),s=this.subscribePortableCrdtMessages(i,t,n)}catch(l){this.loggingService.catch("Error rebinding CrdtService onMessage to the portable channel: ",l)}}),()=>{o=!0;try{d?.(),d=null}finally{s()}}}catch(i){return this.loggingService.catch("Error in CrdtService onMessage: ",i),()=>{}}}subscribePortableCrdtMessages(e,t,n){let i=this.ensurePortableCrdtChannel();if(!i)return()=>{};let o=new V,s=o.pipe(Y(S=>v(this,[S],function*({message:h,seq:p}){try{let C=yield ae(h,f=>this.decryptCrdtData(f,e));return C?{message:C,seq:p}:null}catch(C){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",C),null}})),j(h=>!!h)).subscribe(({message:h,seq:p})=>{try{t(h),i.markDelivered(e,p)}catch(S){this.loggingService.catch("Error in CrdtService onMessage subscription: ",S)}}),d=h=>{h.envelope.veltId===e&&(n!=null&&typeof h.envelope.timestamp=="number"&&h.envelope.timestamp<=n||o.next({message:E({},h.envelope),seq:h.seq}))};for(let h of i.entriesFor(e,n??void 0))d(h);let l=i.listen(d),u=i.listenSnapshot(h=>{let p=h.editors?.[e];p&&p.encryptedState&&o.next({message:{veltId:e,encryptedData:p.encryptedState,yjsClientId:p.yjsClientId??null,messageType:"sync",sessionId:p.sessionId,timestamp:p.timestamp},seq:0})});return()=>{l(),u(),s.unsubscribe()}}subscribeFirebaseCrdtMessages(e,t,n){let i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.streamChildAdded({feature:"crdtMessages",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:e,skipFirestore:!0},afterTs:n}):P(null))).pipe(j(o=>!!o),Y(o=>v(this,null,function*(){try{return yield ae(o,s=>this.decryptCrdtData(s,e))}catch(s){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",s),null}})),j(o=>!!o)).subscribe(o=>{try{t(o)}catch(s){this.loggingService.catch("Error in CrdtService onMessage subscription: ",s)}});return()=>i.unsubscribe()}getMessages(n){return v(this,arguments,function*({id:e,afterTs:t}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getMessages","color: green;"),this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),this.isPortableCrdtActive()){let o=m(e),s=this.ensurePortableCrdtChannel();if(!s)return[];yield s.awaitPrimed();let d=[],l=0;for(let u of s.entriesFor(o,t??void 0)){let h=yield ce(u.envelope,p=>this.decryptCrdtData(p,o));h&&(d.push(h),l=Math.max(l,u.seq))}return l>0&&s.markDelivered(o,l),d.sort((u,h)=>u.timestamp-h.timestamp),d}let i=this.docService.getDocumentPaths();if(i){let o=m(e),s=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,skipFirestore:!0}});if(!s||typeof s!="object"||s?.errorCode)return[];let d=[];for(let l of Object.keys(s)){let u=s[l];if(!u||typeof u!="object"||t!=null&&u.timestamp!=null&&u.timestamp<=t)continue;let h=yield ce(u,p=>this.decryptCrdtData(p,o));h&&d.push(h)}return d.sort((l,u)=>l.timestamp-u.timestamp),d}return[]}catch(i){return this.loggingService.catch("Error in CrdtService getMessages: ",i),[]}})}getSnapshot(t){return v(this,arguments,function*({id:e}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getSnapshot","color: green;"),this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),this.isPortableCrdtActive()){let i=m(e),o=this.ensurePortableCrdtChannel();if(!o)return null;yield o.awaitPrimed();let s=o.snapshotFor(i);return!s||Object.keys(s).length===0?null:yield this.decryptSnapshotRecord(E({},s),i)}let n=this.docService.getDocumentPaths();if(n){let i=m(e),o=yield this.commonDbService.getData({feature:"crdtSnapshot",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});return!o||typeof o!="object"||Object.keys(o).length===0||o?.errorCode?null:yield this.decryptSnapshotRecord(o,i)}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getSnapshot: ",n),Promise.resolve(null)}})}saveSnapshot(d){return v(this,arguments,function*({id:e,state:t,vector:n,type:i,contentKey:o,source:s}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveSnapshot","color: green;");let l=this.docService.getDocumentPaths(),u=this.authService.getUser();if(u?.userId&&l){let h=m(e),p=this.portableCrdtChannels.size>0?this.peekPortableCrdtChannel():null,S=p?.store.getDeliveredSeq(h)??0,C=yield this.encryptCrdtData(t,h),f=yield this.encryptCrdtData(n,h);if(C==null||f==null)return;let w=u.userId,k=m(u.userId),D=this.domService.getTabId(),A={id:e,veltId:h,encryptedState:C,encryptedVector:f,type:i,contentKey:o,source:s,updatedByUserId:w,updatedByVeltUserId:k,sessionId:D};if(this.isPortableCrdtActive()){let U=p??this.resolvePortableCrdtFoldChannel(l);if(!U)return;let{store:_,key:H}=U;if(!(yield this.awaitPortableCrdtPrimedForFold(_))){this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the channel snapshot has not arrived (compaction pauses; content is unaffected)");return}let R=se(A,yield this.getPortableServerTimestamp()),F=_.planFold(h,R,S);if(!F){this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the channel is denied or held an unreadable row (compaction pauses; log replay stays authoritative)");return}let K=ne(F.composite);if(K===null)return;if(K.length>ie){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold skipped \u2014 the composite is ${K.length} base64 characters, over the gateway's ${ie} cap (compaction pauses; content is unaffected)`);return}if(!this.authService.getUser()){this.loggingService.log("Velt [portable backend]: crdt snapshot fold not sent \u2014 no user is signed in (compaction pauses; content is unaffected)");return}let Le=W("crdt")?.mode??"persistent",G=yield this.adapterSelectorService.resolveRealtimeAdapter().publish(H,Le,{payloadB64:K,uptoSeq:F.uptoSeq});G.ok?G.seq===F.uptoSeq&&_.adoptFold(F):this.reportPortableCrdtFoldFailure(G);return}yield this.commonDbService.setData({feature:"crdtSnapshot",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:h,skipFirestore:!0},data:se(A,this.commonDbService.getServerTimestamp())})}}catch(l){this.loggingService.catch("Error in CrdtService saveSnapshot: ",l)}})}pruneMessages(n){return v(this,arguments,function*({id:e,beforeTs:t}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pruneMessages","color: green;"),this.isPortableCrdtActive()){this.loggingService.log("Velt [portable backend]: pruneMessages is a no-op (writeCrdtSnapshot folds own the trim)");return}let i=this.docService.getDocumentPaths();if(i){let o=m(e),s=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,skipFirestore:!0}});if(s&&typeof s=="object"&&!s?.errorCode){let d=[];for(let l of Object.keys(s)){let u=s[l];u?.timestamp!=null&&u.timestamp<t&&d.push(this.commonDbService.deleteData({feature:"crdtMessage",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,messageId:l,skipFirestore:!0}}))}yield Promise.all(d)}}}catch(i){this.loggingService.catch("Error in CrdtService pruneMessages: ",i)}})}updateNotificationsDatabase(e,t,n={}){try{let i=E({crdtData:e,actionType:t,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 t=this.editorEditTrackers.get(e);if(!t){let n=new V,i=n.pipe(J(this.activityDebounceTime)).subscribe(()=>{this.flushEditorActivity(e)});t={count:0,subject$:n,subscription:i},this.editorEditTrackers.set(e,t)}t.count++,t.subject$.next()}catch(t){this.loggingService.catch("Error in CrdtService trackEditForActivity: ",t)}}flushEditorActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t||t.count===0)return;let n=t.count;t.count=0;let i={featureType:"crdt",actionType:be.EDITOR_EDIT,targetEntityId:e,entityData:{editCount:n}};this.activityService?.createActivity(i)}catch(t){this.loggingService.catch("Error in CrdtService flushEditorActivity: ",t)}}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(t){this.loggingService.catch("Error in CrdtService setActivityDebounceTime: ",t)}}flushAllEditorActivities(){try{for(let[e,t]of this.editorEditTrackers)t.count>0&&this.flushEditorActivity(e),t.subject$.complete(),t.subscription.unsubscribe();this.editorEditTrackers.clear()}catch(e){this.loggingService.catch("Error in CrdtService flushAllEditorActivities: ",e)}}};r.PORTABLE_ACTIVATION_WAIT_MS=1e4,r.\u0275fac=function(t){return new(t||r)(I(Te),I(Ee),I(ke),I(Ve),I(Ne),I(Pe),I(q),I(_e),I(we),I(g),I(x))},r.\u0275prov=L({token:r,factory:r.\u0275fac,providedIn:"root"});let c=r;return c})();var $=class extends Fe{constructor(r){super(r),this.getService(g).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(r){this.getService(g).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(b).updateData(r)}catch(a){return this.getService(g).catch("Error in updateData: ",a),Promise.resolve(null)}}_onDataChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(b).onDataChange(r)}catch(a){return this.getService(g).catch("Error in onDataChange: ",a),()=>{}}}_getData(r){this.getService(g).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(b).getData(r)}catch(a){return this.getService(g).catch("Error in getData: ",a),Promise.resolve(null)}}_onStateChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(b).onStateChange(r)}catch(a){return this.getService(g).catch("Error in onStateChange: ",a),()=>{}}}_updateState(r){this.getService(g).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(b).updateState(r)}catch(a){return this.getService(g).catch("Error in updateState: ",a),Promise.resolve(null)}}_registerSyncUser(r){this.getService(g).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(b).registerSyncUser(r)}catch(a){return this.getService(g).catch("Error in registerSyncUser: ",a),Promise.resolve()}}_onRegisteredUserChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(b).onRegisteredUserChange(r)}catch(a){return this.getService(g).catch("Error in onRegisteredUserChange: ",a),()=>{}}}_setPresence(r){this.getService(g).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(b).setPresence(r)}catch(a){return this.getService(g).catch("Error in setPresence: ",a),Promise.resolve()}}_onPresenceChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(b).onPresenceChange(r)}catch(a){return this.getService(g).catch("Error in onPresenceChange: ",a),()=>{}}}_saveVersion(r){this.getService(g).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(b).saveVersion(r)}catch(a){return this.getService(g).catch("Error in saveVersion: ",a),Promise.resolve(null)}}_getVersion(r){this.getService(g).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(b).getVersion(r)}catch(a){return this.getService(g).catch("Error in getVersion: ",a),Promise.resolve(null)}}_getVersions(r){this.getService(g).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(b).getVersions(r)}catch(a){return this.getService(g).catch("Error in getVersions: ",a),Promise.resolve(null)}}_pushMessage(r){this.getService(g).log("%c[WB] Calling FUNCTION: pushMessage","color: green;");try{return this.getService(b).pushMessage(r)}catch(a){return this.getService(g).catch("Error in pushMessage: ",a),Promise.resolve()}}_onMessage(r){this.getService(g).log("%c[WB] Calling FUNCTION: onMessage","color: green;");try{return this.getService(b).onMessage(r)}catch(a){return this.getService(g).catch("Error in onMessage: ",a),()=>{}}}_getMessages(r){this.getService(g).log("%c[WB] Calling FUNCTION: getMessages","color: green;");try{return this.getService(b).getMessages(r)}catch(a){return this.getService(g).catch("Error in getMessages: ",a),Promise.resolve([])}}_getSnapshot(r){this.getService(g).log("%c[WB] Calling FUNCTION: getSnapshot","color: green;");try{return this.getService(b).getSnapshot(r)}catch(a){return this.getService(g).catch("Error in getSnapshot: ",a),Promise.resolve(null)}}_saveSnapshot(r){this.getService(g).log("%c[WB] Calling FUNCTION: saveSnapshot","color: green;");try{return this.getService(b).saveSnapshot(r)}catch(a){return this.getService(g).catch("Error in saveSnapshot: ",a),Promise.resolve()}}_pruneMessages(r){this.getService(g).log("%c[WB] Calling FUNCTION: pruneMessages","color: green;");try{return this.getService(b).pruneMessages(r)}catch(a){return this.getService(g).catch("Error in pruneMessages: ",a),Promise.resolve()}}_enableWebhook(){this.getService(g).log("%c[WB] Calling FUNCTION: enableWebhook","color: green;");try{return this.getService(b).enableWebhook()}catch(r){this.getService(g).catch("Error in enableWebhook: ",r);return}}_disableWebhook(){this.getService(g).log("%c[WB] Calling FUNCTION: disableWebhook","color: green;");try{return this.getService(b).disableWebhook()}catch(r){this.getService(g).catch("Error in disableWebhook: ",r);return}}_setWebhookDebounceTime(r){this.getService(g).log("%c[WB] Calling FUNCTION: setWebhookDebounceTime","color: green;");try{!isNaN(r)&&r>0?this.getService(b).setWebhookDebounceTime(r):this.getService(g).catch("Error in setWebhookDebounceTime: ","Provided value must be a positive number greater than zero.")}catch(a){this.getService(g).catch("Error in setWebhookDebounceTime: ",a)}}_setActivityDebounceTime(r){this.getService(g).log("%c[WB] Calling FUNCTION: setActivityDebounceTime","color: green;");try{!isNaN(r)&&r>=1e4?this.getService(b).setActivityDebounceTime(r):this.getService(g).catch("Error in setActivityDebounceTime: ","Provided value must be a number >= 10000ms (10 seconds).")}catch(a){this.getService(g).catch("Error in setActivityDebounceTime: ",a)}}_on(r){this.getService(g).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(q).onAction(r)}catch(a){return this.getService(g).catch("Error in on: ",a),P(null)}}};var je=(()=>{let r=class r{};r.\u0275fac=function(t){return new(t||r)},r.\u0275mod=Se({type:r}),r.\u0275inj=pe({imports:[ye]});let c=r;return c})();function Qe(c){return c.get(g).log("%c[WB] Loading CRDT feature chunk","color: blue;"),c.get(x).set(De,c.get(b)),ve(je,c),new $(c)}export{Qe as default};
1
+ import{a as Fe}from"./chunk-CLK24UPS.js";import{A as _e,j as Ae,v as Ne,w as re,x as Ue,y as Ve,z as Oe}from"./chunk-IH7GHE67.js";import{Ci as fe,D as ge,Dj as W,E as j,Fj as M,Gj as B,H as Y,J,Jj as Te,Me as be,Qj as we,Rc as ye,Rf as Z,Rj as ke,Sf as ee,V as O,Va as ve,Xa as Se,Y as X,Yd as y,Zf as m,a as E,b as N,ba as L,bj as Ie,ca as pe,dj as De,ea as I,fj as x,g as v,gj as Ee,hj as g,i as le,ie as Q,ij as Pe,k as V,l as he,me,r as P,sg as te,w as ue,zi as Ce}from"./chunk-XNDAIOIN.js";var q=(()=>{let r=class r{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new V),this.actionSubjects.get(e)?.next(t)}catch(n){this.loggingService.catch("Error in CrdtActionsService triggerAction: ",n)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new V);let t=this.actionSubjects.get(e);return t?t.asObservable():P(null)}catch(t){return this.loggingService.catch("Error in CrdtActionsService onAction: ",t),P(null)}}};r.\u0275fac=function(t){return new(t||r)(I(g))},r.\u0275prov=L({token:r,factory:r.\u0275fac,providedIn:"root"});let c=r;return c})();var T=(()=>{let r=class r{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 y.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,t){return v(this,null,function*(){try{if(!t){let s=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));t=new Uint8Array(s).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:t,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},i,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:t}}catch(n){return y.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 y.catch("Failed to derive key from password"),null;let{key:i,salt:o}=n;return{key:i,salt:o}}}let t=yield this.generateKey();return t?{key:t}:(y.catch("Failed to generate key"),null)}catch(t){return y.catch("Failed to resolve key: ",t),null}})}static encrypt(n){return v(this,arguments,function*(e,t={}){try{if(t.customEncryptCallback)try{return yield t.customEncryptCallback(e)}catch(h){return y.catch("Custom encryption callback failed: ",h),""}let i=yield this.resolveKey(t);if(!i)return y.catch("Failed to resolve key"),"";let{key:o,salt:s}=i,d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return y.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let l=new TextEncoder().encode(e),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let h=yield window.crypto.subtle.encrypt(u,o,l),p=new Uint8Array(d.length+h.byteLength);p.set(d,0),p.set(new Uint8Array(h),d.length);let S=8192,C=[];for(let f=0;f<p.length;f+=S){let w=p.slice(f,Math.min(f+S,p.length)),k="";for(let D=0;D<w.length;D++)k+=String.fromCharCode(w[D]);C.push(k)}return btoa(C.join(""))}catch(h){return y.catch("Encryption failed: ",h),""}}catch(i){return y.catch("Failed to encrypt: ",i),null}})}static decrypt(n){return v(this,arguments,function*(e,t={}){try{if(t.customDecryptCallback)try{return yield t.customDecryptCallback(e)}catch(h){return y.catch("Custom decryption callback failed: ",h),""}let i=yield this.resolveKey(t);if(!i)return y.catch("Failed to resolve key"),"";let{key:o}=i,s=new Uint8Array(atob(e).split("").map(h=>h.charCodeAt(0)));if(s.length<this.IV_LENGTH)return y.catch("Invalid encrypted data: Too short"),"";let d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return y.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=s.slice(0,this.IV_LENGTH);let l=s.slice(this.IV_LENGTH),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let h=yield window.crypto.subtle.decrypt(u,o,l);return new TextDecoder().decode(h)}catch(h){return y.catch("Decryption failed: ",h),""}}catch(i){return y.catch("Failed to decrypt: ",i),""}})}static encryptData(n){return v(this,arguments,function*(e,t={}){try{let i=JSON.stringify(e);return(yield this.encrypt(i,t))??""}catch(i){return y.catch("Failed to encrypt data: ",i),""}})}static decryptData(n){return v(this,arguments,function*(e,t={}){try{let i=yield this.decrypt(e,t);return JSON.parse(i)}catch(i){return y.catch("Failed to decrypt data: ",i),null}})}};r.IV_LENGTH=12,r.SALT_LENGTH=16,r.PBKDF2_ITERATIONS=1e5,r.KEY_LENGTH=256;let c=r;return c})();var ie=16777216;function ne(c){try{let r=new TextEncoder().encode(JSON.stringify(c)),a="";for(let e=0;e<r.length;e+=32768)a+=String.fromCharCode(...r.subarray(e,e+32768));return btoa(a)}catch(r){return y.catch("Error in wrapCrdtPayload: ",r),null}}function Me(c){try{let r=atob(c),a=new Uint8Array(r.length);for(let t=0;t<r.length;t++)a[t]=r.charCodeAt(t);let e=JSON.parse(new TextDecoder().decode(a));return e!==null&&typeof e=="object"?e:null}catch{return null}}var z=class{constructor(){this.log=[],this.logSeqs=new Set,this.fullReplayInProgress=!1,this.composite=null,this.compositeUptoSeq=0,this.listeners=new Set,this.snapshotListeners=new Set,this.denied=!1,this.primed=!1,this.primedWaiters=[],this.deliveredSeq=new Map,this.foldUnsafe=!1}ingest(r){try{if(this.denied)return;if(r?.type==="removed"){r.snapshot==="full"&&this.beginFullReplay();return}if(r?.snapshot==="full"?this.beginFullReplay():this.fullReplayInProgress=!1,r?.id==="snapshot"){let i=r.data,o=typeof i?.payloadB64=="string"?Me(i.payloadB64):null;if(o&&o.version===1&&o.editors&&typeof o.editors=="object"?this.composite=o:o!==null?(this.foldUnsafe=!0,y.catch("CrdtPortableChannelStore: unrecognized composite snapshot shape \u2014 ignored (folds disabled)",void 0)):typeof i?.payloadB64=="string"&&(this.foldUnsafe=!0),this.compositeUptoSeq=Number.isInteger(i?.uptoSeq)?i.uptoSeq:0,this.composite)for(let s of this.snapshotListeners)try{s(this.composite,this.compositeUptoSeq)}catch(d){y.catch("Error in CrdtPortableChannelStore snapshot listener: ",d)}return}let a=Number.isInteger(r?.seq)?r.seq:Number(r?.id);if(!Number.isFinite(a)){this.foldUnsafe=!0;return}if(this.logSeqs.has(a))return;let e=r.data?.payloadB64,t=typeof e=="string"?Me(e):null;if(t===null){this.foldUnsafe=!0,y.catch(`CrdtPortableChannelStore: dropping malformed crdt item seq=${a} (folds disabled)`,void 0);return}(typeof t.veltId!="string"||t.veltId.length===0)&&(this.foldUnsafe=!0);let n={seq:a,envelope:t};this.insertInSeqOrder(n);for(let i of this.listeners)try{i(n)}catch(o){y.catch("Error in CrdtPortableChannelStore listener: ",o)}}catch(a){y.catch("Error in CrdtPortableChannelStore ingest: ",a)}}markDenied(){this.denied=!0,this.fullReplayInProgress=!1,this.resetLog(),this.composite=null,this.compositeUptoSeq=0,this.markPrimed()}beginEpoch(){this.primed=!1,this.denied=!1,this.fullReplayInProgress=!1}markPrimed(r){r?.full===!0&&this.beginFullReplay(),this.primed=!0,this.fullReplayInProgress=!1;let a=this.primedWaiters;this.primedWaiters=[];for(let e of a)try{e()}catch(t){y.catch("Error in CrdtPortableChannelStore primed waiter: ",t)}}awaitPrimed(){return this.primed?Promise.resolve():new Promise(r=>this.primedWaiters.push(r))}markDelivered(r,a){Number.isFinite(a)&&a>(this.deliveredSeq.get(r)??0)&&this.deliveredSeq.set(r,a)}getDeliveredSeq(r){return this.deliveredSeq.get(r)??0}planFold(r,a,e){if(this.denied||!this.primed||this.foldUnsafe)return null;let t=1/0;for(let n of this.log)if(n.seq>this.compositeUptoSeq&&n.envelope.veltId!==r){t=n.seq-1;break}return{composite:{version:1,editors:N(E({},this.composite?.editors??{}),{[r]:a})},uptoSeq:Math.max(this.compositeUptoSeq,Math.min(e,t))}}adoptFold(r){this.denied||r.uptoSeq<this.compositeUptoSeq||(this.composite=r.composite,this.compositeUptoSeq=r.uptoSeq)}listen(r){return this.listeners.add(r),()=>this.listeners.delete(r)}listenSnapshot(r){return this.snapshotListeners.add(r),()=>this.snapshotListeners.delete(r)}entriesFor(r,a){return this.log.filter(e=>e.envelope.veltId===r&&(a===void 0||typeof e.envelope.timestamp!="number"||e.envelope.timestamp>a))}snapshotFor(r){return this.composite?.editors?.[r]??null}beginFullReplay(){this.fullReplayInProgress||(this.fullReplayInProgress=!0,this.resetLog(),this.composite=null,this.compositeUptoSeq=0)}insertInSeqOrder(r){this.logSeqs.add(r.seq);let a=this.log.length;for(;a>0&&this.log[a-1].seq>r.seq;)a--;this.log.splice(a,0,r)}resetLog(){this.log=[],this.logSeqs.clear()}};function oe(c,r){return{id:c.id,veltId:c.veltId,encryptedData:c.encryptedData,yjsClientId:c.yjsClientId,messageType:c.messageType??null,type:c.type??null,contentKey:c.contentKey??null,source:c.source??"unknown",updatedByUserId:c.updatedByUserId,updatedByVeltUserId:c.updatedByVeltUserId,sessionId:c.sessionId,timestamp:r}}function se(c,r){return{id:c.id,veltId:c.veltId,encryptedState:c.encryptedState,encryptedVector:c.encryptedVector,type:c.type??null,contentKey:c.contentKey??null,source:c.source??"unknown",updatedByUserId:c.updatedByUserId,updatedByVeltUserId:c.updatedByVeltUserId,sessionId:c.sessionId,timestamp:r}}function ae(c,r){return v(this,null,function*(){if(c.encryptedData){let a=yield r(c.encryptedData);if(a==null)return null;c.data=a,delete c.encryptedData}else if(!c.data)return null;return c})}function ce(c,r){return v(this,null,function*(){if(c.encryptedData){let a=yield r(c.encryptedData);return a==null?null:{data:a,yjsClientId:c.yjsClientId,timestamp:c.timestamp}}return c.data?{data:c.data,yjsClientId:c.yjsClientId,timestamp:c.timestamp}:null})}function Be(c,r){return{id:c.id,versionId:c.versionId,versionName:c.versionName,encryptedState:c.encryptedState,timestamp:r}}function Re(c,r){return v(this,null,function*(){let a=c;if(a?.encryptedState){let e=yield r(a.encryptedState);a.state=e,delete a.encryptedState}return c})}function Ke(c,r){return v(this,null,function*(){let a=null;if(c){a=[];for(let e of Object.values(c))if(e?.encryptedState){let t=yield r(e.encryptedState),n=N(E({},e),{state:t});delete n.encryptedState,a.push(n)}else a.push(e)}return a})}var ze=/^-?(0*)\d{1,10}$/,$e=-2147483648,He=2147483647,Ge=/^(0|[1-9]\d*)$/;function Ye(c){if(ze.test(c)){let r=Number(c);if(r>=$e&&r<=He)return r}return null}function Je(c,r,a,e){return c===a?0:r!==null?e!==null?r-e===0?c.length-a.length:r-e:-1:e!==null?1:c<a?-1:1}function Xe(c){if(c.length===0)return!1;for(let r=0;r<c.length;r++){if(!(r in c))return!1;let a=c[r];if(a==null||typeof a=="object")return!1}return!0}function de(c){if(c==null)return null;if(typeof c!="object"||Array.isArray(c)&&Xe(c))return c;let r=c,a=[],e=!0,t=0;for(let i of Object.keys(r)){let o=de(r[i]);o!==null&&(a.push({key:i,asInt:Ye(i),value:o}),e&&Ge.test(i)?t=Math.max(t,Number(i)):e=!1)}if(a.length===0)return null;if(e&&t<2*a.length){let i=[];for(let o of a)i[Number(o.key)]=o.value;return i}a.sort((i,o)=>Je(i.key,i.asInt,o.key,o.asInt));let n={};for(let i of a)Object.defineProperty(n,i.key,{value:i.value,enumerable:!0,writable:!0,configurable:!0});return n}var b=(()=>{let r=class r{constructor(e,t,n,i,o,s,d,l,u,h,p){this.adapterSelectorService=e,this.analyticsService=t,this.authService=n,this.commonDbService=i,this.commonDbUtilsService=o,this.configService=s,this.crdtActionsService=d,this.docService=l,this.domService=u,this.loggingService=h,this.serviceBook=p,this.MIN_WEBHOOK_DEBOUNCE_TIME=5*1e3,this.webhookDebounceTime=this.MIN_WEBHOOK_DEBOUNCE_TIME,this.updateDataWebhookTrigger$=new V,this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null,this.webhookEnabled$=new he(!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,this.portableCrdtChannels=new Map,this.portableCrdtChannelInvalidator=null;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;"),this.serviceBook.observe(Ie).subscribe(S=>{this.activityService=S}),this.serviceBook.observe(fe).subscribe(S=>{this.notificationService=S}),this.setupUpdateDataWebhookDebounce(),this.docService.addPreDocumentIdChangeFunction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve())),this.authService.addPreSignOutFuction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve()))}catch(S){this.loggingService.catch("Error in CrdtService constructor: ",S)}}trackCrdtDataUpdated(e){try{if(this.lastCrdtDataUpdatedId===e)return;this.lastCrdtDataUpdatedId=e,this.analyticsService.trackEvent(Ce.Events.Crdt.CRDT_DATA_UPDATED,{id:e})}catch(t){this.loggingService.catch("Error in CrdtService trackCrdtDataUpdated: ",t)}}setupUpdateDataWebhookDebounce(){try{this.updateDataWebhookDebounceSubscription&&(this.updateDataWebhookDebounceSubscription.unsubscribe(),this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null),this.updateDataWebhookDebounceSubscription=this.updateDataWebhookTrigger$.pipe(X(e=>{this.pendingWebhookEvent=e}),J(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(t){this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: ",t)}}updateData(i){return v(this,arguments,function*({id:e,state:t,data:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let o=this.docService.getDocumentPaths(),s=this.authService.getUser(),d=this.domService.getTabId();if(s?.userId&&o){let l=m(e),u=s.userId,h=m(s.userId),p=new Date().toISOString(),S=null,C=this.configService.getEncryptionProvider();if(C?.encrypt&&typeof C.encrypt=="function")S=yield C.encrypt({data:t});else{let D={};D.customKey=l,S=yield T.encryptData(t,D)}let f={id:e,veltId:l,encryptedState:S,lastUpdate:p,lastUpdatedBy:u,lastUpdatedByVeltUserId:h,sessionId:d},w={methodName:ee.UPDATE_DATA,uniqueId:te(),timestamp:new Date().getTime(),source:Z.INTERNAL,payload:{id:e,data:n,lastUpdatedBy:u,sessionId:d,lastUpdate:p}},k=yield this.commonDbService.updateData({feature:"crdtData",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:l,skipFirestore:!0},data:f});return this.crdtActionsService.triggerAction(Q.UPDATE_DATA,w),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(w?.payload),this.trackEditForActivity(e),k}return Promise.resolve(null)}catch(o){return this.loggingService.catch("Error in CrdtService updateData: ",o),Promise.resolve(null)}})}triggerUpdateDataWebhook(e){try{this.updateNotificationsDatabase(e,me.UPDATE_DATA)}catch(t){this.loggingService.catch("Error in CrdtService triggerUpdateDataWebhook: ",t)}}onDataChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let n=m(e),i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:n,skipFirestore:!0}}).pipe(O(s=>v(this,null,function*(){try{if(s?.data){if(s.data.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.data.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.data.encryptedState,u)}s.data.state=d,delete s.data?.encryptedState}return s}else{if(s?.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.encryptedState,u)}s.state=d,delete s?.encryptedState}return s}}catch(d){return this.loggingService.catch("Error in CrdtService onDataChange subscription: ",d),null}}))):P(null))).subscribe(o=>{o&&(o.data?t(o.data):t(o))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onDataChange: ",n),()=>{}}}getData(t){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=m(e),o=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});if(o?.encryptedState){let s=null,d=this.configService.getEncryptionProvider();if(d?.decrypt&&typeof d.decrypt=="function")s=yield d.decrypt({data:o.encryptedState});else{let l={};l.customKey=i,s=yield T.decryptData(o.encryptedState,l)}o.state=s,delete o?.encryptedState}return o}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getData: ",n),Promise.resolve(null)}})}onStateChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let n=m(e),i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:n,skipFirestore:!0}}).pipe(O(s=>v(this,null,function*(){try{if(s?.data){if(s.data.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.data.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.data.encryptedState,u)}s.data.state=d,delete s.data?.encryptedState}return s}else{if(s?.encryptedState){let d=null,l=this.configService.getEncryptionProvider();if(l?.decrypt&&typeof l.decrypt=="function")d=yield l.decrypt({data:s.encryptedState});else{let u={};u.customKey=n,d=yield T.decryptData(s.encryptedState,u)}s.state=d,delete s?.encryptedState}return s}}catch(d){return this.loggingService.catch("Error in CrdtService onStateChange subscription: ",d),null}}))):P(null))).subscribe(o=>{o&&(o.data?t(o.data):t(o))});return()=>i.unsubscribe()}catch(n){return this.loggingService.catch("Error in CrdtService onStateChange: ",n),()=>{}}}updateState(n){return v(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let i=this.docService.getDocumentPaths(),o=this.authService.getUser(),s=this.domService.getTabId();if(o?.userId&&i){let d=m(e),l=o.userId,u=m(l),h=null,p=this.configService.getEncryptionProvider();if(p?.encrypt&&typeof p.encrypt=="function")h=yield p.encrypt({data:t});else{let S={};S.customKey=d,h=yield T.encryptData(t,S)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:d,skipFirestore:!0},data:{id:e,veltId:d,encryptedState:h,lastUpdate:new Date().toISOString(),lastUpdatedBy:l,lastUpdatedByVeltUserId:u,sessionId:s}})}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService updateState: ",i),Promise.resolve(null)}})}registerSyncUser(t){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(),o=this.configService.getApiKey(),s=m(e),d=this.domService.getTabId();if(n?.userId&&i&&o){let l=n.userId,u=m(l),h={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:s,userId:u,apiKey:o,skipFirestore:!0},p={userId:l,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:h,data:p});let S=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:h,defaultDocumentPaths:i,apiKey:o});S&&(yield this.commonDbService.setupOnDisconnect(S,{status:"offline",lastSeen:new Date().getTime(),sessionId:d},"crdtSyncPresence",h))}}catch(n){this.loggingService.catch("Error in CrdtService registerSyncUser: ",n)}})}onRegisteredUserChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let n=m(e);return this.subscribeCrdtRosterFeed("allCrdtSyncPresence","onRegisteredUserChange",n,t)}catch(n){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",n),()=>{}}}subscribeCrdtRosterFeed(e,t,n,i){let o=new le(d=>M(()=>d.next(null))),s=ue([this.docService.getDocumentPaths$(),ge(P(null),o)]).pipe(O(([d])=>d?this.commonDbService.dbListener({feature:e,properties:{documentId:d?.documentId??"",organizationId:d?.organizationId??"",id:n,skipFirestore:!0}}).pipe(X(l=>{try{l?.data?i(l.data):i(l)}catch(u){this.loggingService.catch(`Error in CrdtService ${t} subscription: `,u)}})):P(null))).subscribe(()=>{});return()=>s.unsubscribe()}setPresence(t){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(),o=this.configService.getApiKey(),s=m(e),d=this.domService.getTabId();if(n?.userId&&i&&o){let l=n.userId,u=m(l),h={documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:s,userId:u,apiKey:o,skipFirestore:!0},p={userId:l,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtPresence",properties:h,data:p});let S=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:h,defaultDocumentPaths:i,apiKey:o});S&&(yield this.commonDbService.setupOnDisconnect(S,{status:"offline",lastSeen:new Date().getTime(),sessionId:d},"crdtPresence",h))}}catch(n){this.loggingService.catch("Error in CrdtService setPresence: ",n)}})}onPresenceChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let n=m(e);return this.subscribeCrdtRosterFeed("allCrdtPresence","onPresenceChange",n,t)}catch(n){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",n),()=>{}}}saveVersion(o){return v(this,arguments,function*({id:e,versionId:t,versionName:n,state:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let s=this.authService.getUser()?.userId,d=this.isPortableCrdtActive()||this.shouldAwaitPortableActivation(),l=this.docService.getDocumentPaths();if(l){let u=m(e),h="",p=this.configService.getEncryptionProvider();if(p?.encrypt&&typeof p.encrypt=="function")h=yield p.encrypt({data:i});else{let C={};C.customKey=u,h=yield T.encryptData(i,C)}let S=Be({id:e,versionId:t,versionName:n,encryptedState:h},new Date().getTime());if(this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),d&&this.crdtVersionCallerChangedDuringWait("saveCrdtVersion",s))return;if(d&&this.shouldAwaitPortableActivation()){this.saveCrdtVersionOnActivation(l,u,t,S,s);return}return this.isPortableCrdtActive()?this.saveCrdtVersionOnPortable(l,u,t,S,s):this.writeCrdtVersionToCommonDb(l,u,t,S)}return Promise.resolve(null)}catch(s){return this.loggingService.catch("Error in CrdtService saveVersion: ",s),Promise.resolve(null)}})}writeCrdtVersionToCommonDb(e,t,n,i){return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:e?.documentId??"",organizationId:e?.organizationId??"",id:t,versionId:n,skipFirestore:!0},data:i})}saveCrdtVersionOnPortable(e,t,n,i,o){return v(this,null,function*(){if((yield this.callPortableCrdtVersionOp("saveCrdtVersion",N(E({},this.buildPortableCrdtVersionIdentity(e,t)),{versionId:n,record:i}),o)).outcome==="unserved")return this.writeCrdtVersionToCommonDb(e,t,n,i)})}saveCrdtVersionOnActivation(e,t,n,i,o){let s=null;s=M(()=>{if(s?.(),s=null,this.crdtVersionCallerChangedDuringWait("saveCrdtVersion",o))return;(this.isPortableCrdtActive()?this.saveCrdtVersionOnPortable(e,t,n,i,o):this.writeCrdtVersionToCommonDb(e,t,n,i)).catch(l=>this.loggingService.catch("Error in CrdtService saveVersion (sent on activation): ",l))}),this.loggingService.log(`Velt [portable backend]: CRDT named version '${n}' queued \u2014 it is sent when the portable transport registers`)}getVersion({id:e,versionId:t}){return this.readNamedCrdtVersion("getVersion",e,{op:"getCrdtVersion",feature:"crdtVersion",responseKey:"record",versionId:t},(n,i)=>Re(n,o=>this.decryptCrdtDataOrThrow(o,i)),()=>({}))}getVersions({id:e}){return this.readNamedCrdtVersion("getVersions",e,{op:"listCrdtVersions",feature:"crdtVersions",responseKey:"records"},(t,n)=>Ke(t,i=>this.decryptCrdtDataOrThrow(i,n)),()=>[])}readNamedCrdtVersion(e,t,n,i,o){return v(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: "+e,"color: green;");let s=this.authService.getUser()?.userId,d=this.isPortableCrdtActive()||this.shouldAwaitPortableActivation(),l=this.docService.getDocumentPaths();if(l){let u=m(t),h=!1;this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS),h=!0);let p=h&&this.crdtVersionCallerChangedDuringWait(n.op,s)?{}:yield this.readCrdtVersionSource(n,l,u,s),S=yield i(p,u);return d&&this.crdtVersionAnswerOutlivedCaller(n.op,s)?o():S}return Promise.resolve(null)}catch(s){return this.loggingService.catch(`Error in CrdtService ${e}: `,s),Promise.resolve(null)}})}readCrdtVersionSource(e,t,n,i){return v(this,null,function*(){let o=e.op==="getCrdtVersion";if(this.isPortableCrdtActive()){let s=this.buildPortableCrdtVersionIdentity(t,n),d=yield this.callPortableCrdtVersionOp(e.op,o?N(E({},s),{versionId:e.versionId}):s,i);if(d.outcome!=="unserved")return(d.outcome==="ok"?de(d.data?.[e.responseKey]):null)??{}}return this.commonDbService.getData({feature:e.feature,properties:N(E({documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:n},o?{versionId:e.versionId}:{}),{skipFirestore:!0})})})}buildPortableCrdtVersionIdentity(e,t){return{organizationId:e.clientOrganizationId,documentId:e.clientDocumentId,veltId:t}}callPortableCrdtVersionOp(e,t,n){return v(this,null,function*(){try{if(this.hasCrdtVersionCallerChanged(n))return this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' not sent \u2014 the signed-in user changed before it could go out`),{outcome:"stale"};let i=this.adapterSelectorService.resolveDbAdapter(),o=i[e];if(typeof o!="function")return{outcome:"unserved"};let s=yield o.call(i,{scope:"doc",data:t});if(this.hasCrdtVersionCallerChanged(n))return this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' answer discarded \u2014 the signed-in user changed while it was in flight`),{outcome:"stale"};if(s?.ok)return{outcome:"ok",data:s.data};if(Ae(s))return{outcome:"unserved"};let d=s,l=re(s)?"got no answer from the gateway, so its outcome is unknown":d?.code==="failed-precondition"&&Oe.has(String(d?.message))?"was not sent":"failed at the gateway";return this.loggingService.catch(`Velt [portable backend]: CRDT named-version operation '${e}' ${l}: `,{code:d?.code,message:d?.message}),{outcome:"refused"}}catch(i){return this.loggingService.catch(`Error in CrdtService ${e}: `,i),{outcome:"refused"}}})}crdtVersionCallerChangedDuringWait(e,t){return this.hasCrdtVersionCallerChanged(t)?(this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' not sent \u2014 the signed-in user changed during the activation wait`),!0):!1}crdtVersionAnswerOutlivedCaller(e,t){return this.hasCrdtVersionCallerChanged(t)?(this.loggingService.log(`Velt [portable backend]: CRDT named-version operation '${e}' answer discarded \u2014 the signed-in user changed during decryption`),!0):!1}hasCrdtVersionCallerChanged(e){return(this.authService.getUser()?.userId??null)!==(e??null)}encryptCrdtData(e,t){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=t,yield T.encryptData(e,i)}catch(n){return this.loggingService.catch("Error in CrdtService encryptCrdtData: ",n),null}})}decryptCrdtData(e,t){return v(this,null,function*(){try{return yield this.decryptCrdtDataOrThrow(e,t)}catch(n){return this.loggingService.catch("Error in CrdtService decryptCrdtData: ",n),null}})}decryptCrdtDataOrThrow(e,t){return v(this,null,function*(){let n=this.configService.getEncryptionProvider();if(n?.decrypt&&typeof n.decrypt=="function")return yield n.decrypt({data:e});let i={};return i.customKey=t,yield T.decryptData(e,i)})}isPortableCrdtActive(){try{return this.adapterSelectorService.isPortableBackendActive()}catch(e){return this.loggingService.catch("Error in CrdtService isPortableCrdtActive: ",e),!1}}shouldAwaitPortableActivation(){try{return this.adapterSelectorService.isPortableBackendPending()===!0}catch(e){return this.loggingService.catch("Error in CrdtService shouldAwaitPortableActivation: ",e),!1}}buildPortableCrdtChannelKey(e){try{let t=e===void 0?this.docService.getDocumentPaths():e,n=this.configService.getApiKey();return!t?.documentId||!n?null:{scope:"doc",feature:"crdt",apiKey:n,organizationId:t.organizationId!=null&&t.organizationId!==""?String(t.organizationId):void 0,documentId:String(t.documentId)}}catch(t){return this.loggingService.catch("Error in CrdtService buildPortableCrdtChannelKey: ",t),null}}static portableCrdtChannelMapKey(e){return`${e.apiKey}:${e.organizationId??""}:${e.documentId}`}peekPortableCrdtChannel(){try{let e=this.buildPortableCrdtChannelKey(),t=e?this.portableCrdtChannels.get(r.portableCrdtChannelMapKey(e)):void 0;return e&&t?{key:e,store:t.store}:null}catch(e){return this.loggingService.catch("Error in CrdtService peekPortableCrdtChannel: ",e),null}}awaitPortableCrdtPrimedForFold(e){return v(this,null,function*(){let t;try{return yield Promise.race([e.awaitPrimed().then(()=>!0),new Promise(n=>{t=setTimeout(()=>n(!1),r.PORTABLE_ACTIVATION_WAIT_MS)})])}finally{clearTimeout(t)}})}resolvePortableCrdtFoldChannel(e){try{let t=this.buildPortableCrdtChannelKey(e),n=this.buildPortableCrdtChannelKey();if(!t||!n)return null;if(r.portableCrdtChannelMapKey(t)!==r.portableCrdtChannelMapKey(n))return this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the document changed while the snapshot was being encrypted (compaction pauses; content is unaffected)"),null;let i=this.ensurePortableCrdtChannel();return i?{key:n,store:i}:null}catch(t){return this.loggingService.catch("Error in CrdtService resolvePortableCrdtFoldChannel: ",t),null}}reportPortableCrdtFoldFailure(e){try{let t=e;if(re(e)){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold sent but not answered (${t?.message}): outcome unknown \u2014 not adopted; the log replay stays authoritative`);return}if(Ue(e)){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold not sent (${t?.message}) \u2014 compaction pauses; content is unaffected`);return}this.loggingService.catch("Velt [portable backend]: crdt snapshot fold rejected (log NOT trimmed; feed unaffected): ",e)}catch{}}ensurePortableCrdtChannel(){try{let e=this.buildPortableCrdtChannelKey();if(!e)return null;this.portableCrdtChannelInvalidator||(this.portableCrdtChannelInvalidator=M(()=>this.resubscribePortableCrdtChannels()));let t=r.portableCrdtChannelMapKey(e),n=this.portableCrdtChannels.get(t);if(n)return n.store;let i=new z,o=W("crdt")?.mode??"persistent",s=this.adapterSelectorService.resolveRealtimeAdapter().subscribe(e,o,d=>i.ingest(d),{onError:()=>i.markDenied(),onSnapshotComplete:d=>i.markPrimed(d)});return this.portableCrdtChannels.set(t,{store:i,sub:s,key:e}),i}catch(e){return this.loggingService.catch("Error in CrdtService ensurePortableCrdtChannel: ",e),null}}resubscribePortableCrdtChannels(){try{let e=W("crdt")?.mode??"persistent";for(let[t,n]of Array.from(this.portableCrdtChannels.entries())){try{n.sub?.unsubscribe()}catch(i){this.loggingService.catch("Error unsubscribing a portable CRDT channel: ",i)}try{n.store.beginEpoch(),n.sub=this.adapterSelectorService.resolveRealtimeAdapter().subscribe(n.key,e,i=>n.store.ingest(i),{onError:()=>n.store.markDenied(),onSnapshotComplete:i=>n.store.markPrimed(i)})}catch(i){this.loggingService.catch("Error re-subscribing a portable CRDT channel: ",i),n.sub=null}}}catch(e){this.loggingService.catch("Error in CrdtService resubscribePortableCrdtChannels: ",e)}}getPortableServerTimestamp(){return v(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveRealtimeAdapter().getServerTimeOffset();return Date.now()+(e??0)}catch(e){return this.loggingService.catch("Error in CrdtService getPortableServerTimestamp: ",e),Date.now()}})}decryptSnapshotRecord(e,t){return v(this,null,function*(){if(e?.encryptedState){let n=yield this.decryptCrdtData(e.encryptedState,t);if(n==null)return null;e.state=n,delete e?.encryptedState}if(e?.encryptedVector){let n=yield this.decryptCrdtData(e.encryptedVector,t);if(n==null)return null;e.vector=n,delete e?.encryptedVector}return e})}pushMessage(u){return v(this,arguments,function*({id:e,data:t,yjsClientId:n,messageType:i,eventData:o,type:s,contentKey:d,source:l}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pushMessage","color: green;");let h=this.docService.getDocumentPaths(),p=this.authService.getUser();if(p?.userId&&h){let S=m(e),C=yield this.encryptCrdtData(t,S);if(C==null)return;let f=p.userId,w=m(p.userId),k=this.domService.getTabId(),D={id:e,veltId:S,encryptedData:C,yjsClientId:n,messageType:i,type:s,contentKey:d,source:l,updatedByUserId:f,updatedByVeltUserId:w,sessionId:k};if(this.isPortableCrdtActive()){let A=this.buildPortableCrdtChannelKey(),U=oe(D,yield this.getPortableServerTimestamp()),_=A?ne(U):null;if(!A||_===null)return;let H=W("crdt")?.mode??"persistent",R=yield this.adapterSelectorService.resolveRealtimeAdapter().publish(A,H,{payloadB64:_});if(!R.ok){console.error("Velt [portable backend]: crdt update dropped: ",R);return}}else yield this.commonDbService.pushData({feature:"crdtMessages",properties:{documentId:h?.documentId??"",organizationId:h?.organizationId??"",id:S,skipFirestore:!0},data:oe(D,this.commonDbService.getServerTimestamp())});if(i==="sync"){let A=new Date().toISOString(),U={methodName:ee.UPDATE_DATA,uniqueId:te(),timestamp:new Date().getTime(),source:Z.INTERNAL,payload:{id:e,data:o,lastUpdatedBy:f,sessionId:k,lastUpdate:A}};this.crdtActionsService.triggerAction(Q.UPDATE_DATA,U),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(U?.payload),this.trackEditForActivity(e)}}}catch(h){this.loggingService.catch("Error in CrdtService pushMessage: ",h)}})}onMessage(e){return this.bindOnMessageInternal(e)}bindOnMessageInternal({id:e,callback:t,afterTs:n}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onMessage","color: green;");let i=m(e);if(this.isPortableCrdtActive())return this.subscribePortableCrdtMessages(i,t,n);let o=!1,s=this.subscribeFirebaseCrdtMessages(i,t,n),d=null;return d=M(()=>{try{if(o||!this.isPortableCrdtActive())return;d?.(),d=null,s(),s=this.subscribePortableCrdtMessages(i,t,n)}catch(l){this.loggingService.catch("Error rebinding CrdtService onMessage to the portable channel: ",l)}}),()=>{o=!0;try{d?.(),d=null}finally{s()}}}catch(i){return this.loggingService.catch("Error in CrdtService onMessage: ",i),()=>{}}}subscribePortableCrdtMessages(e,t,n){let i=this.ensurePortableCrdtChannel();if(!i)return()=>{};let o=new V,s=o.pipe(Y(S=>v(this,[S],function*({message:h,seq:p}){try{let C=yield ae(h,f=>this.decryptCrdtData(f,e));return C?{message:C,seq:p}:null}catch(C){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",C),null}})),j(h=>!!h)).subscribe(({message:h,seq:p})=>{try{t(h),i.markDelivered(e,p)}catch(S){this.loggingService.catch("Error in CrdtService onMessage subscription: ",S)}}),d=h=>{h.envelope.veltId===e&&(n!=null&&typeof h.envelope.timestamp=="number"&&h.envelope.timestamp<=n||o.next({message:E({},h.envelope),seq:h.seq}))};for(let h of i.entriesFor(e,n??void 0))d(h);let l=i.listen(d),u=i.listenSnapshot(h=>{let p=h.editors?.[e];p&&p.encryptedState&&o.next({message:{veltId:e,encryptedData:p.encryptedState,yjsClientId:p.yjsClientId??null,messageType:"sync",sessionId:p.sessionId,timestamp:p.timestamp},seq:0})});return()=>{l(),u(),s.unsubscribe()}}subscribeFirebaseCrdtMessages(e,t,n){let i=this.docService.getDocumentPaths$().pipe(O(o=>o?this.commonDbService.streamChildAdded({feature:"crdtMessages",properties:{documentId:o?.documentId??"",organizationId:o?.organizationId??"",id:e,skipFirestore:!0},afterTs:n}):P(null))).pipe(j(o=>!!o),Y(o=>v(this,null,function*(){try{return yield ae(o,s=>this.decryptCrdtData(s,e))}catch(s){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",s),null}})),j(o=>!!o)).subscribe(o=>{try{t(o)}catch(s){this.loggingService.catch("Error in CrdtService onMessage subscription: ",s)}});return()=>i.unsubscribe()}getMessages(n){return v(this,arguments,function*({id:e,afterTs:t}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getMessages","color: green;"),this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),this.isPortableCrdtActive()){let o=m(e),s=this.ensurePortableCrdtChannel();if(!s)return[];yield s.awaitPrimed();let d=[],l=0;for(let u of s.entriesFor(o,t??void 0)){let h=yield ce(u.envelope,p=>this.decryptCrdtData(p,o));h&&(d.push(h),l=Math.max(l,u.seq))}return l>0&&s.markDelivered(o,l),d.sort((u,h)=>u.timestamp-h.timestamp),d}let i=this.docService.getDocumentPaths();if(i){let o=m(e),s=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,skipFirestore:!0}});if(!s||typeof s!="object"||s?.errorCode)return[];let d=[];for(let l of Object.keys(s)){let u=s[l];if(!u||typeof u!="object"||t!=null&&u.timestamp!=null&&u.timestamp<=t)continue;let h=yield ce(u,p=>this.decryptCrdtData(p,o));h&&d.push(h)}return d.sort((l,u)=>l.timestamp-u.timestamp),d}return[]}catch(i){return this.loggingService.catch("Error in CrdtService getMessages: ",i),[]}})}getSnapshot(t){return v(this,arguments,function*({id:e}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getSnapshot","color: green;"),this.shouldAwaitPortableActivation()&&(yield B(r.PORTABLE_ACTIVATION_WAIT_MS)),this.isPortableCrdtActive()){let i=m(e),o=this.ensurePortableCrdtChannel();if(!o)return null;yield o.awaitPrimed();let s=o.snapshotFor(i);return!s||Object.keys(s).length===0?null:yield this.decryptSnapshotRecord(E({},s),i)}let n=this.docService.getDocumentPaths();if(n){let i=m(e),o=yield this.commonDbService.getData({feature:"crdtSnapshot",properties:{documentId:n?.documentId??"",organizationId:n?.organizationId??"",id:i,skipFirestore:!0}});return!o||typeof o!="object"||Object.keys(o).length===0||o?.errorCode?null:yield this.decryptSnapshotRecord(o,i)}return Promise.resolve(null)}catch(n){return this.loggingService.catch("Error in CrdtService getSnapshot: ",n),Promise.resolve(null)}})}saveSnapshot(d){return v(this,arguments,function*({id:e,state:t,vector:n,type:i,contentKey:o,source:s}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveSnapshot","color: green;");let l=this.docService.getDocumentPaths(),u=this.authService.getUser();if(u?.userId&&l){let h=m(e),p=this.portableCrdtChannels.size>0?this.peekPortableCrdtChannel():null,S=p?.store.getDeliveredSeq(h)??0,C=yield this.encryptCrdtData(t,h),f=yield this.encryptCrdtData(n,h);if(C==null||f==null)return;let w=u.userId,k=m(u.userId),D=this.domService.getTabId(),A={id:e,veltId:h,encryptedState:C,encryptedVector:f,type:i,contentKey:o,source:s,updatedByUserId:w,updatedByVeltUserId:k,sessionId:D};if(this.isPortableCrdtActive()){let U=p??this.resolvePortableCrdtFoldChannel(l);if(!U)return;let{store:_,key:H}=U;if(!(yield this.awaitPortableCrdtPrimedForFold(_))){this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the channel snapshot has not arrived (compaction pauses; content is unaffected)");return}let R=se(A,yield this.getPortableServerTimestamp()),F=_.planFold(h,R,S);if(!F){this.loggingService.log("Velt [portable backend]: crdt snapshot fold skipped \u2014 the channel is denied or held an unreadable row (compaction pauses; log replay stays authoritative)");return}let K=ne(F.composite);if(K===null)return;if(K.length>ie){this.loggingService.log(`Velt [portable backend]: crdt snapshot fold skipped \u2014 the composite is ${K.length} base64 characters, over the gateway's ${ie} cap (compaction pauses; content is unaffected)`);return}if(!this.authService.getUser()){this.loggingService.log("Velt [portable backend]: crdt snapshot fold not sent \u2014 no user is signed in (compaction pauses; content is unaffected)");return}let Le=W("crdt")?.mode??"persistent",G=yield this.adapterSelectorService.resolveRealtimeAdapter().publish(H,Le,{payloadB64:K,uptoSeq:F.uptoSeq});G.ok?G.seq===F.uptoSeq&&_.adoptFold(F):this.reportPortableCrdtFoldFailure(G);return}yield this.commonDbService.setData({feature:"crdtSnapshot",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:h,skipFirestore:!0},data:se(A,this.commonDbService.getServerTimestamp())})}}catch(l){this.loggingService.catch("Error in CrdtService saveSnapshot: ",l)}})}pruneMessages(n){return v(this,arguments,function*({id:e,beforeTs:t}){try{if(this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pruneMessages","color: green;"),this.isPortableCrdtActive()){this.loggingService.log("Velt [portable backend]: pruneMessages is a no-op (writeCrdtSnapshot folds own the trim)");return}let i=this.docService.getDocumentPaths();if(i){let o=m(e),s=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,skipFirestore:!0}});if(s&&typeof s=="object"&&!s?.errorCode){let d=[];for(let l of Object.keys(s)){let u=s[l];u?.timestamp!=null&&u.timestamp<t&&d.push(this.commonDbService.deleteData({feature:"crdtMessage",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:o,messageId:l,skipFirestore:!0}}))}yield Promise.all(d)}}}catch(i){this.loggingService.catch("Error in CrdtService pruneMessages: ",i)}})}updateNotificationsDatabase(e,t,n={}){try{let i=E({crdtData:e,actionType:t,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 t=this.editorEditTrackers.get(e);if(!t){let n=new V,i=n.pipe(J(this.activityDebounceTime)).subscribe(()=>{this.flushEditorActivity(e)});t={count:0,subject$:n,subscription:i},this.editorEditTrackers.set(e,t)}t.count++,t.subject$.next()}catch(t){this.loggingService.catch("Error in CrdtService trackEditForActivity: ",t)}}flushEditorActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t||t.count===0)return;let n=t.count;t.count=0;let i={featureType:"crdt",actionType:be.EDITOR_EDIT,targetEntityId:e,entityData:{editCount:n}};this.activityService?.createActivity(i)}catch(t){this.loggingService.catch("Error in CrdtService flushEditorActivity: ",t)}}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(t){this.loggingService.catch("Error in CrdtService setActivityDebounceTime: ",t)}}flushAllEditorActivities(){try{for(let[e,t]of this.editorEditTrackers)t.count>0&&this.flushEditorActivity(e),t.subject$.complete(),t.subscription.unsubscribe();this.editorEditTrackers.clear()}catch(e){this.loggingService.catch("Error in CrdtService flushAllEditorActivities: ",e)}}};r.PORTABLE_ACTIVATION_WAIT_MS=1e4,r.\u0275fac=function(t){return new(t||r)(I(Te),I(Ee),I(ke),I(Ve),I(Ne),I(Pe),I(q),I(_e),I(we),I(g),I(x))},r.\u0275prov=L({token:r,factory:r.\u0275fac,providedIn:"root"});let c=r;return c})();var $=class extends Fe{constructor(r){super(r),this.getService(g).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(r){this.getService(g).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(b).updateData(r)}catch(a){return this.getService(g).catch("Error in updateData: ",a),Promise.resolve(null)}}_onDataChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(b).onDataChange(r)}catch(a){return this.getService(g).catch("Error in onDataChange: ",a),()=>{}}}_getData(r){this.getService(g).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(b).getData(r)}catch(a){return this.getService(g).catch("Error in getData: ",a),Promise.resolve(null)}}_onStateChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(b).onStateChange(r)}catch(a){return this.getService(g).catch("Error in onStateChange: ",a),()=>{}}}_updateState(r){this.getService(g).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(b).updateState(r)}catch(a){return this.getService(g).catch("Error in updateState: ",a),Promise.resolve(null)}}_registerSyncUser(r){this.getService(g).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(b).registerSyncUser(r)}catch(a){return this.getService(g).catch("Error in registerSyncUser: ",a),Promise.resolve()}}_onRegisteredUserChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(b).onRegisteredUserChange(r)}catch(a){return this.getService(g).catch("Error in onRegisteredUserChange: ",a),()=>{}}}_setPresence(r){this.getService(g).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(b).setPresence(r)}catch(a){return this.getService(g).catch("Error in setPresence: ",a),Promise.resolve()}}_onPresenceChange(r){this.getService(g).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(b).onPresenceChange(r)}catch(a){return this.getService(g).catch("Error in onPresenceChange: ",a),()=>{}}}_saveVersion(r){this.getService(g).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(b).saveVersion(r)}catch(a){return this.getService(g).catch("Error in saveVersion: ",a),Promise.resolve(null)}}_getVersion(r){this.getService(g).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(b).getVersion(r)}catch(a){return this.getService(g).catch("Error in getVersion: ",a),Promise.resolve(null)}}_getVersions(r){this.getService(g).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(b).getVersions(r)}catch(a){return this.getService(g).catch("Error in getVersions: ",a),Promise.resolve(null)}}_pushMessage(r){this.getService(g).log("%c[WB] Calling FUNCTION: pushMessage","color: green;");try{return this.getService(b).pushMessage(r)}catch(a){return this.getService(g).catch("Error in pushMessage: ",a),Promise.resolve()}}_onMessage(r){this.getService(g).log("%c[WB] Calling FUNCTION: onMessage","color: green;");try{return this.getService(b).onMessage(r)}catch(a){return this.getService(g).catch("Error in onMessage: ",a),()=>{}}}_getMessages(r){this.getService(g).log("%c[WB] Calling FUNCTION: getMessages","color: green;");try{return this.getService(b).getMessages(r)}catch(a){return this.getService(g).catch("Error in getMessages: ",a),Promise.resolve([])}}_getSnapshot(r){this.getService(g).log("%c[WB] Calling FUNCTION: getSnapshot","color: green;");try{return this.getService(b).getSnapshot(r)}catch(a){return this.getService(g).catch("Error in getSnapshot: ",a),Promise.resolve(null)}}_saveSnapshot(r){this.getService(g).log("%c[WB] Calling FUNCTION: saveSnapshot","color: green;");try{return this.getService(b).saveSnapshot(r)}catch(a){return this.getService(g).catch("Error in saveSnapshot: ",a),Promise.resolve()}}_pruneMessages(r){this.getService(g).log("%c[WB] Calling FUNCTION: pruneMessages","color: green;");try{return this.getService(b).pruneMessages(r)}catch(a){return this.getService(g).catch("Error in pruneMessages: ",a),Promise.resolve()}}_enableWebhook(){this.getService(g).log("%c[WB] Calling FUNCTION: enableWebhook","color: green;");try{return this.getService(b).enableWebhook()}catch(r){this.getService(g).catch("Error in enableWebhook: ",r);return}}_disableWebhook(){this.getService(g).log("%c[WB] Calling FUNCTION: disableWebhook","color: green;");try{return this.getService(b).disableWebhook()}catch(r){this.getService(g).catch("Error in disableWebhook: ",r);return}}_setWebhookDebounceTime(r){this.getService(g).log("%c[WB] Calling FUNCTION: setWebhookDebounceTime","color: green;");try{!isNaN(r)&&r>0?this.getService(b).setWebhookDebounceTime(r):this.getService(g).catch("Error in setWebhookDebounceTime: ","Provided value must be a positive number greater than zero.")}catch(a){this.getService(g).catch("Error in setWebhookDebounceTime: ",a)}}_setActivityDebounceTime(r){this.getService(g).log("%c[WB] Calling FUNCTION: setActivityDebounceTime","color: green;");try{!isNaN(r)&&r>=1e4?this.getService(b).setActivityDebounceTime(r):this.getService(g).catch("Error in setActivityDebounceTime: ","Provided value must be a number >= 10000ms (10 seconds).")}catch(a){this.getService(g).catch("Error in setActivityDebounceTime: ",a)}}_on(r){this.getService(g).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(q).onAction(r)}catch(a){return this.getService(g).catch("Error in on: ",a),P(null)}}};var je=(()=>{let r=class r{};r.\u0275fac=function(t){return new(t||r)},r.\u0275mod=Se({type:r}),r.\u0275inj=pe({imports:[ye]});let c=r;return c})();function Qe(c){return c.get(g).log("%c[WB] Loading CRDT feature chunk","color: blue;"),c.get(x).set(De,c.get(b)),ve(je,c),new $(c)}export{Qe as default};