@veltdev/sdk
Version:
Velt is an SDK to add collaborative features to your product within minutes. Example: Comments like Figma, Frame.io, Google docs or sheets, Recording like Loom, Huddles like Slack and much more.
3 lines (2 loc) • 30.9 kB
JavaScript
import{f as B,j as Z}from"./chunk-KU45CEXD.js";import{$ as y,Ee as p,Ii as ne,L as w,Nh as k,Qe as te,Qf as T,Se as re,T as q,Va as Y,Wa as X,_ as H,_b as Q,a as _,aa as W,ae as d,ag as O,b as C,bi as ie,ca as h,di as E,g as V,i as v,jh as j,k as N,od as ee,qa as J,r as $,ua as K,v as L}from"./chunk-GR3NESUB.js";var P=class{_totalWeight=0;_averageItemSize;_defaultItemSize;constructor(i=50){this._defaultItemSize=i,this._averageItemSize=i}getAverageItemSize(){return this._averageItemSize}addSample(i,o){let e=this._totalWeight+i.end-i.start;if(e){let t=(o+this._averageItemSize*this._totalWeight)/e;t&&(this._averageItemSize=t,this._totalWeight=e)}}reset(){this._averageItemSize=this._defaultItemSize,this._totalWeight=0}},z=class{scrolledIndexChange=new v(()=>{});_viewport=null;_minBufferPx;_maxBufferPx;_averager;_lastScrollOffset;_lastRenderedContentSize;_lastRenderedContentOffset;_removalFailures=0;constructor(i,o,e=new P){this._minBufferPx=i,this._maxBufferPx=o,this._averager=e}attach(i){this._averager.reset(),this._viewport=i,this._renderContentForCurrentOffset()}detach(){this._viewport=null}onContentScrolled(){this._viewport&&this._updateRenderedContentAfterScroll()}onDataLengthChanged(){this._viewport&&(this._renderContentForCurrentOffset(),this._checkRenderedContentSize())}onContentRendered(){this._viewport&&this._checkRenderedContentSize()}onRenderedOffsetChanged(){this._viewport&&this._checkRenderedContentOffset()}scrollToIndex(){}updateBufferSize(i,o){if(o<i)throw Error("CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx");this._minBufferPx=i,this._maxBufferPx=o}_updateRenderedContentAfterScroll(){let i=this._viewport,o=i.measureScrollOffset(),e=o-this._lastScrollOffset,t=Math.abs(e),r=i.getRenderedRange(),s=0;if(e<0){let g=r.start*this._averager.getAverageItemSize()-this._lastRenderedContentOffset;s=Math.round(g*Math.max(0,Math.min(1,t/(o+t)))),e=e-s,t=Math.abs(e)}let a=this._lastScrollOffset-this._lastRenderedContentOffset,c=this._lastRenderedContentOffset+this._lastRenderedContentSize-(this._lastScrollOffset+i.getViewportSize()),u=t+this._minBufferPx-(e<0?a:c);if(u>0)if(t>=i.getViewportSize())this._renderContentForCurrentOffset();else{let f=Math.max(0,Math.ceil((u-this._minBufferPx+this._maxBufferPx)/this._averager.getAverageItemSize())),g=(e<0?c:a)-this._minBufferPx+t,b=Math.floor(g/this._averager.getAverageItemSize()/(this._removalFailures+1)),A=Math.min(r.end-r.start,Math.max(0,b)),l=this._expandRange(r,e<0?f:0,e>0?f:0);e<0?l.end=Math.max(l.start+1,l.end-A):l.start=Math.min(l.end-1,l.start+A);let S,G;if(e<0){let R=i.measureRangeSize({start:l.end,end:r.end});R<=g?(S=this._lastRenderedContentOffset+this._lastRenderedContentSize-R,this._removalFailures=0):(l.end=r.end,S=this._lastRenderedContentOffset+this._lastRenderedContentSize,this._removalFailures++),G="to-end"}else{let R=i.measureRangeSize({start:r.start,end:l.start});R<=g?(S=this._lastRenderedContentOffset+R,this._removalFailures=0):(l.start=r.start,S=this._lastRenderedContentOffset,this._removalFailures++),G="to-start"}i.setRenderedRange(l),i.setRenderedContentOffset(S+s,G)}else s&&i.setRenderedContentOffset(this._lastRenderedContentOffset+s);this._lastScrollOffset=o}_checkRenderedContentSize(){let i=this._viewport;this._lastRenderedContentSize=i.measureRenderedContentSize(),this._averager.addSample(i.getRenderedRange(),this._lastRenderedContentSize),this._updateTotalContentSize(this._lastRenderedContentSize)}_checkRenderedContentOffset(){let i=this._viewport;this._lastRenderedContentOffset=i.getOffsetToRenderedContentStart()}_renderContentForCurrentOffset(){let i=this._viewport,o=i.measureScrollOffset();this._lastScrollOffset=o,this._removalFailures=0;let e=this._averager.getAverageItemSize(),t=Math.min(i.getDataLength()-1,Math.floor(o/e)),r=Math.ceil(this._maxBufferPx/e),s=this._expandRange(this._getVisibleRangeForIndex(t),r,r);i.setRenderedRange(s),i.setRenderedContentOffset(e*s.start)}_getVisibleRangeForIndex(i){let o=this._viewport,e={start:i,end:i+Math.ceil(o.getViewportSize()/this._averager.getAverageItemSize())},t=e.end-o.getDataLength();return t>0&&(e.start=Math.max(0,e.start-t)),e}_expandRange(i,o,e){let t=this._viewport,r=Math.max(0,i.start-o),s=Math.min(t.getDataLength(),i.end+e);return{start:r,end:s}}_updateTotalContentSize(i){let o=this._viewport,e=o.getRenderedRange(),t=i+(o.getDataLength()-(e.end-e.start))*this._averager.getAverageItemSize();o.setTotalContentSize(t)}};function le(n){return n._scrollStrategy}var Ae=(()=>{class n{get minBufferPx(){return this._minBufferPx}set minBufferPx(o){this._minBufferPx=B(o)}_minBufferPx=100;get maxBufferPx(){return this._maxBufferPx}set maxBufferPx(o){this._maxBufferPx=B(o)}_maxBufferPx=200;_scrollStrategy=new z(this.minBufferPx,this.maxBufferPx);ngOnChanges(){this._scrollStrategy.updateBufferSize(this.minBufferPx,this.maxBufferPx)}static \u0275fac=function(e){return new(e||n)};static \u0275dir=X({type:n,selectors:[["cdk-virtual-scroll-viewport","autosize",""]],inputs:{minBufferPx:"minBufferPx",maxBufferPx:"maxBufferPx"},features:[Q([{provide:Z,useFactory:le,deps:[H(()=>n)]}]),K]})}return n})(),Re=(()=>{class n{static \u0275fac=function(e){return new(e||n)};static \u0275mod=Y({type:n});static \u0275inj=W({})}return n})();var I=(()=>{let i=class i{constructor(e){this.loggingService=e,this.enabledSignal=J(!1),this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0;try{this.enabled$=ee(this.enabledSignal).pipe(w())}catch(t){this.loggingService.catch("Error in SuggestionModeService constructor: ",t),this.enabled$=new v}}enable(e){try{this.onTargetEditStart=e?.onTargetEditStart??null,this.onTargetEditCommit=e?.onTargetEditCommit??null,this.autoCommit=e?.autoCommit!==!1,this.enabledSignal.set(!0)}catch(t){this.loggingService.catch("Error in SuggestionModeService enable: ",t)}}disable(){try{this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0,this.enabledSignal.set(!1)}catch(e){this.loggingService.catch("Error in SuggestionModeService disable: ",e)}}isEnabled(){try{return this.enabledSignal()}catch(e){return this.loggingService.catch("Error in SuggestionModeService isEnabled: ",e),!1}}getOnTargetEditStart(){try{return this.onTargetEditStart}catch(e){return this.loggingService.catch("Error in SuggestionModeService getOnTargetEditStart: ",e),null}}getOnTargetEditCommit(){try{return this.onTargetEditCommit}catch(e){return this.loggingService.catch("Error in SuggestionModeService getOnTargetEditCommit: ",e),null}}isAutoCommitEnabled(){try{return this.autoCommit}catch(e){return this.loggingService.catch("Error in SuggestionModeService isAutoCommitEnabled: ",e),!1}}};i.\u0275fac=function(t){return new(t||i)(h(E))},i.\u0275prov=y({token:i,factory:i.\u0275fac,providedIn:"root"});let n=i;return n})();var D=(()=>{let i=class i{constructor(e){this.loggingService=e,this.snapshots=new Map}captureFromGetter(e,t){try{if(!e||typeof t!="function")return!1;let r;try{r=t()}catch(s){return T()&&this.loggingService.catch(`[velt] Suggestion target "${e}" getter threw: `,s),!1}return this.captureValue(e,r)}catch(r){return this.loggingService.catch("Error in SuggestionSnapshotService captureFromGetter: ",r),!1}}captureValue(e,t){try{if(!e)return!1;let r;try{r=structuredClone(t)}catch(s){return T()&&this.loggingService.catch(`[velt] Suggestion target "${e}" snapshot failed (value not cloneable). Cause: structuredClone rejected the value (cyclic refs, DOM nodes, or functions are common culprits). Fix: ensure your getter returns plain JSON-serializable data.`,s),!1}return this.snapshots.set(e,r),!0}catch(r){return this.loggingService.catch("Error in SuggestionSnapshotService captureValue: ",r),!1}}getSnapshot(e){try{return this.snapshots.has(e)?this.snapshots.get(e):void 0}catch(t){this.loggingService.catch("Error in SuggestionSnapshotService getSnapshot: ",t);return}}hasSnapshot(e){try{return this.snapshots.has(e)}catch(t){return this.loggingService.catch("Error in SuggestionSnapshotService hasSnapshot: ",t),!1}}clearSnapshot(e){try{this.snapshots.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionSnapshotService clearSnapshot: ",t)}}clearAllSnapshots(){try{this.snapshots.clear()}catch(e){this.loggingService.catch("Error in SuggestionSnapshotService clearAllSnapshots: ",e)}}};i.\u0275fac=function(t){return new(t||i)(h(E))},i.\u0275prov=y({token:i,factory:i.\u0275fac,providedIn:"root"});let n=i;return n})();var ae=(()=>{let i=class i{constructor(e,t,r){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.registry=new Map,this.warnedUnstableIds=new Set,this.actionsService=null}registerTarget(e,t){try{if(!e||typeof t!="function")return;this.warnIfUnstableId(e);let r=this.registry.get(e)??{};r.getter=t,this.registry.set(e,r)}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService registerTarget: ",r)}}unregisterTarget(e){try{let t=this.registry.get(e);if(!t)return;delete t.getter,t.node||this.registry.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService unregisterTarget: ",t)}}getGetter(e){try{return this.registry.get(e)?.getter}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getGetter: ",t);return}}setActionsService(e){try{this.actionsService=e}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService setActionsService: ",t)}}getNode(e){try{if(!e)return;let t=this.registry.get(e)?.node;if(t&&t.isConnected)return t;let r=this.queryAll(e);if(r.length===0)return;r.length>1&&this.warnDuplicateId(e,r.length);let s=r[0],a=this.registry.get(e)??{};return a.node=s,this.registry.set(e,a),s}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getNode: ",t);return}}getFallbackValue(e){try{let t=this.getNode(e);if(!t)return{hasValue:!1};let r=t.textContent??"";return r.length>0?{hasValue:!0,value:r}:{hasValue:!1}}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService getFallbackValue: ",t),{hasValue:!1}}}isRegistered(e){try{return this.registry.get(e)?.getter?!0:!!this.getNode(e)}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService isRegistered: ",t),!1}}countTaggedElements(e){try{let t=e??this.rootEl??document.body;return t?t.querySelectorAll(`[${p.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).length:0}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService countTaggedElements: ",t),0}}startObserving(e=document.body){try{if(this.observer)return;this.rootEl=e,this.scanAndRefresh(e),this.observer=new MutationObserver(()=>{try{this.scanAndRefresh(this.rootEl??document.body)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService observer callback: ",t)}}),this.observer.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[p.ATTRIBUTES.VELT_SUGGESTION_TARGET]}),this.installDelegatedListeners(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService startObserving: ",t)}}stopObserving(){try{this.observer?.disconnect(),this.observer=void 0,this.rootEl&&this.removeDelegatedListeners(this.rootEl),this.rootEl=void 0}catch(e){this.loggingService.catch("Error in SuggestionTargetRegistryService stopObserving: ",e)}}clear(){try{this.registry.clear(),this.warnedUnstableIds.clear()}catch(e){this.loggingService.catch("Error in SuggestionTargetRegistryService clear: ",e)}}installDelegatedListeners(e){try{this.boundFocusIn=t=>this.handleFocusIn(t),this.boundChange=t=>this.handleChange(t),this.boundFocusOut=t=>this.handleFocusOut(t),e.addEventListener("focusin",this.boundFocusIn,!0),e.addEventListener("change",this.boundChange,!0),e.addEventListener("focusout",this.boundFocusOut,!0)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService installDelegatedListeners: ",t)}}removeDelegatedListeners(e){try{this.boundFocusIn&&e.removeEventListener("focusin",this.boundFocusIn,!0),this.boundChange&&e.removeEventListener("change",this.boundChange,!0),this.boundFocusOut&&e.removeEventListener("focusout",this.boundFocusOut,!0),this.boundFocusIn=void 0,this.boundChange=void 0,this.boundFocusOut=void 0}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService removeDelegatedListeners: ",t)}}handleFocusIn(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t)return;this.captureSnapshotForTarget(t.targetId,t.element);let r=this.snapshotService.getSnapshot(t.targetId),s={targetId:t.targetId,oldValue:r,newValue:r,element:t.element},a=this.modeService.getOnTargetEditStart();if(a)try{a(s)}catch(c){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditStart customer callback threw: ",c)}this.actionsService?.triggerAction(d.TARGET_EDIT_START,{details:s,timestamp:Date.now()})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleFocusIn: ",t)}}handleChange(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t||!this.isAtomicCommitTarget(e.target))return;this.processCommit(t.targetId,t.element)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleChange: ",t)}}handleFocusOut(e){try{if(!this.modeService.isEnabled())return;let t=this.findTaggedAncestor(e.target);if(!t||this.isAtomicCommitTarget(e.target))return;this.processCommit(t.targetId,t.element)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService handleFocusOut: ",t)}}isAtomicCommitTarget(e){try{if(e instanceof HTMLSelectElement)return!0;if(e instanceof HTMLInputElement){let t=(e.type||"").toLowerCase();return t==="checkbox"||t==="radio"}return!1}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService isAtomicCommitTarget: ",t),!1}}processCommit(e,t){try{let r=this.snapshotService.getSnapshot(e),s=this.readElementValue(e,t);if(O(r,s))return;let a={targetId:e,oldValue:r,newValue:s,element:t},c=this.modeService.getOnTargetEditCommit(),u=null;if(c){let g=null;try{g=c(a)}catch(b){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditCommit customer callback threw: ",b)}g&&(u=this.invokeAutoCommit({targetId:e,newValue:s,summary:g.summary,summaryHtml:g.summaryHtml,metadata:g.metadata}))}else this.modeService.isAutoCommitEnabled()&&(u=this.invokeAutoCommit({targetId:e,newValue:s}));let f=g=>V(this,null,function*(){return u&&(yield u)?null:this.invokeAutoCommit({targetId:e,newValue:s,summary:g?.summary,summaryHtml:g?.summaryHtml,metadata:g?.metadata})});this.actionsService?.triggerAction(d.TARGET_EDIT_COMMIT,{details:a,commitSuggestion:f,timestamp:Date.now()})}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService processCommit: ",r)}}invokeAutoCommit(e){try{return this.actionsService?this.actionsService.commitSuggestion(e).catch(t=>(T()&&this.loggingService.catch(`[velt] auto-commit for "${e.targetId}" rejected: `,t),null)):(T()&&this.loggingService.log("[velt] auto-commit skipped: actions service not wired. SuggestionActionsService constructor should call registry.setActionsService(this)."),Promise.resolve(null))}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService invokeAutoCommit: ",t),Promise.resolve(null)}}captureSnapshotForTarget(e,t){try{let r=this.registry.get(e);if(r?.getter){this.snapshotService.captureFromGetter(e,r.getter);return}let s=this.readElementValue(e,t);this.snapshotService.captureValue(e,s)}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService captureSnapshotForTarget: ",r)}}readElementValue(e,t){try{let r=this.registry.get(e);if(r?.getter)try{return r.getter()}catch{return}if(t instanceof HTMLInputElement){let s=(t.type||"").toLowerCase();return s==="checkbox"||s==="radio"?t.checked:s==="number"||s==="range"?Number.isNaN(t.valueAsNumber)?t.value:t.valueAsNumber:t.value}return t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?t.value:(t instanceof HTMLElement&&t.isContentEditable,t.textContent??"")}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService readElementValue: ",r);return}}findTaggedAncestor(e){try{if(!(e instanceof Element))return null;let t=e.closest(`[${p.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`);if(!t)return null;let r=t.getAttribute(p.ATTRIBUTES.VELT_SUGGESTION_TARGET);return r?{element:t,targetId:r}:null}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService findTaggedAncestor: ",t),null}}queryAll(e){try{let t=window.CSS?.escape?window.CSS.escape(e):e.replace(/"/g,'\\"');return Array.from(document.querySelectorAll(`[${p.ATTRIBUTES.VELT_SUGGESTION_TARGET}="${t}"]`))}catch{return[]}}scanAndRefresh(e){try{e.querySelectorAll(`[${p.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).forEach(r=>{let s=r.getAttribute(p.ATTRIBUTES.VELT_SUGGESTION_TARGET);if(!s)return;let a=this.registry.get(s)??{};(!a.node||!a.node.isConnected)&&(a.node=r,this.registry.set(s,a))})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService scanAndRefresh: ",t)}}warnIfUnstableId(e){try{if(!T()||this.warnedUnstableIds.has(e))return;let t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(e),r=/\d{10,}/.test(e);(t||r)&&(this.warnedUnstableIds.add(e),this.loggingService.catch(`[velt] Target id "${e}" appears unstable. Cause: contains a UUID or timestamp shape \u2014 these typically change across re-renders. Fix: use a stable customer-owned id (the same one you use in your state). Docs: velt.dev/docs/suggestions/target-ids`,new Error("UNSTABLE_TARGET_ID")))}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService warnIfUnstableId: ",t)}}warnDuplicateId(e,t){try{if(!T())return;this.loggingService.catch(`[velt] Duplicate target id "${e}" \u2014 ${t} elements share this id. Cause: the same ${p.ATTRIBUTES.VELT_SUGGESTION_TARGET} appears on multiple DOM nodes. Fix: ensure each suggestable element has a unique id. Velt is using the first registered element. Docs: velt.dev/docs/suggestions/target-ids`,new Error("DUPLICATE_TARGET_ID"))}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService warnDuplicateId: ",r)}}};i.\u0275fac=function(t){return new(t||i)(h(E),h(I),h(D))},i.\u0275prov=y({token:i,factory:i.\u0275fac,providedIn:"root"});let n=i;return n})();var Ve=(()=>{let i=class i{constructor(e,t,r,s,a,c){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.targetRegistry=s,this.serviceBook=a,this.commonDbService=c,this.actionSubjects=new Map,this.observingActive=!1,this.commentService=null;try{this.targetRegistry.setActionsService(this),this.serviceBook.observe(k).subscribe(u=>{this.commentService=u})}catch(u){this.loggingService.catch("Error in SuggestionActionsService constructor: ",u)}}enableSuggestionMode(e){try{this.modeService.enable(e),this.startObservingIfNeeded(),this.warnIfNoTaggedElements()}catch(t){this.loggingService.catch("Error in SuggestionActionsService enableSuggestionMode: ",t)}}disableSuggestionMode(){try{this.modeService.disable(),this.stopObservingIfNeeded()}catch(e){this.loggingService.catch("Error in SuggestionActionsService disableSuggestionMode: ",e)}}isSuggestionModeEnabled(){try{return this.modeService.isEnabled()}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled: ",e),!1}}isSuggestionModeEnabled$(){try{return this.modeService.enabled$}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled$: ",e),new v}}registerTarget(e){try{if(!e?.targetId||typeof e?.getter!="function")return;this.targetRegistry.registerTarget(e.targetId,e.getter)}catch(t){this.loggingService.catch("Error in SuggestionActionsService registerTarget: ",t)}}unregisterTarget(e){try{this.targetRegistry.unregisterTarget(e)}catch(t){this.loggingService.catch("Error in SuggestionActionsService unregisterTarget: ",t)}}startSuggestion(e){try{let t=this.targetRegistry.getGetter(e);if(t){this.snapshotService.captureFromGetter(e,t);return}let r=this.targetRegistry.getFallbackValue(e);r.hasValue?this.snapshotService.captureValue(e,r.value):this.loggingService.warn(`[velt] startSuggestion: target "${e}" not registered. Cause: no getter via registerTarget() and no textContent fallback. Fix: tag the element with data-velt-suggestion-target and register a getter via registerTarget(). Docs: velt.dev/docs/suggestions/targets`)}catch(t){this.loggingService.catch("Error in SuggestionActionsService startSuggestion: ",t)}}commitSuggestion(e){return new Promise((t,r)=>{try{if(!e?.targetId){r(new Error("INVALID_CONFIG"));return}if(!this.modeService.isEnabled()){this.loggingService.warn("[velt] commitSuggestion called while suggestion mode is disabled. Cause: enableSuggestionMode() has not been called (or disableSuggestionMode() was called). Fix: call enableSuggestionMode() before commit, or branch on isSuggestionModeEnabled() in your onSave handler. Docs: velt.dev/docs/suggestions/mode"),r(new Error("MODE_NOT_SUGGESTING"));return}if(!this.targetRegistry.isRegistered(e.targetId)){this.loggingService.warn(`[velt] commitSuggestion: target "${e.targetId}" not registered. Cause: no element has data-velt-suggestion-target="${e.targetId}" and no registerTarget() call provided a getter. Fix: tag the element or register a getter at app boot. Docs: velt.dev/docs/suggestions/targets`),r(new Error("TARGET_NOT_REGISTERED"));return}if(!this.snapshotService.hasSnapshot(e.targetId)){let l=this.targetRegistry.getGetter(e.targetId);if(l){if(!this.snapshotService.captureFromGetter(e.targetId,l)){r(new Error("SNAPSHOT_FAILED"));return}}else{let S=this.targetRegistry.getFallbackValue(e.targetId);if(S.hasValue)this.snapshotService.captureValue(e.targetId,S.value);else{this.loggingService.warn(`[velt] commitSuggestion: target "${e.targetId}" requires registerTarget() for complex values. Cause: complex objects need a getter so the SDK can deep-clone the snapshot. Fix: call velt.getSuggestionElement().registerTarget("${e.targetId}", () => yourState.${e.targetId}) at app boot. Docs: velt.dev/docs/suggestions/getter`),r(new Error("NO_GETTER_FOR_COMPLEX"));return}}}let u=this.snapshotService.getSnapshot(e.targetId),f=e.newValue;if(O(u,f)){this.loggingService.warn(`[velt] commitSuggestion: no change detected for target "${e.targetId}". Cause: oldValue and newValue are deeply equal. Fix: only call commitSuggestion when the customer actually changed the value. Docs: velt.dev/docs/suggestions/edge-cases`),r(new Error("NO_CHANGE_TO_SUGGEST"));return}let g=new te;g.type="suggestion",g.suggestion={status:"pending",targetId:e.targetId,targetType:"custom",oldValue:u,newValue:f,summary:e.summary??null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},g.metadata=e.metadata??{};let b=fe(e.summary,e.summaryHtml,u,f),A=new re;if(A.commentText=b.commentText,A.commentHtml=b.commentHtml,g.comments=[A],!this.commentService){this.loggingService.catch('SuggestionActionsService.commitSuggestion: comment chunk not loaded \u2014 call Snippyly.preloadComment() first or include "comment" in featureAllowList.',new Error("comment chunk unavailable")),r(new Error("comment chunk not loaded"));return}this.commentService.addComment(void 0,void 0,void 0,void 0,!1,[],void 0,void 0,void 0,void 0,void 0,void 0,void 0,l=>{try{this.snapshotService.clearSnapshot(e.targetId),this.projectAndTrigger(d.SUGGESTION_CREATED,l.annotation),t({id:l.annotation.annotationId})}catch(S){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion callback: ",S),r(S)}},void 0,void 0,g,void 0,void 0,!0,void 0,void 0,"internal",void 0)}catch(s){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion: ",s),r(s)}})}getSuggestions(e){try{let t=this.commentService?.getCommentAnnotationsOnCurrentOrganizationAndDocument()??[],r=[];for(let s of t){if(!s.suggestion)continue;let a=this.projectAnnotationToSuggestion(s);a&&this.matchesFilter(a,e)&&r.push(a)}return r}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions: ",t),[]}}getSuggestions$(e){try{return this.serviceBook.observe(k).pipe(q(t=>t?t.getCommentAnnotationsOnCurrentOrganizationAndDocument$():$([]))).pipe(L(t=>{let r=[];for(let s of t??[]){if(!s.suggestion)continue;let a=this.projectAnnotationToSuggestion(s);a&&this.matchesFilter(a,e)&&r.push(a)}return r}),w(j))}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions$: ",t),new v}}getPendingSuggestion(e){try{if(!e)return null;let t=this.getSuggestions({targetId:e,status:"pending"});return t.length===0?null:t.sort((r,s)=>(s.createdAt??0)-(r.createdAt??0))[0]}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion: ",t),null}}getPendingSuggestion$(e){try{return e?this.getSuggestions$({targetId:e,status:"pending"}).pipe(L(t=>t.length===0?null:t.sort((r,s)=>(s.createdAt??0)-(r.createdAt??0))[0]),w(j)):new v}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion$: ",t),new v}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new N),this.actionSubjects.get(e)?.next(t)}catch(r){this.loggingService.catch("Error in SuggestionActionsService triggerAction: ",r)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new N),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in SuggestionActionsService onAction: ",t),$(null)}}projectAndTrigger(e,t){try{if(!t||!t.suggestion)return;let r=this.projectAnnotationToSuggestion(t);if(!r)return;let s=this.timestamp;switch(e){case d.SUGGESTION_CREATED:{let a={suggestion:r,timestamp:s};this.triggerAction(d.SUGGESTION_CREATED,a);break}case d.SUGGESTION_APPROVED:{let a={suggestion:r,timestamp:s};this.triggerAction(d.SUGGESTION_APPROVED,a);break}case d.SUGGESTION_REJECTED:{let a={suggestion:r,timestamp:s};this.triggerAction(d.SUGGESTION_REJECTED,a);break}case d.SUGGESTION_STALE:{let a={suggestion:r,timestamp:s};this.triggerAction(d.SUGGESTION_STALE,a);break}}}catch(r){this.loggingService.catch("Error in SuggestionActionsService projectAndTrigger: ",r)}}projectAnnotationToSuggestion(e){try{let t=e.suggestion;if(!t)return;let r={annotationId:e.annotationId,targetId:t.targetId,targetType:t.targetType,oldValue:t.oldValue,newValue:t.newValue,summary:t.summary,metadata:e.metadata??{},driftDetected:!!t.driftDetected,createdBy:e.from,createdAt:e.createdAt??0};switch(t.status){case"pending":return C(_({},r),{status:"pending",rejectReason:null,resolvedBy:null,resolvedAt:null});case"accepted":case"apply_failed":return C(_({},r),{status:t.status,rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp});case"rejected":return C(_({},r),{status:"rejected",rejectReason:t.rejectReason??null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp});case"stale":return C(_({},r),{status:"stale",rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt});default:return}}catch(t){this.loggingService.catch("Error in SuggestionActionsService projectAnnotationToSuggestion: ",t);return}}startObservingIfNeeded(){try{if(this.observingActive)return;this.observingActive=!0,this.targetRegistry.startObserving()}catch(e){this.loggingService.catch("Error in SuggestionActionsService startObservingIfNeeded: ",e)}}stopObservingIfNeeded(){try{if(!this.observingActive)return;this.observingActive=!1,this.targetRegistry.stopObserving()}catch(e){this.loggingService.catch("Error in SuggestionActionsService stopObservingIfNeeded: ",e)}}warnIfNoTaggedElements(){try{this.targetRegistry.countTaggedElements()===0&&this.loggingService.warn('[velt] No suggestable elements found on this page. Cause: no DOM elements have a data-velt-suggestion-target attribute. Fix: tag at least one element with data-velt-suggestion-target="your.id" before enabling suggestion mode. Docs: velt.dev/docs/suggestions/getting-started')}catch(e){this.loggingService.catch("Error in SuggestionActionsService warnIfNoTaggedElements: ",e)}}get timestamp(){return this.commonDbService.getServerTimestamp()}matchesFilter(e,t){try{return t?!(t.targetId&&e.targetId!==t.targetId||t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(e.status)):!0}catch(r){return this.loggingService.catch("Error in SuggestionActionsService matchesFilter: ",r),!1}}};i.\u0275fac=function(t){return new(t||i)(h(E),h(I),h(D),h(ae),h(ie),h(ne))},i.\u0275prov=y({token:i,factory:i.\u0275fac,providedIn:"root"});let n=i;return n})();function ge(n){try{return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}catch{return""}}function m(n){try{if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}catch{return""}}function ce(n){try{if(n===null||typeof n!="object"||Array.isArray(n))return!1;let i=Object.getPrototypeOf(n);return i===Object.prototype||i===null}catch{return!1}}function ue(n,i){try{let o=n==null,e=i==null;if(o&&!e)return[{op:"add",newText:m(i)}];if(!o&&e)return[{op:"remove",oldText:m(n)}];if(ce(n)&&ce(i)){let t=n,r=i,s=[...Object.keys(t),...Object.keys(r).filter(c=>!(c in t))],a=[];for(let c of s){let u=c in t,f=c in r;u&&f?O(t[c],r[c])||a.push({op:"replace",oldText:`${c}: ${m(t[c])}`,newText:`${c}: ${m(r[c])}`}):u?a.push({op:"remove",oldText:`${c}: ${m(t[c])}`}):a.push({op:"add",newText:`${c}: ${m(r[c])}`})}if(a.length>0)return a}return[{op:"replace",oldText:m(n),newText:m(i)}]}catch{return[{op:"replace",oldText:m(n),newText:m(i)}]}}function de(n,i){try{return ue(n,i).map(o=>o.op==="add"?`Add: "${o.newText??""}"`:o.op==="remove"?`Remove: "${o.oldText??""}"`:`Replace: "${o.oldText??""}" with "${o.newText??""}"`).join(`
`)}catch{return'Replace: "" with ""'}}var F="color:#e0492b;font-style:italic;",M="color:#0f8a4d;font-style:italic;";function Se(n,i){try{let o=ue(n,i),e=t=>ge(t??"");if(o.length===1){let t=o[0];return t.op==="add"?`<div>Add:</div><div style="${M}">“${e(t.newText)}”</div>`:t.op==="remove"?`<div>Remove:</div><div style="${F}">“${e(t.oldText)}”</div>`:`<div>Replace:</div><div style="${F}">“${e(t.oldText)}”</div><div>with</div><div style="${M}">“${e(t.newText)}”</div>`}return o.map(t=>t.op==="add"?`<div>Add: <span style="${M}">“${e(t.newText)}”</span></div>`:t.op==="remove"?`<div>Remove: <span style="${F}">“${e(t.oldText)}”</span></div>`:`<div>Replace: <span style="${F}">“${e(t.oldText)}”</span> with <span style="${M}">“${e(t.newText)}”</span></div>`).join("")}catch{return"<div>Replace:</div><div>with</div>"}}function fe(n,i,o,e){try{let t=n||de(o,e),r;return i?r=i:n?r=`<p>${ge(n)}</p>`:r=Se(o,e),{commentText:t,commentHtml:r}}catch{return{commentText:"",commentHtml:""}}}export{Ae as a,Re as b,ae as c,Ve as d};