@veltdev/sdk-staging 6.0.44 → 6.0.45
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.
- package/app/models/data/comment-events.data.model.d.ts +10 -0
- package/app/models/data/comment-sidebar-config.model.d.ts +35 -0
- package/app/models/element/comment-element.model.d.ts +6 -3
- package/{chunk-NIXY2MMJ.js → chunk-36A7ZG4L.js} +1 -1
- package/{chunk-HQICZ4KH.js → chunk-3SLQQKJ6.js} +1 -1
- package/{chunk-VXKVV74S.js → chunk-4GZCXZSN.js} +1 -1
- package/{chunk-HZJQNVS6.js → chunk-6E6YYWQ4.js} +1 -1
- package/{chunk-LWGJ3OWM.js → chunk-6K62XPB3.js} +1 -1
- package/{chunk-BCCFAKMJ.js → chunk-7KXS2DSG.js} +1 -1
- package/{chunk-4QD6BCPV.js → chunk-ACPZ3R7G.js} +1 -1
- package/{chunk-2Y2VEYTA.js → chunk-BB7YQNOZ.js} +1 -1
- package/{chunk-EMRT2TA4.js → chunk-BEMVY5TX.js} +1 -1
- package/{chunk-BRBK63OM.js → chunk-BNG3HAKY.js} +1 -1
- package/{chunk-FU3PWZIS.js → chunk-CQ6HOISZ.js} +1 -1
- package/{chunk-WTN5DFZR.js → chunk-CU4CNZ3O.js} +1 -1
- package/{chunk-G3FQCUGP.js → chunk-D5QZV6VO.js} +1 -1
- package/{chunk-2FS2LLFT.js → chunk-E47OMTOM.js} +1 -1
- package/{chunk-BLBHPZRN.js → chunk-EFWZWZAR.js} +1 -1
- package/{chunk-AW22CHIF.js → chunk-I3POWLVT.js} +1 -1
- package/{chunk-YH3OHM33.js → chunk-I4SBC3EE.js} +1 -1
- package/{chunk-BEYATMPG.js → chunk-JV7MPTE5.js} +1 -1
- package/{chunk-OKVF43CR.js → chunk-LCF6FZ5S.js} +1 -1
- package/{chunk-KS76UKA5.js → chunk-LWTRRGHL.js} +1 -1
- package/{chunk-ZDLTYC4M.js → chunk-N65XETWG.js} +1 -1
- package/{chunk-ZOFOR5OQ.js → chunk-NZWI6NA5.js} +1 -1
- package/{chunk-HYYAUDDE.js → chunk-OXMSOSYV.js} +1 -1
- package/{chunk-XGRWIQXQ.js → chunk-QBZHSLQ3.js} +1 -1
- package/{chunk-BGMA2CZX.js → chunk-QNEPYZBW.js} +1 -1
- package/{chunk-RYIR6UVW.js → chunk-QT57U43N.js} +1 -1
- package/{chunk-Q6PUYIXT.js → chunk-QUMZPTVX.js} +1 -1
- package/{chunk-BSKC7PDG.js → chunk-R3KBXENN.js} +1 -1
- package/{chunk-RD3LXH2F.js → chunk-SP25RLYB.js} +1 -1
- package/{chunk-UCN46LMI.js → chunk-U52DCY3D.js} +1 -1
- package/{chunk-5PFE7VZH.js → chunk-VYRSFZO2.js} +1 -1
- package/{chunk-UMIQCTT5.js → chunk-XUBFTUBO.js} +1 -1
- package/{chunk-VNY7M5U6.js → chunk-XY7DGMPO.js} +1 -1
- package/{chunk-7D33ZDW3.js → chunk-YKZV3FEU.js} +1 -1
- package/{chunk-UPZ52FZB.js → chunk-ZMILEE6P.js} +1 -1
- package/chunk-ZOA2LIG4.js +1 -0
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +17 -17
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-portable.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +2 -2
- package/chunk-Q4R6KJCT.js +0 -1
|
@@ -427,15 +427,21 @@ export interface CommentToolClickedEvent extends CommentToolClickEvent {
|
|
|
427
427
|
}
|
|
428
428
|
export interface SidebarButtonClickEvent {
|
|
429
429
|
metadata?: VeltEventMetadata;
|
|
430
|
+
/** Set only when the button is bound to a named Sidebar V2 (`sidebar-id`); absent for the default button. */
|
|
431
|
+
sidebarId?: string;
|
|
430
432
|
}
|
|
431
433
|
export interface SidebarButtonClickedEvent extends SidebarButtonClickEvent {
|
|
432
434
|
}
|
|
433
435
|
/** Fired when the comment sidebar opens. Subscribe via `commentElement.on('sidebarOpen')`. */
|
|
434
436
|
export interface SidebarOpenEvent {
|
|
437
|
+
/** The `sidebar-id` of the named sidebar that emitted the event. Absent for the default sidebar. */
|
|
438
|
+
sidebarId?: string;
|
|
435
439
|
metadata?: VeltEventMetadata;
|
|
436
440
|
}
|
|
437
441
|
/** Fired when the comment sidebar closes. Subscribe via `commentElement.on('sidebarClose')`. */
|
|
438
442
|
export interface SidebarCloseEvent {
|
|
443
|
+
/** The `sidebar-id` of the named sidebar that emitted the event. Absent for the default sidebar. */
|
|
444
|
+
sidebarId?: string;
|
|
439
445
|
metadata?: VeltEventMetadata;
|
|
440
446
|
}
|
|
441
447
|
/**
|
|
@@ -445,6 +451,8 @@ export interface SidebarCloseEvent {
|
|
|
445
451
|
*/
|
|
446
452
|
export interface FullscreenClickEvent {
|
|
447
453
|
fullScreen: boolean;
|
|
454
|
+
/** The `sidebar-id` of the named sidebar that emitted the event. Absent for the default sidebar. */
|
|
455
|
+
sidebarId?: string;
|
|
448
456
|
metadata?: VeltEventMetadata;
|
|
449
457
|
}
|
|
450
458
|
/** Fired when a comment is clicked in the sidebar list. Subscribe via `commentElement.on('commentClick')`. */
|
|
@@ -456,6 +464,8 @@ export interface CommentClickEvent {
|
|
|
456
464
|
[key: string]: any;
|
|
457
465
|
};
|
|
458
466
|
annotation?: CommentAnnotation;
|
|
467
|
+
/** The `sidebar-id` of the named sidebar that emitted the event. Absent for the default sidebar. */
|
|
468
|
+
sidebarId?: string;
|
|
459
469
|
metadata?: VeltEventMetadata;
|
|
460
470
|
}
|
|
461
471
|
/**
|
|
@@ -105,5 +105,40 @@ export interface OpenCommentSidebarConfig {
|
|
|
105
105
|
* select the annotation (no pin dialog opens) and does not move keyboard focus. Sidebar V2 only.
|
|
106
106
|
*/
|
|
107
107
|
annotationId?: string;
|
|
108
|
+
/**
|
|
109
|
+
* Open the Sidebar V2 instance mounted with this `sidebar-id` instead of the default sidebar.
|
|
110
|
+
* Without it the call opens the default (unnamed) sidebar exactly as before. When the named
|
|
111
|
+
* sidebar is not mounted, one warning is logged and nothing opens. When `annotationId` is
|
|
112
|
+
* outside that sidebar's `scope`, one warning is logged and nothing is focused (the scope is
|
|
113
|
+
* never widened).
|
|
114
|
+
*/
|
|
115
|
+
sidebarId?: string;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Optional config for `closeCommentSidebar(config?)` and `toggleCommentSidebar(config?)`.
|
|
119
|
+
* Without `sidebarId` both calls act on the default sidebar exactly as before.
|
|
120
|
+
*/
|
|
121
|
+
export interface CommentSidebarInstanceConfig {
|
|
122
|
+
/** Act on the Sidebar V2 instance mounted with this `sidebar-id`. */
|
|
123
|
+
sidebarId?: string;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* One rule of a Sidebar V2 `scope`. It matches an annotation when the value at `path` (a dot
|
|
127
|
+
* path on the annotation, for example `sourceType` or `checkInfo.ruleKey`) equals any entry of
|
|
128
|
+
* `values`, with typed equality (no string coercion). An array at the path matches when any
|
|
129
|
+
* element matches. A missing, undefined or null value never matches.
|
|
130
|
+
*/
|
|
131
|
+
export interface CommentSidebarScopeRule {
|
|
132
|
+
path: string;
|
|
133
|
+
values: Array<string | number | boolean>;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* A fixed, non-clearable pre-filter for one Sidebar V2 instance (the `scope` attribute). An
|
|
137
|
+
* annotation is in scope when EVERY `include` rule matches and NO `exclude` rule matches.
|
|
138
|
+
* Filters, facets, counts, search, Reset, grouping and empty states all work inside the scope.
|
|
139
|
+
*/
|
|
140
|
+
export interface CommentSidebarScope {
|
|
141
|
+
include?: CommentSidebarScopeRule[];
|
|
142
|
+
exclude?: CommentSidebarScopeRule[];
|
|
108
143
|
}
|
|
109
144
|
export {};
|
|
@@ -7,7 +7,7 @@ import { AutocompleteData } from "../data/autocomplete.data.model";
|
|
|
7
7
|
import { AcceptSuggestionRequest, RejectSuggestionRequest, AcceptCommentAnnotationRequest, AddAttachmentRequest, AddAttachmentResponse, AddCommentAnnotationRequest, AddCommentRequest, AddReactionRequest, ApproveCommentAnnotationRequest, AssignUserRequest, CommentRequestQuery, CommentVisibilityConfig, ClearComposerRequest, CopyLinkRequest, DeleteAttachmentRequest, DeleteCommentAnnotationRequest, DeleteCommentRequest, DeleteReactionRequest, DeleteRecordingRequest, FetchCommentAnnotationsRequest, FormatConfig, GetAttachmentRequest, GetCommentRequest, GetComposerDataRequest, GetLinkRequest, GetRecordingRequest, PrivateModeConfig, RejectCommentAnnotationRequest, ResolveCommentAnnotationRequest, SubmitCommentRequest, SubscribeCommentAnnotationRequest, ToggleReactionRequest, UnsubscribeCommentAnnotationRequest, UpdateAccessRequest, UpdateCommentRequest, UpdatePriorityRequest, UpdateStatusRequest } from "../data/comment-actions.data.model";
|
|
8
8
|
import { CommentAnnotation, CommentOnElementConfig, CommentSelectionChangeData, ManualCommentAnnotationConfig, UpdateContextConfig } from "../data/comment-annotation.data.model";
|
|
9
9
|
import { SuggestionAcceptEvent, SuggestionRejectEvent, AcceptCommentAnnotationEvent, AddCommentAnnotationEvent, AddCommentEvent, AddReactionEvent, ApproveCommentAnnotationEvent, AssignToConfig, AssignUserEvent, CommentAddEventData, CommentEventTypesMap, CommentUpdateEventData, ComposerTextChangeEvent, CopyLinkEvent, DeleteAttachmentEvent, DeleteCommentAnnotationEvent, DeleteCommentEvent, DeleteReactionEvent, DeleteRecordingEvent, FetchCommentAnnotationsResponse, GetCommentAnnotationsCountResponse, GetCommentAnnotationsResponse, GetLinkResponse, PageModeComposerConfig, RejectCommentAnnotationEvent, SubscribeCommentAnnotationEvent, UnsubscribeCommentAnnotationEvent, ToggleReactionEvent, UpdateAccessEvent, UpdateCommentEvent, UpdatePriorityEvent, UpdateStatusEvent } from "../data/comment-events.data.model";
|
|
10
|
-
import { CommentSidebarCustomActionEventData, CommentSidebarCustomActionsState, CommentSidebarData, CommentSidebarDataOptions, OpenCommentSidebarConfig } from "../data/comment-sidebar-config.model";
|
|
10
|
+
import { CommentSidebarCustomActionEventData, CommentSidebarCustomActionsState, CommentSidebarData, CommentSidebarDataOptions, OpenCommentSidebarConfig, CommentSidebarInstanceConfig } from "../data/comment-sidebar-config.model";
|
|
11
11
|
import { CommentContextProvider, IdScopedAnchoringConfig, TransformContext, UnreadCommentsCount } from "../data/comment-utils.data.model";
|
|
12
12
|
import { CustomAnnotationDropdownData } from "../data/custom-chip-dropdown.data.model";
|
|
13
13
|
import { CustomCategory, CustomPriority, CustomStatus } from "../data/custom-filter.data.model";
|
|
@@ -75,18 +75,21 @@ export declare class CommentElement {
|
|
|
75
75
|
* To open comment sidebar
|
|
76
76
|
* @param config Optional. `{ annotationId }` opens the sidebar on that thread: focused view with
|
|
77
77
|
* `focusedThreadMode` + `openAnnotationInFocusMode`, otherwise its card is scrolled into view (sidebar V2).
|
|
78
|
+
* `{ sidebarId }` opens the Sidebar V2 mounted with that `sidebar-id` instead of the default sidebar.
|
|
78
79
|
*/
|
|
79
80
|
openCommentSidebar: (config?: OpenCommentSidebarConfig) => void;
|
|
80
81
|
|
|
81
82
|
/**
|
|
82
83
|
* To close comment sidebar
|
|
84
|
+
* @param config Optional. `{ sidebarId }` closes the Sidebar V2 mounted with that `sidebar-id`.
|
|
83
85
|
*/
|
|
84
|
-
closeCommentSidebar: ()
|
|
86
|
+
closeCommentSidebar: { (): void; (config?: CommentSidebarInstanceConfig): void };
|
|
85
87
|
|
|
86
88
|
/**
|
|
87
89
|
* To toggle comment sidebar
|
|
90
|
+
* @param config Optional. `{ sidebarId }` toggles the Sidebar V2 mounted with that `sidebar-id`.
|
|
88
91
|
*/
|
|
89
|
-
toggleCommentSidebar: ()
|
|
92
|
+
toggleCommentSidebar: { (): void; (config?: CommentSidebarInstanceConfig): void };
|
|
90
93
|
|
|
91
94
|
/**
|
|
92
95
|
* To enable context in page mode composer feature
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as V}from"./chunk-
|
|
1
|
+
import{i as V}from"./chunk-ZOA2LIG4.js";import{Ga as x,Ha as L,Ja as D,M as C,R as v,S as I}from"./chunk-7KXS2DSG.js";import{Wa as m,_a as d,_i as y,a as s,b as h,fa as o,oj as E,qj as U,sa as f,xc as u,ya as S,zc as p}from"./chunk-QUMZPTVX.js";var A=(()=>{let r=class r extends D{set parentLocalUIState(t){try{t&&(this.localUIStateSignal=t,this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!0)}catch{}}get elementRef(){try{return this.hostElementRef}catch{return null}}getServiceComponentConfigSignal(){}constructor(){let t=o(S),e=o(L),i=o(p),a=o(E).get(y),g=o(x),l=o(U);super(t,e,i,a??void 0,void 0,g,l),this.defaultCondition=u(!0,{transform:n=>{try{return typeof n=="string"?n==="true"||n==="":n}catch{return!0}}}),this.isLocalUIStateOwner=!1,this._localUIStateFromExplicitInput=!1,this.veltContextHost=new V({getHost:()=>this.hostElementRef?.nativeElement,ownerRef:this,getEntity:()=>this.getPublishedVeltEntity(),getLocalUIState:()=>this.isLocalUIStateOwner?this.localUIStateSignal:void 0,onContextChanged:()=>{this.adoptInheritedLocalUIState(),this.rebindServiceConfigFromPlacement(),this.onVeltContextChanged()},markForCheck:()=>this.cd?.markForCheck()}),this.isLocalUIStateRoot=!1,this.selfConnectedConfig=!1,this.ownsConfigSignal=!0;try{this.hostElementRef=t,this.themeService=e,this.dynamicDataService=g,this.loggingService=l,this.cd=i,this.commentService=a??void 0,this.initializeLocalUIState()}catch(n){this.loggingService=this.loggingService||l,this.loggingService?.catch?.("Error in V2PrimitiveThemedBase constructor:",n)}}initializeLocalUIState(){this.localUIStateSignal=f(this.getDefaultLocalUIState()),this.isLocalUIStateOwner=!0}getConditionalClassesContext(){return{componentConfigSignal:this.componentConfigSignal}}ngOnInit(){try{this.adoptInheritedLocalUIState(),this.connectToServiceSignalIfStandalone(),this.dynamicDataService.applyConditionalClasses(this.hostElementRef?.nativeElement,this.getConditionalClassesContext()),this.setupA11yAttributes(),this.isLocalUIStateOwner&&this.setupDarkModeSync(),this.finalizeVeltContext()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnInit:",t)}}adoptInheritedLocalUIState(){try{v({host:this.hostElementRef?.nativeElement,current:this.localUIStateSignal,isOwner:this.isLocalUIStateOwner,fromExplicitInput:this._localUIStateFromExplicitInput,isRoot:this.isLocalUIStateRoot,adopt:t=>{this.localUIStateSignal=t,this.isLocalUIStateOwner=!1}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase adoptInheritedLocalUIState:",t)}}rebindServiceConfigFromPlacement(){try{if(!this.selfConnectedConfig)return;let t=this.getServiceComponentConfigSignal();if(!t||t===this.componentConfigSignal)return;let e=this.componentConfigSignal,i=this.ownsConfigSignal;if(this.componentConfigSignal=t,this.ownsConfigSignal=!1,i)try{e?.update(a=>s({},a))}catch{}this.cd?.markForCheck()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase rebindServiceConfigFromPlacement:",t)}}finalizeVeltContext(){this.veltContextHost.finalize()}getPublishedVeltEntity(){}getInheritedVeltEntity(){try{return I(this.hostElementRef?.nativeElement)}catch{return}}refreshVeltContextFromPlacement(){this.veltContextHost.refreshFromPlacement()}onVeltContextChanged(){}getInheritedVeltContextData(){try{return C(this.hostElementRef?.nativeElement)?.payload?.contextData||{}}catch{return{}}}connectToServiceSignalIfStandalone(){try{let t=this.componentConfigSignal();if(!t||!t?.uiState){this.selfConnectedConfig=!0;let e=this.getServiceComponentConfigSignal();e&&(this.componentConfigSignal=e,this.ownsConfigSignal=!1)}}catch(t){this.loggingService.catch("Error connecting to service signal:",t)}}ngOnDestroy(){try{this.darkModeConfigSyncSubscription&&this.darkModeConfigSyncSubscription.unsubscribe(),this.veltContextHost.destroy(),super.ngOnDestroy()}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase ngOnDestroy:",t)}}setupA11yAttributes(){}setupDarkModeSync(){try{this.darkModeConfigSyncSubscription=this.onDarkModeChange().subscribe(t=>{try{if(this.componentConfigSignal&&typeof this.componentConfigSignal=="function"){let e=this.componentConfigSignal();e&&e.uiState&&e.uiState.darkMode!==t&&this.componentConfigSignal.update(i=>h(s({},i),{uiState:h(s({},i.uiState),{darkMode:t})}))}}catch(e){this.loggingService.catch("Error in darkMode sync subscription:",e)}})}catch(t){this.loggingService.catch("Error in V2PrimitiveThemedBase setupDarkModeSync:",t)}}};r.\u0275fac=function(e){return new(e||r)},r.\u0275cmp=m({type:r,selectors:[["app-v2-primitive-themed-base"]],inputs:{defaultCondition:[1,"defaultCondition"],parentLocalUIState:"parentLocalUIState"},standalone:!1,features:[d],decls:0,vars:0,template:function(e,i){},encapsulation:2});let c=r;return c})();export{A as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as s,K as a,ba as c,ea as n,l as o,qj as h}from"./chunk-
|
|
1
|
+
import{B as s,K as a,ba as c,ea as n,l as o,qj as h}from"./chunk-QUMZPTVX.js";var u=(()=>{let r=class r{constructor(t){this.loggingService=t,this.toasts$=new o([])}setToast(t){try{t.id||(t.id=Math.random()),this.toasts$.next([...this.toasts$.value,t]),t.duration&&t.duration>0&&s(t.duration).pipe(a(1)).subscribe(()=>{this.removeToast(t)},i=>{this.loggingService.catch("Error in ToastService setToast timer subscription: ",i)})}catch(i){this.loggingService.catch("Error in ToastService setToast: ",i)}}removeToast(t){try{this.toasts$.next(this.toasts$.value.filter(i=>i.id!==t.id))}catch(i){this.loggingService.catch("Error in ToastService removeToast: ",i)}}getToasts$(){return this.toasts$.asObservable()}};r.\u0275fac=function(i){return new(i||r)(n(h))},r.\u0275prov=c({token:r,factory:r.\u0275fac,providedIn:"root"});let e=r;return e})();export{u as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as P,j as ae}from"./chunk-BCCFAKMJ.js";import{G as he,H as fe}from"./chunk-7D33ZDW3.js";import{He as A,Kg as D,M as O,V as Z,Xa as ne,Xe as ge,Ya as se,Ze as ue,_i as U,a as b,aa as ee,ac as oe,b as M,ba as x,c as J,ca as te,de as p,di as z,ea as S,g as Y,i as C,k as B,l as Q,oj as de,qd as ce,qj as R,r as $,sa as re,ui as le,v as k,wa as ie,xg as _}from"./chunk-Q6PUYIXT.js";var V=class{_totalWeight=0;_averageItemSize;_defaultItemSize;constructor(n=50){this._defaultItemSize=n,this._averageItemSize=n}getAverageItemSize(){return this._averageItemSize}addSample(n,a){let e=this._totalWeight+n.end-n.start;if(e){let t=(a+this._averageItemSize*this._totalWeight)/e;t&&(this._averageItemSize=t,this._totalWeight=e)}}reset(){this._averageItemSize=this._defaultItemSize,this._totalWeight=0}},H=class{scrolledIndexChange=new C(()=>{});_viewport=null;_minBufferPx;_maxBufferPx;_averager;_lastScrollOffset;_lastRenderedContentSize;_lastRenderedContentOffset;_removalFailures=0;constructor(n,a,e=new V){this._minBufferPx=n,this._maxBufferPx=a,this._averager=e}attach(n){this._averager.reset(),this._viewport=n,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(n,a){if(a<n)throw Error("CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx");this._minBufferPx=n,this._maxBufferPx=a}_updateRenderedContentAfterScroll(){let n=this._viewport,a=n.measureScrollOffset(),e=a-this._lastScrollOffset,t=Math.abs(e),r=n.getRenderedRange(),i=0;if(e<0){let l=r.start*this._averager.getAverageItemSize()-this._lastRenderedContentOffset;i=Math.round(l*Math.max(0,Math.min(1,t/(a+t)))),e=e-i,t=Math.abs(e)}let o=this._lastScrollOffset-this._lastRenderedContentOffset,c=this._lastRenderedContentOffset+this._lastRenderedContentSize-(this._lastScrollOffset+n.getViewportSize()),u=t+this._minBufferPx-(e<0?o:c);if(u>0)if(t>=n.getViewportSize())this._renderContentForCurrentOffset();else{let g=Math.max(0,Math.ceil((u-this._minBufferPx+this._maxBufferPx)/this._averager.getAverageItemSize())),l=(e<0?c:o)-this._minBufferPx+t,h=Math.floor(l/this._averager.getAverageItemSize()/(this._removalFailures+1)),f=Math.min(r.end-r.start,Math.max(0,h)),d=this._expandRange(r,e<0?g:0,e>0?g:0);e<0?d.end=Math.max(d.start+1,d.end-f):d.start=Math.min(d.end-1,d.start+f);let v,E;if(e<0){let y=n.measureRangeSize({start:d.end,end:r.end});y<=l?(v=this._lastRenderedContentOffset+this._lastRenderedContentSize-y,this._removalFailures=0):(d.end=r.end,v=this._lastRenderedContentOffset+this._lastRenderedContentSize,this._removalFailures++),E="to-end"}else{let y=n.measureRangeSize({start:r.start,end:d.start});y<=l?(v=this._lastRenderedContentOffset+y,this._removalFailures=0):(d.start=r.start,v=this._lastRenderedContentOffset,this._removalFailures++),E="to-start"}n.setRenderedRange(d),n.setRenderedContentOffset(v+i,E)}else i&&n.setRenderedContentOffset(this._lastRenderedContentOffset+i);this._lastScrollOffset=a}_checkRenderedContentSize(){let n=this._viewport;this._lastRenderedContentSize=n.measureRenderedContentSize(),this._averager.addSample(n.getRenderedRange(),this._lastRenderedContentSize),this._updateTotalContentSize(this._lastRenderedContentSize)}_checkRenderedContentOffset(){let n=this._viewport;this._lastRenderedContentOffset=n.getOffsetToRenderedContentStart()}_renderContentForCurrentOffset(){let n=this._viewport,a=n.measureScrollOffset();this._lastScrollOffset=a,this._removalFailures=0;let e=this._averager.getAverageItemSize(),t=Math.min(n.getDataLength()-1,Math.floor(a/e)),r=Math.ceil(this._maxBufferPx/e),i=this._expandRange(this._getVisibleRangeForIndex(t),r,r);n.setRenderedRange(i),n.setRenderedContentOffset(e*i.start)}_getVisibleRangeForIndex(n){let a=this._viewport,e={start:n,end:n+Math.ceil(a.getViewportSize()/this._averager.getAverageItemSize())},t=e.end-a.getDataLength();return t>0&&(e.start=Math.max(0,e.start-t)),e}_expandRange(n,a,e){let t=this._viewport,r=Math.max(0,n.start-a),i=Math.min(t.getDataLength(),n.end+e);return{start:r,end:i}}_updateTotalContentSize(n){let a=this._viewport,e=a.getRenderedRange(),t=n+(a.getDataLength()-(e.end-e.start))*this._averager.getAverageItemSize();a.setTotalContentSize(t)}};function Ae(s){return s._scrollStrategy}var Ue=(()=>{class s{get minBufferPx(){return this._minBufferPx}set minBufferPx(a){this._minBufferPx=P(a)}_minBufferPx=100;get maxBufferPx(){return this._maxBufferPx}set maxBufferPx(a){this._maxBufferPx=P(a)}_maxBufferPx=200;_scrollStrategy=new H(this.minBufferPx,this.maxBufferPx);ngOnChanges(){this._scrollStrategy.updateBufferSize(this.minBufferPx,this.maxBufferPx)}static \u0275fac=function(e){return new(e||s)};static \u0275dir=se({type:s,selectors:[["cdk-virtual-scroll-viewport","autosize",""]],inputs:{minBufferPx:"minBufferPx",maxBufferPx:"maxBufferPx"},features:[oe([{provide:ae,useFactory:Ae,deps:[ee(()=>s)]}]),ie]})}return s})(),Ve=(()=>{class s{static \u0275fac=function(e){return new(e||s)};static \u0275mod=ne({type:s});static \u0275inj=te({})}return s})();var xe=["removed","added","contextBefore","contextAfter","occurrence"];function q(s){if(s==null)return{value:null,reason:null,droppedKeys:[]};let n=typeof s=="object"?Object.getPrototypeOf(s):void 0;if(n!==Object.prototype&&n!==null)return{value:null,reason:"it is not a plain object",droppedKeys:[]};let a=s;for(let i of["removed","added","contextBefore","contextAfter"])if(typeof a[i]!="string")return{value:null,reason:`"${i}" must be a string`,droppedKeys:[]};let e=a.occurrence;if(typeof e!="number"||!Number.isInteger(e)||e<1)return{value:null,reason:'"occurrence" must be an integer of 1 or more',droppedKeys:[]};let t={removed:a.removed,added:a.added,contextBefore:a.contextBefore,contextAfter:a.contextAfter,occurrence:e};if(t.removed.length+t.added.length>8192)return{value:null,reason:'"removed" and "added" together are longer than 8192 characters',droppedKeys:[]};let r=Object.keys(a).filter(i=>!xe.includes(i));return{value:t,reason:null,droppedKeys:r}}function _e(s,n,a){if(!n)return 0;let e=0,t=0;for(;;){let r=s.indexOf(n,t);if(r<0||r>=a)return e;e++,t=r+1}}var Re=s=>s>=55296&&s<=56319,we=s=>s>=56320&&s<=57343,I=(s,n)=>n>0&&n<s.length&&Re(s.charCodeAt(n-1))&&we(s.charCodeAt(n)),Oe=/[\p{L}\p{N}_]/u,w=s=>!!s&&Oe.test(s),m=s=>s.replace(/\u00a0/g," ");function Se(s,n){let a=m(s),e=m(n),t=Math.min(a.length,e.length),r=0;for(;r<t&&a.charCodeAt(r)===e.charCodeAt(r);)r++;let i=0;for(;i<t-r&&a.charCodeAt(a.length-1-i)===e.charCodeAt(e.length-1-i);)i++;let o=a.length-r-i,c=e.length-r-i;if(o>0&&c>0){for(;r>0&&w(a[r-1])&&(w(a[r])||w(e[r]));)r--;for(;i<t-r&&a.charCodeAt(a.length-1-i)===e.charCodeAt(e.length-1-i);)i++;for(;i>0&&w(a[a.length-i])&&(w(a[a.length-i-1])||w(e[e.length-i-1]));)i--}else if(o+c>0){let u=o>0?a:e,g=o+c,l=f=>w(u[f])&&!w(u[f-1]),h=r;for(let f=r;f>0&&u[f-1]===u[f+g-1];)f--,l(f)&&(h=f);!l(r)&&h!==r&&(i+=r-h,r=h)}for(;r>0&&(I(a,r)||I(e,r));)r--;for(;i>0&&(I(a,a.length-i)||I(e,e.length-i));)i--;return{prefix:r,suffix:i}}function N(s,n,a,e){if(n<0||a<n||a>s.length)return null;let t=s.slice(n,a);if(m(t)===m(e)||t.length+e.length>8192)return null;let r=Math.max(0,n-32);I(s,r)&&r++;let i=Math.min(s.length,a+32);I(s,i)&&i--;let o=s.slice(r,n),c=s.slice(a,i),u=o+t+c,g=1+_e(s,u,r);return{removed:t,added:e,contextBefore:o,contextAfter:c,occurrence:g}}function me(s,n,a){return m(n).includes(m(s.contextBefore+s.removed+s.contextAfter))&&m(a).includes(m(s.contextBefore+s.added+s.contextAfter))}function G(s){return{removed:m(s.removed),added:m(s.added),contextBefore:m(s.contextBefore),contextAfter:m(s.contextAfter),occurrence:s.occurrence}}function ve(s,n){if(m(s)===m(n))return null;let{prefix:a,suffix:e}=Se(s,n);return N(s,a,s.length-e,n.slice(a,n.length-e))}function qe(s,n){if(m(s)===m(n))return null;let{prefix:a,suffix:e}=Se(s,n);return{removed:s.slice(a,s.length-e),start:a,end:n.length-e}}var j=(()=>{let n=class n{constructor(e){this.loggingService=e,this.enabledSignal=re(!1),this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0;try{this.enabled$=ce(this.enabledSignal).pipe(O())}catch(t){this.loggingService.catch("Error in SuggestionModeService constructor: ",t),this.enabled$=new C}}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}}};n.\u0275fac=function(t){return new(t||n)(S(R))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var L=(()=>{let n=class n{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(i){return _()&&this.loggingService.catch(`[velt] Suggestion target "${e}" getter threw: `,i),!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(i){return _()&&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.`,i),!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)}}};n.\u0275fac=function(t){return new(t||n)(S(R))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var Ee=(()=>{let n=class n{constructor(e,t,r){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.registry=new Map,this.warnedUnstableIds=new Set,this.latestEdit=new Map,this.editSeq=0,this.actionsService=null,this.typedEditSource=null}registerTarget(e,t,r){try{if(!e||typeof t!="function")return;this.warnIfUnstableId(e);let i=this.registry.get(e)??{};i.getter=t,i.setter=typeof r?.setter=="function"?r.setter:void 0,i.restoreOnCommit=r?.restoreOnCommit,this.registry.set(e,i)}catch(i){this.loggingService.catch("Error in SuggestionTargetRegistryService registerTarget: ",i)}}unregisterTarget(e){try{let t=this.registry.get(e);if(!t)return;delete t.getter,delete t.setter,delete t.restoreOnCommit,this.latestEdit.delete(e),t.node||this.registry.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService unregisterTarget: ",t)}}getSetter(e){try{return this.registry.get(e)?.setter}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getSetter: ",t);return}}callSetter(e,t,r){return this.runSetter(e,t,r)!==null}runSetter(e,t,r){let i=this.registry.get(e)?.setter;if(!i)return null;let o=c=>this.loggingService.catch("Error in SuggestionTargetRegistryService: the target setter threw",c,{targetId:e,reason:r.reason});try{let c=i(t,b({targetId:e},r));if(c&&typeof c.then=="function")return Promise.resolve(c).catch(o)}catch(c){o(c)}return Promise.resolve()}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 i=r[0],o=this.registry.get(e)??{};return o.node=i,this.registry.set(e,o),i}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getNode: ",t);return}}setTypedEditSource(e){this.typedEditSource=e}getTypedEdits(e){try{return this.typedEditSource?.(e)??[]}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService getTypedEdits: ",t),[]}}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(`[${A.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:[A.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.latestEdit.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),i={targetId:t.targetId,oldValue:r,newValue:r,element:t.element},o=this.modeService.getOnTargetEditStart();if(o)try{o(i)}catch(c){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditStart customer callback threw: ",c)}this.actionsService?.triggerAction(p.TARGET_EDIT_START,{details:i,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),i=this.readElementValue(e,t);if(D(r,i))return;let o=this.splitTypedEdits(t,r,i),c=this.restoreWhenCommitted(e,r,o?o.length:1);if(o){o.forEach((u,g)=>this.commitEdit(e,t,r,u.newValue,u.textChange,!0,c?.(g)));return}this.commitEdit(e,t,r,i,void 0,!1,c?.(0))}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService processCommit: ",r)}}restoreWhenCommitted(e,t,r){let i=this.registry.get(e);if(!i?.setter||i.restoreOnCommit===!1){this.latestEdit.delete(e);return}let o=++this.editSeq;this.latestEdit.set(e,o);let c=new Set;return u=>g=>{try{if(!g||c.size===r||(c.add(u),c.size<r||this.latestEdit.get(e)!==o))return;this.latestEdit.delete(e);let l=this.runSetter(e,t,{reason:"restore"}),h=()=>{this.findTaggedAncestor(document.activeElement)?.targetId===e&&this.snapshotService.captureValue(e,t)};h(),l?.then(h,()=>{})}catch(l){this.loggingService.catch("Error in SuggestionTargetRegistryService restoreWhenCommitted: ",l)}}}splitTypedEdits(e,t,r){try{if(typeof t!="string"||typeof r!="string")return null;let i=this.getTypedEdits(e);if(i.length<2)return null;let o=g=>g.replace(/\u00a0/g," ");if(i.some(g=>o(g.base)!==o(t)))return null;let c=t;for(let g of[...i].sort((l,h)=>h.start-l.start))c=c.slice(0,g.start)+g.added+c.slice(g.end);if(o(c)!==o(r))return null;let u=[];for(let g of i){let l=N(t,g.start,g.end,g.added);if(!l)return null;u.push({newValue:t.slice(0,g.start)+o(g.added)+t.slice(g.end),textChange:G(l)})}return u}catch(i){return this.loggingService.catch("Error in SuggestionTargetRegistryService splitTypedEdits: ",i),null}}commitEdit(e,t,r,i,o,c=!1,u){try{let g={targetId:e,oldValue:r,newValue:i,element:t},l=this.modeService.getOnTargetEditCommit(),h=null;if(l){let d=null;try{d=l(g)}catch(v){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditCommit customer callback threw: ",v)}d&&(h=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:d.summary,summaryHtml:d.summaryHtml,metadata:d.metadata,textChange:d.textChange??o}),u&&h.then(u))}else this.modeService.isAutoCommitEnabled()&&(h=this.invokeAutoCommit({targetId:e,newValue:i,textChange:o,snapshot:c?{value:r}:void 0}),u&&h.then(u));let f=d=>Y(this,null,function*(){if(h&&(yield h))return null;let v=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:d?.summary,summaryHtml:d?.summaryHtml,metadata:d?.metadata,textChange:d?.textChange??o});return u&&v.then(u),v});this.actionsService?.triggerAction(p.TARGET_EDIT_COMMIT,{details:g,commitSuggestion:f,timestamp:Date.now()})}catch(g){this.loggingService.catch("Error in SuggestionTargetRegistryService commitEdit: ",g)}}invokeAutoCommit(r){var i=r,{snapshot:e}=i,t=J(i,["snapshot"]);try{return e&&this.snapshotService.captureValue(t.targetId,e.value),this.actionsService?this.actionsService.commitSuggestion(t).catch(o=>(_()&&this.loggingService.catch(`[velt] auto-commit for "${t.targetId}" rejected: `,o),null)):(_()&&this.loggingService.log("[velt] auto-commit skipped: actions service not wired. SuggestionActionsService constructor should call registry.setActionsService(this)."),Promise.resolve(null))}catch(o){return this.loggingService.catch("Error in SuggestionTargetRegistryService invokeAutoCommit: ",o),Promise.resolve(null)}}captureSnapshotForTarget(e,t){try{let r=this.registry.get(e);if(r?.getter){this.snapshotService.captureFromGetter(e,r.getter);return}let i=this.readElementValue(e,t);this.snapshotService.captureValue(e,i)}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 i=(t.type||"").toLowerCase();return i==="checkbox"||i==="radio"?t.checked:i==="number"||i==="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(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`);if(!t)return null;let r=t.getAttribute(A.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(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}="${t}"]`))}catch{return[]}}scanAndRefresh(e){try{e.querySelectorAll(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).forEach(r=>{let i=r.getAttribute(A.ATTRIBUTES.VELT_SUGGESTION_TARGET);if(!i)return;let o=this.registry.get(i)??{};(!o.node||!o.node.isConnected)&&(o.node=r,this.registry.set(i,o))})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService scanAndRefresh: ",t)}}warnIfUnstableId(e){try{if(!_()||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(!_())return;this.loggingService.catch(`[velt] Duplicate target id "${e}" \u2014 ${t} elements share this id. Cause: the same ${A.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)}}};n.\u0275fac=function(t){return new(t||n)(S(R),S(j),S(L))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var Me=new Set(["apiKey","documentId","clientDocumentId","organizationId","clientOrganizationId","folderId","veltFolderId","parentVeltFolderId","documentMetadata","sdkVersion","pageInfo"]),St=(()=>{let n=class n{constructor(e,t,r,i,o,c,u){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.targetRegistry=i,this.serviceBook=o,this.commonDbService=c,this.docService=u,this.actionSubjects=new Map,this.appliedValues=new Map,this.observingActive=!1,this.commentService=null,this.inlineSuggestionsEnabled$=new Q(!0);try{this.targetRegistry.setActionsService(this),this.serviceBook.observe(U).subscribe(g=>{this.commentService=g})}catch(g){this.loggingService.catch("Error in SuggestionActionsService constructor: ",g)}}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}}enableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value||this.inlineSuggestionsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in SuggestionActionsService enableInlineSuggestions: ",e)}}disableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value&&this.inlineSuggestionsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in SuggestionActionsService disableInlineSuggestions: ",e)}}isInlineSuggestionsEnabled$(){return this.inlineSuggestionsEnabled$.pipe(O())}isSuggestionModeEnabled$(){try{return this.modeService.enabled$}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled$: ",e),new C}}registerTarget(e){try{if(!e?.targetId||typeof e?.getter!="function")return;this.targetRegistry.registerTarget(e.targetId,e.getter,{setter:e.setter,restoreOnCommit:e.restoreOnCommit})}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 E=this.targetRegistry.getGetter(e.targetId);if(E){if(!this.snapshotService.captureFromGetter(e.targetId,E)){r(new Error("SNAPSHOT_FAILED"));return}}else{let y=this.targetRegistry.getFallbackValue(e.targetId);if(y.hasValue)this.snapshotService.captureValue(e.targetId,y.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),g=e.newValue;if(D(u,g)){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 l=new ge;l.type="suggestion",l.suggestion={status:"pending",targetId:e.targetId,targetType:"custom",oldValue:u,newValue:g,summary:e.summary??null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},this.setCustomerMetadata(l.suggestion,e.metadata),this.setTextChange(l.suggestion,e.targetId,e.textChange,u,g);let h=this.resolveSuggestionLocation(e),f=this.resolveSuggestionContext(e),d=Fe(e.summary,e.summaryHtml,u,g),v=new ue;if(v.commentText=d.commentText,v.commentHtml=d.commentHtml,l.comments=[v],!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,h?.location,void 0,void 0,void 0,void 0,void 0,E=>{try{this.snapshotService.clearSnapshot(e.targetId),this.projectAndTrigger(p.SUGGESTION_CREATED,E.annotation),t({id:E.annotation.annotationId})}catch(y){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion callback: ",y),r(y)}},void 0,void 0,l,h?.locationId,f,!0,void 0,void 0,"internal",h?.locationId!==void 0?!0:void 0)}catch(i){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion: ",i),r(i)}})}getSuggestions(e){try{let t=this.commentService?.getCommentAnnotationsOnCurrentOrganizationAndDocument()??[],r=[];for(let i of t){if(!i.suggestion)continue;let o=this.projectAnnotationToSuggestion(i);o&&this.matchesFilter(o,e)&&r.push(o)}return r}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions: ",t),[]}}getSuggestions$(e){try{return this.serviceBook.observe(U).pipe(Z(t=>t?t.getCommentAnnotationsOnCurrentOrganizationAndDocument$():$([]))).pipe(k(t=>{let r=[];for(let i of t??[]){if(!i.suggestion)continue;let o=this.projectAnnotationToSuggestion(i);o&&this.matchesFilter(o,e)&&r.push(o)}return r}),O(z))}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions$: ",t),new C}}getPendingSuggestion(e){try{if(!e)return null;let t=this.getSuggestions({targetId:e,status:"pending"});return t.length===0?null:t.sort((r,i)=>(i.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(k(t=>t.length===0?null:t.sort((r,i)=>(i.createdAt??0)-(r.createdAt??0))[0]),O(z)):new C}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion$: ",t),new C}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new B),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 B),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 i=this.timestamp;switch(e){case p.SUGGESTION_CREATED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_CREATED,o);break}case p.SUGGESTION_APPROVED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_APPROVED,o);break}case p.SUGGESTION_REJECTED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_REJECTED,o);break}case p.SUGGESTION_STALE:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_STALE,o);break}}}catch(r){this.loggingService.catch("Error in SuggestionActionsService projectAndTrigger: ",r)}}resolveSuggestionContext(e){try{let t=e.context;if(t==null)return;if(typeof t!="object"||Array.isArray(t)){this.loggingService.warn('[velt] commitSuggestion: context was not saved. Cause: it is not an object. Fix: pass an object, e.g. { textEditorConfig: { editorId: "<editor id>" } }. Docs: velt.dev/docs/suggestions');return}let r;try{r=JSON.parse(JSON.stringify(t))}catch{this.loggingService.warn("[velt] commitSuggestion: context was not saved. Cause: it cannot be stored as JSON (e.g. it refers to itself). Fix: pass plain JSON data. Docs: velt.dev/docs/suggestions");return}if(r===null||typeof r!="object"||Array.isArray(r)){this.loggingService.warn('[velt] commitSuggestion: context was not saved. Cause: it is not stored as an object (e.g. a Date). Fix: pass an object, e.g. { textEditorConfig: { editorId: "<editor id>" } }. Docs: velt.dev/docs/suggestions');return}let i=De.filter(o=>o in r);return i.length&&(i.forEach(o=>delete r[o]),this.loggingService.warn(`[velt] commitSuggestion: context keys ${i.join(", ")} were not saved. Cause: the SDK sets them. Fix: leave them out (use \`access\` for context access). Docs: velt.dev/docs/suggestions`)),r}catch(t){this.loggingService.catch("Error in SuggestionActionsService resolveSuggestionContext: ",t);return}}resolveSuggestionLocation(e){try{let t=null,r=e.location;if(r!=null){let o=typeof r=="object"&&!Array.isArray(r)?r.id:void 0;typeof o=="string"&&o.trim()?t=r:this.loggingService.warn('[velt] commitSuggestion: location was not used. Cause: it is not an object with a non-empty string id. Fix: pass { id: "<location id>" }, or omit it to use the location around the target element. Docs: velt.dev/docs/suggestions')}if(!t){let o=this.targetRegistry.getNode(e.targetId);t=o?this.docService.getAdditionLocationFromElement(o):null}if(!t?.id)return null;let i=this.docService.getLocationMetadataByClientLocationId(t.id);return i?.location?{location:i.location,locationId:i.locationId}:{location:t}}catch(t){return this.loggingService.catch("Error in SuggestionActionsService resolveSuggestionLocation: ",t),null}}setCustomerMetadata(e,t){let r=this.cloneCustomerMetadata(t);r&&(e.metadata=r)}setTextChange(e,t,r,i,o){try{let c=q(r);c.reason?this.loggingService.warn(`[velt] commitSuggestion: textChange was not saved. Cause: ${c.reason}. Fix: pass { removed, added, contextBefore, contextAfter, occurrence }. Docs: velt.dev/docs/suggestions`):c.droppedKeys.length&&this.loggingService.warn(`[velt] commitSuggestion: textChange keys ${c.droppedKeys.join(", ")} were not saved. Cause: they are not textChange keys. Fix: put your own data in metadata. Docs: velt.dev/docs/suggestions`);let u=c.value??this.computeTextChange(t,i,o);u&&(e.textChange=u)}catch(c){this.loggingService.catch("Error in SuggestionActionsService setTextChange: ",c)}}computeTextChange(e,t,r){if(typeof t!="string"||typeof r!="string")return null;let i=this.targetRegistry.getNode(e);if(!(i instanceof HTMLElement)||!i.isConnected||!i.isContentEditable||i.closest(".ProseMirror"))return null;for(let c of this.targetRegistry.getTypedEdits(i)??[]){let u=N(c.base,c.start,c.end,c.added);if(u&&me(u,t,r))return G(u)}let o=ve(t,r);return o&&G(o)}getTextChange(e){return q(e.textChange).value}cloneCustomerMetadata(e){if(e==null)return;let t=typeof e=="object"?Object.getPrototypeOf(e):void 0;if(t!==Object.prototype&&t!==null){this.loggingService.warn('[velt] commitSuggestion: metadata was not saved. Cause: it is not a plain object. Fix: pass a plain JSON object, e.g. { kind: "replacement" }. Docs: velt.dev/docs/suggestions');return}try{let r=le(e);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{this.loggingService.warn("[velt] commitSuggestion: metadata was not saved. Cause: it cannot be serialized as JSON (BigInt or a circular reference). Fix: pass JSON-safe values only. Docs: velt.dev/docs/suggestions");return}}getCustomerMetadata(e){let t=e.suggestion?.metadata;if(t&&typeof t=="object"&&!Array.isArray(t))return b({},t);let r={},i=e.metadata;if(i&&typeof i=="object")for(let o of Object.keys(i))Me.has(o)||Object.defineProperty(r,o,{value:i[o],enumerable:!0,writable:!0,configurable:!0});return r}setAppliedValues(e,t){this.appliedValues.set(e,t)}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:this.getCustomerMetadata(e),textChange:this.getTextChange(t),driftDetected:!!t.driftDetected,createdBy:e.from,createdAt:e.createdAt??0};switch(t.status){case"pending":return M(b({},r),{status:"pending",rejectReason:null,resolvedBy:null,resolvedAt:null});case"accepted":case"apply_failed":{let i=t.status==="accepted"?this.appliedValues.get(e.annotationId):void 0;return M(b(b({},r),i??{}),{status:t.status,rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp})}case"rejected":return M(b({},r),{status:"rejected",rejectReason:t.rejectReason??null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp});case"stale":return M(b({},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}}};n.\u0275fac=function(t){return new(t||n)(S(R),S(j),S(L),S(Ee),S(de),S(he),S(fe))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();function be(s){try{return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}catch{return""}}function T(s){try{if(s==null)return"";if(typeof s=="string")return s;if(typeof s=="object")try{return JSON.stringify(s)}catch{return String(s)}return String(s)}catch{return""}}var De=["accessFields","_setAccessFields","_replaceAccessFields","_setVisibilityConfig"];function Te(s){try{if(s===null||typeof s!="object"||Array.isArray(s))return!1;let n=Object.getPrototypeOf(s);return n===Object.prototype||n===null}catch{return!1}}function Ce(s,n){try{let a=s==null,e=n==null;if(a&&!e)return[{op:"add",newText:T(n)}];if(!a&&e)return[{op:"remove",oldText:T(s)}];if(Te(s)&&Te(n)){let t=s,r=n,i=[...Object.keys(t),...Object.keys(r).filter(c=>!(c in t))],o=[];for(let c of i){let u=c in t,g=c in r;u&&g?D(t[c],r[c])||o.push({op:"replace",oldText:`${c}: ${T(t[c])}`,newText:`${c}: ${T(r[c])}`}):u?o.push({op:"remove",oldText:`${c}: ${T(t[c])}`}):o.push({op:"add",newText:`${c}: ${T(r[c])}`})}if(o.length>0)return o}return[{op:"replace",oldText:T(s),newText:T(n)}]}catch{return[{op:"replace",oldText:T(s),newText:T(n)}]}}function Ne(s,n){try{return Ce(s,n).map(a=>a.op==="add"?`Add: "${a.newText??""}"`:a.op==="remove"?`Remove: "${a.oldText??""}"`:`Replace: "${a.oldText??""}" with "${a.newText??""}"`).join(`
|
|
1
|
+
import{f as P,j as ae}from"./chunk-7KXS2DSG.js";import{G as he,H as fe}from"./chunk-YKZV3FEU.js";import{He as A,Kg as D,M as O,V as Z,Xa as ne,Xe as ge,Ya as se,Ze as ue,_i as U,a as b,aa as ee,ac as oe,b as M,ba as x,c as J,ca as te,de as p,di as z,ea as S,g as Y,i as C,k as B,l as Q,oj as de,qd as ce,qj as R,r as $,sa as re,ui as le,v as k,wa as ie,xg as _}from"./chunk-QUMZPTVX.js";var V=class{_totalWeight=0;_averageItemSize;_defaultItemSize;constructor(n=50){this._defaultItemSize=n,this._averageItemSize=n}getAverageItemSize(){return this._averageItemSize}addSample(n,a){let e=this._totalWeight+n.end-n.start;if(e){let t=(a+this._averageItemSize*this._totalWeight)/e;t&&(this._averageItemSize=t,this._totalWeight=e)}}reset(){this._averageItemSize=this._defaultItemSize,this._totalWeight=0}},H=class{scrolledIndexChange=new C(()=>{});_viewport=null;_minBufferPx;_maxBufferPx;_averager;_lastScrollOffset;_lastRenderedContentSize;_lastRenderedContentOffset;_removalFailures=0;constructor(n,a,e=new V){this._minBufferPx=n,this._maxBufferPx=a,this._averager=e}attach(n){this._averager.reset(),this._viewport=n,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(n,a){if(a<n)throw Error("CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx");this._minBufferPx=n,this._maxBufferPx=a}_updateRenderedContentAfterScroll(){let n=this._viewport,a=n.measureScrollOffset(),e=a-this._lastScrollOffset,t=Math.abs(e),r=n.getRenderedRange(),i=0;if(e<0){let l=r.start*this._averager.getAverageItemSize()-this._lastRenderedContentOffset;i=Math.round(l*Math.max(0,Math.min(1,t/(a+t)))),e=e-i,t=Math.abs(e)}let o=this._lastScrollOffset-this._lastRenderedContentOffset,c=this._lastRenderedContentOffset+this._lastRenderedContentSize-(this._lastScrollOffset+n.getViewportSize()),u=t+this._minBufferPx-(e<0?o:c);if(u>0)if(t>=n.getViewportSize())this._renderContentForCurrentOffset();else{let g=Math.max(0,Math.ceil((u-this._minBufferPx+this._maxBufferPx)/this._averager.getAverageItemSize())),l=(e<0?c:o)-this._minBufferPx+t,h=Math.floor(l/this._averager.getAverageItemSize()/(this._removalFailures+1)),f=Math.min(r.end-r.start,Math.max(0,h)),d=this._expandRange(r,e<0?g:0,e>0?g:0);e<0?d.end=Math.max(d.start+1,d.end-f):d.start=Math.min(d.end-1,d.start+f);let v,E;if(e<0){let y=n.measureRangeSize({start:d.end,end:r.end});y<=l?(v=this._lastRenderedContentOffset+this._lastRenderedContentSize-y,this._removalFailures=0):(d.end=r.end,v=this._lastRenderedContentOffset+this._lastRenderedContentSize,this._removalFailures++),E="to-end"}else{let y=n.measureRangeSize({start:r.start,end:d.start});y<=l?(v=this._lastRenderedContentOffset+y,this._removalFailures=0):(d.start=r.start,v=this._lastRenderedContentOffset,this._removalFailures++),E="to-start"}n.setRenderedRange(d),n.setRenderedContentOffset(v+i,E)}else i&&n.setRenderedContentOffset(this._lastRenderedContentOffset+i);this._lastScrollOffset=a}_checkRenderedContentSize(){let n=this._viewport;this._lastRenderedContentSize=n.measureRenderedContentSize(),this._averager.addSample(n.getRenderedRange(),this._lastRenderedContentSize),this._updateTotalContentSize(this._lastRenderedContentSize)}_checkRenderedContentOffset(){let n=this._viewport;this._lastRenderedContentOffset=n.getOffsetToRenderedContentStart()}_renderContentForCurrentOffset(){let n=this._viewport,a=n.measureScrollOffset();this._lastScrollOffset=a,this._removalFailures=0;let e=this._averager.getAverageItemSize(),t=Math.min(n.getDataLength()-1,Math.floor(a/e)),r=Math.ceil(this._maxBufferPx/e),i=this._expandRange(this._getVisibleRangeForIndex(t),r,r);n.setRenderedRange(i),n.setRenderedContentOffset(e*i.start)}_getVisibleRangeForIndex(n){let a=this._viewport,e={start:n,end:n+Math.ceil(a.getViewportSize()/this._averager.getAverageItemSize())},t=e.end-a.getDataLength();return t>0&&(e.start=Math.max(0,e.start-t)),e}_expandRange(n,a,e){let t=this._viewport,r=Math.max(0,n.start-a),i=Math.min(t.getDataLength(),n.end+e);return{start:r,end:i}}_updateTotalContentSize(n){let a=this._viewport,e=a.getRenderedRange(),t=n+(a.getDataLength()-(e.end-e.start))*this._averager.getAverageItemSize();a.setTotalContentSize(t)}};function Ae(s){return s._scrollStrategy}var Ue=(()=>{class s{get minBufferPx(){return this._minBufferPx}set minBufferPx(a){this._minBufferPx=P(a)}_minBufferPx=100;get maxBufferPx(){return this._maxBufferPx}set maxBufferPx(a){this._maxBufferPx=P(a)}_maxBufferPx=200;_scrollStrategy=new H(this.minBufferPx,this.maxBufferPx);ngOnChanges(){this._scrollStrategy.updateBufferSize(this.minBufferPx,this.maxBufferPx)}static \u0275fac=function(e){return new(e||s)};static \u0275dir=se({type:s,selectors:[["cdk-virtual-scroll-viewport","autosize",""]],inputs:{minBufferPx:"minBufferPx",maxBufferPx:"maxBufferPx"},features:[oe([{provide:ae,useFactory:Ae,deps:[ee(()=>s)]}]),ie]})}return s})(),Ve=(()=>{class s{static \u0275fac=function(e){return new(e||s)};static \u0275mod=ne({type:s});static \u0275inj=te({})}return s})();var xe=["removed","added","contextBefore","contextAfter","occurrence"];function q(s){if(s==null)return{value:null,reason:null,droppedKeys:[]};let n=typeof s=="object"?Object.getPrototypeOf(s):void 0;if(n!==Object.prototype&&n!==null)return{value:null,reason:"it is not a plain object",droppedKeys:[]};let a=s;for(let i of["removed","added","contextBefore","contextAfter"])if(typeof a[i]!="string")return{value:null,reason:`"${i}" must be a string`,droppedKeys:[]};let e=a.occurrence;if(typeof e!="number"||!Number.isInteger(e)||e<1)return{value:null,reason:'"occurrence" must be an integer of 1 or more',droppedKeys:[]};let t={removed:a.removed,added:a.added,contextBefore:a.contextBefore,contextAfter:a.contextAfter,occurrence:e};if(t.removed.length+t.added.length>8192)return{value:null,reason:'"removed" and "added" together are longer than 8192 characters',droppedKeys:[]};let r=Object.keys(a).filter(i=>!xe.includes(i));return{value:t,reason:null,droppedKeys:r}}function _e(s,n,a){if(!n)return 0;let e=0,t=0;for(;;){let r=s.indexOf(n,t);if(r<0||r>=a)return e;e++,t=r+1}}var Re=s=>s>=55296&&s<=56319,we=s=>s>=56320&&s<=57343,I=(s,n)=>n>0&&n<s.length&&Re(s.charCodeAt(n-1))&&we(s.charCodeAt(n)),Oe=/[\p{L}\p{N}_]/u,w=s=>!!s&&Oe.test(s),m=s=>s.replace(/\u00a0/g," ");function Se(s,n){let a=m(s),e=m(n),t=Math.min(a.length,e.length),r=0;for(;r<t&&a.charCodeAt(r)===e.charCodeAt(r);)r++;let i=0;for(;i<t-r&&a.charCodeAt(a.length-1-i)===e.charCodeAt(e.length-1-i);)i++;let o=a.length-r-i,c=e.length-r-i;if(o>0&&c>0){for(;r>0&&w(a[r-1])&&(w(a[r])||w(e[r]));)r--;for(;i<t-r&&a.charCodeAt(a.length-1-i)===e.charCodeAt(e.length-1-i);)i++;for(;i>0&&w(a[a.length-i])&&(w(a[a.length-i-1])||w(e[e.length-i-1]));)i--}else if(o+c>0){let u=o>0?a:e,g=o+c,l=f=>w(u[f])&&!w(u[f-1]),h=r;for(let f=r;f>0&&u[f-1]===u[f+g-1];)f--,l(f)&&(h=f);!l(r)&&h!==r&&(i+=r-h,r=h)}for(;r>0&&(I(a,r)||I(e,r));)r--;for(;i>0&&(I(a,a.length-i)||I(e,e.length-i));)i--;return{prefix:r,suffix:i}}function N(s,n,a,e){if(n<0||a<n||a>s.length)return null;let t=s.slice(n,a);if(m(t)===m(e)||t.length+e.length>8192)return null;let r=Math.max(0,n-32);I(s,r)&&r++;let i=Math.min(s.length,a+32);I(s,i)&&i--;let o=s.slice(r,n),c=s.slice(a,i),u=o+t+c,g=1+_e(s,u,r);return{removed:t,added:e,contextBefore:o,contextAfter:c,occurrence:g}}function me(s,n,a){return m(n).includes(m(s.contextBefore+s.removed+s.contextAfter))&&m(a).includes(m(s.contextBefore+s.added+s.contextAfter))}function G(s){return{removed:m(s.removed),added:m(s.added),contextBefore:m(s.contextBefore),contextAfter:m(s.contextAfter),occurrence:s.occurrence}}function ve(s,n){if(m(s)===m(n))return null;let{prefix:a,suffix:e}=Se(s,n);return N(s,a,s.length-e,n.slice(a,n.length-e))}function qe(s,n){if(m(s)===m(n))return null;let{prefix:a,suffix:e}=Se(s,n);return{removed:s.slice(a,s.length-e),start:a,end:n.length-e}}var j=(()=>{let n=class n{constructor(e){this.loggingService=e,this.enabledSignal=re(!1),this.onTargetEditStart=null,this.onTargetEditCommit=null,this.autoCommit=!0;try{this.enabled$=ce(this.enabledSignal).pipe(O())}catch(t){this.loggingService.catch("Error in SuggestionModeService constructor: ",t),this.enabled$=new C}}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}}};n.\u0275fac=function(t){return new(t||n)(S(R))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var L=(()=>{let n=class n{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(i){return _()&&this.loggingService.catch(`[velt] Suggestion target "${e}" getter threw: `,i),!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(i){return _()&&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.`,i),!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)}}};n.\u0275fac=function(t){return new(t||n)(S(R))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var Ee=(()=>{let n=class n{constructor(e,t,r){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.registry=new Map,this.warnedUnstableIds=new Set,this.latestEdit=new Map,this.editSeq=0,this.actionsService=null,this.typedEditSource=null}registerTarget(e,t,r){try{if(!e||typeof t!="function")return;this.warnIfUnstableId(e);let i=this.registry.get(e)??{};i.getter=t,i.setter=typeof r?.setter=="function"?r.setter:void 0,i.restoreOnCommit=r?.restoreOnCommit,this.registry.set(e,i)}catch(i){this.loggingService.catch("Error in SuggestionTargetRegistryService registerTarget: ",i)}}unregisterTarget(e){try{let t=this.registry.get(e);if(!t)return;delete t.getter,delete t.setter,delete t.restoreOnCommit,this.latestEdit.delete(e),t.node||this.registry.delete(e)}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService unregisterTarget: ",t)}}getSetter(e){try{return this.registry.get(e)?.setter}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getSetter: ",t);return}}callSetter(e,t,r){return this.runSetter(e,t,r)!==null}runSetter(e,t,r){let i=this.registry.get(e)?.setter;if(!i)return null;let o=c=>this.loggingService.catch("Error in SuggestionTargetRegistryService: the target setter threw",c,{targetId:e,reason:r.reason});try{let c=i(t,b({targetId:e},r));if(c&&typeof c.then=="function")return Promise.resolve(c).catch(o)}catch(c){o(c)}return Promise.resolve()}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 i=r[0],o=this.registry.get(e)??{};return o.node=i,this.registry.set(e,o),i}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService getNode: ",t);return}}setTypedEditSource(e){this.typedEditSource=e}getTypedEdits(e){try{return this.typedEditSource?.(e)??[]}catch(t){return this.loggingService.catch("Error in SuggestionTargetRegistryService getTypedEdits: ",t),[]}}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(`[${A.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:[A.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.latestEdit.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),i={targetId:t.targetId,oldValue:r,newValue:r,element:t.element},o=this.modeService.getOnTargetEditStart();if(o)try{o(i)}catch(c){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditStart customer callback threw: ",c)}this.actionsService?.triggerAction(p.TARGET_EDIT_START,{details:i,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),i=this.readElementValue(e,t);if(D(r,i))return;let o=this.splitTypedEdits(t,r,i),c=this.restoreWhenCommitted(e,r,o?o.length:1);if(o){o.forEach((u,g)=>this.commitEdit(e,t,r,u.newValue,u.textChange,!0,c?.(g)));return}this.commitEdit(e,t,r,i,void 0,!1,c?.(0))}catch(r){this.loggingService.catch("Error in SuggestionTargetRegistryService processCommit: ",r)}}restoreWhenCommitted(e,t,r){let i=this.registry.get(e);if(!i?.setter||i.restoreOnCommit===!1){this.latestEdit.delete(e);return}let o=++this.editSeq;this.latestEdit.set(e,o);let c=new Set;return u=>g=>{try{if(!g||c.size===r||(c.add(u),c.size<r||this.latestEdit.get(e)!==o))return;this.latestEdit.delete(e);let l=this.runSetter(e,t,{reason:"restore"}),h=()=>{this.findTaggedAncestor(document.activeElement)?.targetId===e&&this.snapshotService.captureValue(e,t)};h(),l?.then(h,()=>{})}catch(l){this.loggingService.catch("Error in SuggestionTargetRegistryService restoreWhenCommitted: ",l)}}}splitTypedEdits(e,t,r){try{if(typeof t!="string"||typeof r!="string")return null;let i=this.getTypedEdits(e);if(i.length<2)return null;let o=g=>g.replace(/\u00a0/g," ");if(i.some(g=>o(g.base)!==o(t)))return null;let c=t;for(let g of[...i].sort((l,h)=>h.start-l.start))c=c.slice(0,g.start)+g.added+c.slice(g.end);if(o(c)!==o(r))return null;let u=[];for(let g of i){let l=N(t,g.start,g.end,g.added);if(!l)return null;u.push({newValue:t.slice(0,g.start)+o(g.added)+t.slice(g.end),textChange:G(l)})}return u}catch(i){return this.loggingService.catch("Error in SuggestionTargetRegistryService splitTypedEdits: ",i),null}}commitEdit(e,t,r,i,o,c=!1,u){try{let g={targetId:e,oldValue:r,newValue:i,element:t},l=this.modeService.getOnTargetEditCommit(),h=null;if(l){let d=null;try{d=l(g)}catch(v){this.loggingService.catch("Error in SuggestionTargetRegistryService onTargetEditCommit customer callback threw: ",v)}d&&(h=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:d.summary,summaryHtml:d.summaryHtml,metadata:d.metadata,textChange:d.textChange??o}),u&&h.then(u))}else this.modeService.isAutoCommitEnabled()&&(h=this.invokeAutoCommit({targetId:e,newValue:i,textChange:o,snapshot:c?{value:r}:void 0}),u&&h.then(u));let f=d=>Y(this,null,function*(){if(h&&(yield h))return null;let v=this.invokeAutoCommit({targetId:e,newValue:i,snapshot:c?{value:r}:void 0,summary:d?.summary,summaryHtml:d?.summaryHtml,metadata:d?.metadata,textChange:d?.textChange??o});return u&&v.then(u),v});this.actionsService?.triggerAction(p.TARGET_EDIT_COMMIT,{details:g,commitSuggestion:f,timestamp:Date.now()})}catch(g){this.loggingService.catch("Error in SuggestionTargetRegistryService commitEdit: ",g)}}invokeAutoCommit(r){var i=r,{snapshot:e}=i,t=J(i,["snapshot"]);try{return e&&this.snapshotService.captureValue(t.targetId,e.value),this.actionsService?this.actionsService.commitSuggestion(t).catch(o=>(_()&&this.loggingService.catch(`[velt] auto-commit for "${t.targetId}" rejected: `,o),null)):(_()&&this.loggingService.log("[velt] auto-commit skipped: actions service not wired. SuggestionActionsService constructor should call registry.setActionsService(this)."),Promise.resolve(null))}catch(o){return this.loggingService.catch("Error in SuggestionTargetRegistryService invokeAutoCommit: ",o),Promise.resolve(null)}}captureSnapshotForTarget(e,t){try{let r=this.registry.get(e);if(r?.getter){this.snapshotService.captureFromGetter(e,r.getter);return}let i=this.readElementValue(e,t);this.snapshotService.captureValue(e,i)}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 i=(t.type||"").toLowerCase();return i==="checkbox"||i==="radio"?t.checked:i==="number"||i==="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(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`);if(!t)return null;let r=t.getAttribute(A.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(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}="${t}"]`))}catch{return[]}}scanAndRefresh(e){try{e.querySelectorAll(`[${A.ATTRIBUTES.VELT_SUGGESTION_TARGET}]`).forEach(r=>{let i=r.getAttribute(A.ATTRIBUTES.VELT_SUGGESTION_TARGET);if(!i)return;let o=this.registry.get(i)??{};(!o.node||!o.node.isConnected)&&(o.node=r,this.registry.set(i,o))})}catch(t){this.loggingService.catch("Error in SuggestionTargetRegistryService scanAndRefresh: ",t)}}warnIfUnstableId(e){try{if(!_()||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(!_())return;this.loggingService.catch(`[velt] Duplicate target id "${e}" \u2014 ${t} elements share this id. Cause: the same ${A.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)}}};n.\u0275fac=function(t){return new(t||n)(S(R),S(j),S(L))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var Me=new Set(["apiKey","documentId","clientDocumentId","organizationId","clientOrganizationId","folderId","veltFolderId","parentVeltFolderId","documentMetadata","sdkVersion","pageInfo"]),St=(()=>{let n=class n{constructor(e,t,r,i,o,c,u){this.loggingService=e,this.modeService=t,this.snapshotService=r,this.targetRegistry=i,this.serviceBook=o,this.commonDbService=c,this.docService=u,this.actionSubjects=new Map,this.appliedValues=new Map,this.observingActive=!1,this.commentService=null,this.inlineSuggestionsEnabled$=new Q(!0);try{this.targetRegistry.setActionsService(this),this.serviceBook.observe(U).subscribe(g=>{this.commentService=g})}catch(g){this.loggingService.catch("Error in SuggestionActionsService constructor: ",g)}}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}}enableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value||this.inlineSuggestionsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in SuggestionActionsService enableInlineSuggestions: ",e)}}disableInlineSuggestions(){try{this.inlineSuggestionsEnabled$.value&&this.inlineSuggestionsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in SuggestionActionsService disableInlineSuggestions: ",e)}}isInlineSuggestionsEnabled$(){return this.inlineSuggestionsEnabled$.pipe(O())}isSuggestionModeEnabled$(){try{return this.modeService.enabled$}catch(e){return this.loggingService.catch("Error in SuggestionActionsService isSuggestionModeEnabled$: ",e),new C}}registerTarget(e){try{if(!e?.targetId||typeof e?.getter!="function")return;this.targetRegistry.registerTarget(e.targetId,e.getter,{setter:e.setter,restoreOnCommit:e.restoreOnCommit})}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 E=this.targetRegistry.getGetter(e.targetId);if(E){if(!this.snapshotService.captureFromGetter(e.targetId,E)){r(new Error("SNAPSHOT_FAILED"));return}}else{let y=this.targetRegistry.getFallbackValue(e.targetId);if(y.hasValue)this.snapshotService.captureValue(e.targetId,y.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),g=e.newValue;if(D(u,g)){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 l=new ge;l.type="suggestion",l.suggestion={status:"pending",targetId:e.targetId,targetType:"custom",oldValue:u,newValue:g,summary:e.summary??null,driftDetected:!1,rejectReason:null,resolvedBy:null,resolvedAt:null},this.setCustomerMetadata(l.suggestion,e.metadata),this.setTextChange(l.suggestion,e.targetId,e.textChange,u,g);let h=this.resolveSuggestionLocation(e),f=this.resolveSuggestionContext(e),d=Fe(e.summary,e.summaryHtml,u,g),v=new ue;if(v.commentText=d.commentText,v.commentHtml=d.commentHtml,l.comments=[v],!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,h?.location,void 0,void 0,void 0,void 0,void 0,E=>{try{this.snapshotService.clearSnapshot(e.targetId),this.projectAndTrigger(p.SUGGESTION_CREATED,E.annotation),t({id:E.annotation.annotationId})}catch(y){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion callback: ",y),r(y)}},void 0,void 0,l,h?.locationId,f,!0,void 0,void 0,"internal",h?.locationId!==void 0?!0:void 0)}catch(i){this.loggingService.catch("Error in SuggestionActionsService commitSuggestion: ",i),r(i)}})}getSuggestions(e){try{let t=this.commentService?.getCommentAnnotationsOnCurrentOrganizationAndDocument()??[],r=[];for(let i of t){if(!i.suggestion)continue;let o=this.projectAnnotationToSuggestion(i);o&&this.matchesFilter(o,e)&&r.push(o)}return r}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions: ",t),[]}}getSuggestions$(e){try{return this.serviceBook.observe(U).pipe(Z(t=>t?t.getCommentAnnotationsOnCurrentOrganizationAndDocument$():$([]))).pipe(k(t=>{let r=[];for(let i of t??[]){if(!i.suggestion)continue;let o=this.projectAnnotationToSuggestion(i);o&&this.matchesFilter(o,e)&&r.push(o)}return r}),O(z))}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getSuggestions$: ",t),new C}}getPendingSuggestion(e){try{if(!e)return null;let t=this.getSuggestions({targetId:e,status:"pending"});return t.length===0?null:t.sort((r,i)=>(i.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(k(t=>t.length===0?null:t.sort((r,i)=>(i.createdAt??0)-(r.createdAt??0))[0]),O(z)):new C}catch(t){return this.loggingService.catch("Error in SuggestionActionsService getPendingSuggestion$: ",t),new C}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new B),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 B),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 i=this.timestamp;switch(e){case p.SUGGESTION_CREATED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_CREATED,o);break}case p.SUGGESTION_APPROVED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_APPROVED,o);break}case p.SUGGESTION_REJECTED:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_REJECTED,o);break}case p.SUGGESTION_STALE:{let o={suggestion:r,timestamp:i};this.triggerAction(p.SUGGESTION_STALE,o);break}}}catch(r){this.loggingService.catch("Error in SuggestionActionsService projectAndTrigger: ",r)}}resolveSuggestionContext(e){try{let t=e.context;if(t==null)return;if(typeof t!="object"||Array.isArray(t)){this.loggingService.warn('[velt] commitSuggestion: context was not saved. Cause: it is not an object. Fix: pass an object, e.g. { textEditorConfig: { editorId: "<editor id>" } }. Docs: velt.dev/docs/suggestions');return}let r;try{r=JSON.parse(JSON.stringify(t))}catch{this.loggingService.warn("[velt] commitSuggestion: context was not saved. Cause: it cannot be stored as JSON (e.g. it refers to itself). Fix: pass plain JSON data. Docs: velt.dev/docs/suggestions");return}if(r===null||typeof r!="object"||Array.isArray(r)){this.loggingService.warn('[velt] commitSuggestion: context was not saved. Cause: it is not stored as an object (e.g. a Date). Fix: pass an object, e.g. { textEditorConfig: { editorId: "<editor id>" } }. Docs: velt.dev/docs/suggestions');return}let i=De.filter(o=>o in r);return i.length&&(i.forEach(o=>delete r[o]),this.loggingService.warn(`[velt] commitSuggestion: context keys ${i.join(", ")} were not saved. Cause: the SDK sets them. Fix: leave them out (use \`access\` for context access). Docs: velt.dev/docs/suggestions`)),r}catch(t){this.loggingService.catch("Error in SuggestionActionsService resolveSuggestionContext: ",t);return}}resolveSuggestionLocation(e){try{let t=null,r=e.location;if(r!=null){let o=typeof r=="object"&&!Array.isArray(r)?r.id:void 0;typeof o=="string"&&o.trim()?t=r:this.loggingService.warn('[velt] commitSuggestion: location was not used. Cause: it is not an object with a non-empty string id. Fix: pass { id: "<location id>" }, or omit it to use the location around the target element. Docs: velt.dev/docs/suggestions')}if(!t){let o=this.targetRegistry.getNode(e.targetId);t=o?this.docService.getAdditionLocationFromElement(o):null}if(!t?.id)return null;let i=this.docService.getLocationMetadataByClientLocationId(t.id);return i?.location?{location:i.location,locationId:i.locationId}:{location:t}}catch(t){return this.loggingService.catch("Error in SuggestionActionsService resolveSuggestionLocation: ",t),null}}setCustomerMetadata(e,t){let r=this.cloneCustomerMetadata(t);r&&(e.metadata=r)}setTextChange(e,t,r,i,o){try{let c=q(r);c.reason?this.loggingService.warn(`[velt] commitSuggestion: textChange was not saved. Cause: ${c.reason}. Fix: pass { removed, added, contextBefore, contextAfter, occurrence }. Docs: velt.dev/docs/suggestions`):c.droppedKeys.length&&this.loggingService.warn(`[velt] commitSuggestion: textChange keys ${c.droppedKeys.join(", ")} were not saved. Cause: they are not textChange keys. Fix: put your own data in metadata. Docs: velt.dev/docs/suggestions`);let u=c.value??this.computeTextChange(t,i,o);u&&(e.textChange=u)}catch(c){this.loggingService.catch("Error in SuggestionActionsService setTextChange: ",c)}}computeTextChange(e,t,r){if(typeof t!="string"||typeof r!="string")return null;let i=this.targetRegistry.getNode(e);if(!(i instanceof HTMLElement)||!i.isConnected||!i.isContentEditable||i.closest(".ProseMirror"))return null;for(let c of this.targetRegistry.getTypedEdits(i)??[]){let u=N(c.base,c.start,c.end,c.added);if(u&&me(u,t,r))return G(u)}let o=ve(t,r);return o&&G(o)}getTextChange(e){return q(e.textChange).value}cloneCustomerMetadata(e){if(e==null)return;let t=typeof e=="object"?Object.getPrototypeOf(e):void 0;if(t!==Object.prototype&&t!==null){this.loggingService.warn('[velt] commitSuggestion: metadata was not saved. Cause: it is not a plain object. Fix: pass a plain JSON object, e.g. { kind: "replacement" }. Docs: velt.dev/docs/suggestions');return}try{let r=le(e);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{this.loggingService.warn("[velt] commitSuggestion: metadata was not saved. Cause: it cannot be serialized as JSON (BigInt or a circular reference). Fix: pass JSON-safe values only. Docs: velt.dev/docs/suggestions");return}}getCustomerMetadata(e){let t=e.suggestion?.metadata;if(t&&typeof t=="object"&&!Array.isArray(t))return b({},t);let r={},i=e.metadata;if(i&&typeof i=="object")for(let o of Object.keys(i))Me.has(o)||Object.defineProperty(r,o,{value:i[o],enumerable:!0,writable:!0,configurable:!0});return r}setAppliedValues(e,t){this.appliedValues.set(e,t)}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:this.getCustomerMetadata(e),textChange:this.getTextChange(t),driftDetected:!!t.driftDetected,createdBy:e.from,createdAt:e.createdAt??0};switch(t.status){case"pending":return M(b({},r),{status:"pending",rejectReason:null,resolvedBy:null,resolvedAt:null});case"accepted":case"apply_failed":{let i=t.status==="accepted"?this.appliedValues.get(e.annotationId):void 0;return M(b(b({},r),i??{}),{status:t.status,rejectReason:null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp})}case"rejected":return M(b({},r),{status:"rejected",rejectReason:t.rejectReason??null,resolvedBy:t.resolvedBy,resolvedAt:t.resolvedAt??this.timestamp});case"stale":return M(b({},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}}};n.\u0275fac=function(t){return new(t||n)(S(R),S(j),S(L),S(Ee),S(de),S(he),S(fe))},n.\u0275prov=x({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();function be(s){try{return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}catch{return""}}function T(s){try{if(s==null)return"";if(typeof s=="string")return s;if(typeof s=="object")try{return JSON.stringify(s)}catch{return String(s)}return String(s)}catch{return""}}var De=["accessFields","_setAccessFields","_replaceAccessFields","_setVisibilityConfig"];function Te(s){try{if(s===null||typeof s!="object"||Array.isArray(s))return!1;let n=Object.getPrototypeOf(s);return n===Object.prototype||n===null}catch{return!1}}function Ce(s,n){try{let a=s==null,e=n==null;if(a&&!e)return[{op:"add",newText:T(n)}];if(!a&&e)return[{op:"remove",oldText:T(s)}];if(Te(s)&&Te(n)){let t=s,r=n,i=[...Object.keys(t),...Object.keys(r).filter(c=>!(c in t))],o=[];for(let c of i){let u=c in t,g=c in r;u&&g?D(t[c],r[c])||o.push({op:"replace",oldText:`${c}: ${T(t[c])}`,newText:`${c}: ${T(r[c])}`}):u?o.push({op:"remove",oldText:`${c}: ${T(t[c])}`}):o.push({op:"add",newText:`${c}: ${T(r[c])}`})}if(o.length>0)return o}return[{op:"replace",oldText:T(s),newText:T(n)}]}catch{return[{op:"replace",oldText:T(s),newText:T(n)}]}}function Ne(s,n){try{return Ce(s,n).map(a=>a.op==="add"?`Add: "${a.newText??""}"`:a.op==="remove"?`Remove: "${a.oldText??""}"`:`Replace: "${a.oldText??""}" with "${a.newText??""}"`).join(`
|
|
2
2
|
`)}catch{return'Replace: "" with ""'}}var X="color:#e0492b;font-style:italic;",W="color:#0f8a4d;font-style:italic;";function Ge(s,n){try{let a=Ce(s,n),e=t=>be(t??"");if(a.length===1){let t=a[0],r=(i,o,c)=>`<div class="velt-suggestion-default-line">${i} <span class="velt-suggestion-default-${c}" dir="auto" style="${c==="old"?X:W}">“${e(o)}”</span></div>`;return t.op==="add"?r("Add",t.newText,"new"):t.op==="remove"?r("Remove",t.oldText,"old"):r("Replace",t.oldText,"old")+r("with",t.newText,"new")}return a.map(t=>t.op==="add"?`<div>Add: <span style="${W}">“${e(t.newText)}”</span></div>`:t.op==="remove"?`<div>Remove: <span style="${X}">“${e(t.oldText)}”</span></div>`:`<div>Replace: <span style="${X}">“${e(t.oldText)}”</span> with <span style="${W}">“${e(t.newText)}”</span></div>`).join("")}catch{return"<div>Replace:</div><div>with</div>"}}function Fe(s,n,a,e){try{let t=s||Ne(a,e),r;return n?r=n:s?r=`<p>${be(s)}</p>`:r=Ge(a,e),{commentText:t,commentHtml:r}}catch{return{commentText:"",commentHtml:""}}}export{Ue as a,Ve as b,q as c,qe as d,j as e,Ee as f,St as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Hk as s,Ra as c,Za as o}from"./chunk-
|
|
1
|
+
import{Hk as s,Ra as c,Za as o}from"./chunk-QUMZPTVX.js";var n=(()=>{let r=class r{constructor(t){this.domService=t}transform(t){try{return this.domService.sanitizeHtml(t)}catch{return t}}};r.\u0275fac=function(i){return new(i||r)(c(s,16))},r.\u0275pipe=o({name:"sanitizeHtml",type:r,pure:!0});let e=r;return e})();export{n as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Fa as ge}from"./chunk-BCCFAKMJ.js";import{E as le,G as ue,H as he,b as oe,m as ne,n as ce,p as ae,s as de}from"./chunk-7D33ZDW3.js";import{$f as T,$j as se,Dk as te,He as b,Ii as E,Ik as ie,Ji as $,M as F,Pf as p,Qd as B,Qf as g,Uj as ee,Xj as re,_f as j,a as v,ag as _,b as O,ba as L,cg as k,dg as D,di as V,ea as R,ee as S,fa as z,g as m,gi as q,hi as X,kg as J,ki as H,l as N,mi as K,oi as x,qj as Y,rj as Q,sf as U,tf as P,uf as I,v as W,vg as G,wj as Z}from"./chunk-Q6PUYIXT.js";var A="public",w=100,fe=50,$e=(()=>{let C=class C{constructor(e,r,s,t,i,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=t,this.usersService=i,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=z(Z),this.adapterSelectorService=z(se),this.currentUserPermissions$=new N(null),this.permissionsCache$=new N(null),this.permissionProvider$=new N(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",this.reportedPortablePermissionFailures=new Set,this.clientResolverContradictionWarned=!1,this.reportedUnknownFolderErrorCodes=new Set;try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(l){this.loggingService.catch("Error in UserPermissionService constructor:",l)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,t,i,o){try{return e.find(a=>a.resourceId===s&&a.type===t&&a.organizationId===i&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:i,type:t,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===t&&a.organizationId===i&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(b.DEFAULT_VELT_CONTEXT))return!0;let s=r.filter(i=>!J(i));if(!s.length){if(r.some(c=>c.startsWith(b.VISIBILITY_ORG_PREFIX)))return!0;let o=`${b.VISIBILITY_SELF_PREFIX}${j(e).toString()}`;return r.includes(o)}let t=this.contactService.getUserAccessFieldsByUserId(e);return t?.length?s.every(i=>t.includes(i)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}isMetadataProbeUnanswerable(e){try{return this.adapterSelectorService?.isPortableBackendActive()?!ne(e)&&!ce(e):!1}catch(r){return this.loggingService.catch("Error in UserPermissionService isMetadataProbeUnanswerable: ",r),!1}}organizationDetails(e){return m(this,null,function*(){try{if(this.isMetadataProbeUnanswerable("organizationMetadata"))return{error:!1};let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return m(this,arguments,function*({documentId:e,organizationId:r,clientDocumentId:s,clientOrganizationId:t}){try{if(this.isMetadataProbeUnanswerable("documentMetadata")){let d=yield this.docService.readPortableDocumentForProbe?.(e,s,t);return d?.missing?{errorCode:g.DOES_NOT_EXIST,error:!0}:d?.accessType?{error:!1,accessType:d.accessType}:{error:!1}}let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(o&&o?.errorCode)return{errorCode:g.PERMISSION_DENIED,error:!0};if(o&&!o?.metadata)return{errorCode:g.DOES_NOT_EXIST,error:!0};let c=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,v(v({},c),o?.metadata??{}));let a,n=o?.metadata?.veltFolderId;if(n)try{a=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:n,organizationId:r}}))?.folderIamConfig?.accessType}catch(d){this.loggingService.catch("Error fetching folder accessType for document:",d)}return a||(a=o?.docIamConfig?.accessType),{error:!1,accessType:a}}catch(o){return this.loggingService.catch("Error in UserPermissionService documentDetails:",o),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return m(this,arguments,function*({folderId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("folderMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return t&&t?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:t?.folderIamConfig?.accessType}}catch(t){return this.loggingService.catch("Error in UserPermissionService folderDetails:",t),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return m(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let i=this.adapterSelectorService?.isPortableSession?.()===!0;if(i&&this.adapterSelectorService?.isPortableBackendActive?.()!==!0&&(yield re(C.PORTABLE_ACTIVATION_WAIT_MS),s!==this.authService.getUser()?.userId))return{};let o=yield this.validateResources(t),c;if(i&&this.adapterSelectorService?.isPortableBackendActive?.()===!0){if(c=yield this.fetchPortableUserPermissions(t,o,s??""),s!==this.authService.getUser()?.userId)return{}}else{let[a,n]=yield this.fetchUserPermissionsFromDB(t),d=this.authService.getUser()?.userId;if(s!==d)return{};c=this.buildPermissionsResponse(t,o,a,n)}if(Object.keys(c).length>0){if(!e)this.setCurrentUserPermissions(c);else if(this.permissionsCacheGeneration===r){let a=this.buildPermissionsCacheKey(e);a!==null&&this.requestKeyedPermissionsCache.set(a,JSON.parse(JSON.stringify(c)))}}return c}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return m(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,t=this.requestKeyedPermissionsCache.get(r);if(t)return JSON.parse(JSON.stringify(t));let i=this.inFlightPermissionsRequests.get(r);if(i){let a=yield i;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.reportedPortablePermissionFailures?.clear(),this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let t=e[s];t!==void 0&&(r[s]=Array.isArray(t)?[...t].sort():t)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?k(o):void 0}}let t=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:t,organizationId:t?k(t):void 0}}validateResources(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t,clientOrganizationId:i}=e,o=[],c=[],a=r.length>0||s.length>0;t&&!a&&(o.push(this.organizationDetails(t)),c.push({id:i??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:t??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:t??"",clientDocumentId:u,clientOrganizationId:i})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),l=this.processValidationResults(n,c);return O(v({},this.suppressResolverGrantedFailures(l,i)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let t=this.getPermissionsCache()??[];if(t.length===0)return e;let i=(n,d,l)=>t.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!l||u?.organizationId===l)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&i(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&i(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===g.PERMISSION_DENIED&&r&&i(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return m(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],t=[],i,o={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let u=n.status==="fulfilled"?n.value.errorCode??g.SOMETHING_WENT_WRONG:g.SOMETHING_WENT_WRONG,h={id:d.id,errorCode:u};switch(d.type){case"organization":if(i=h,u===g.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(h);break;case"document":t.push(h);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:t,failedOrganizationId:i,folderAccessTypes:o,documentAccessTypes:c}}fetchPortableUserPermissions(e,r,s){return m(this,null,function*(){try{let t=e.clientOrganizationId??"";if(!s||!t)return{};let i=fe,o=T(e.folderIds??[],i),c=T(e.documentIds??[],i),a=Math.max(o.length,c.length,1),n={},d=this.adapterSelectorService.resolveDbAdapter();for(let h=0;h<a;h++){let f={organizationId:t,userIds:[s]};o[h]?.length&&(f.folderIds=o[h]),c[h]?.length&&(f.documentIds=c[h]);let y=yield ee(d,"getUserPermissions",{scope:"org",data:f});if(!y?.ok)return oe("getUserPermissions",y,{logCatch:(me,ve)=>this.loggingService.catch(me,ve,void 0,!0),reported:this.reportedPortablePermissionFailures,isOutcomeUnknown:le}),{};this.reportedPortablePermissionFailures.clear(),this.mergePortablePermissionsMap(n,this.readPortablePermissionsMap(y.data,s))}let l=n[s],u=l?{[s]:l}:{};return l&&(Object.entries(l.documents??{}).forEach(([h,f])=>{if(f&&!f.accessType){let y=r.documentAccessTypes?.[h]??r.defaultDocumentAccessType;y&&(f.accessType=y)}}),Object.entries(l.folders??{}).forEach(([h,f])=>{if(f&&!f.accessType){let y=r.folderAccessTypes?.[h]??r.defaultDocumentAccessType;y&&(f.accessType=y)}})),this.ensureCurrentUserFailuresRecorded(u,t,r.failedFolderIds,r.failedDocumentIds,r.failedOrganizationId,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processContextPermissions(u),u}catch(t){return this.loggingService.catch("Error in UserPermissionService fetchPortableUserPermissions: ",t),{}}})}readPortablePermissionsMap(e,r){let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(!s(e))return{};let t=new Set(["data","success","statusCode","message"]),i=Object.keys(e);return r!=="data"&&s(e.data)&&i.every(c=>t.has(c))?e.data:e}mergePortablePermissionsMap(e,r){Object.entries(r??{}).forEach(([s,t])=>{if(!t||typeof t!="object")return;let i=e[s]??(e[s]={});t.folders&&(i.folders=v(v({},i.folders??{}),t.folders)),t.documents&&(i.documents=v(v({},i.documents??{}),t.documents)),t.organization&&(i.organization=v(v({},i.organization??{}),t.organization)),t.context&&(i.context=t.context)})}fetchUserPermissionsFromDB(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t}=e,i=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),t??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:i,organizationId:t}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:i,organizationId:t,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,t){let{folderIds:i,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:l}=r,u={};return this.processRegularUserPermissions(u,s,i,o,c??"",a??"",n,d,l,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,l,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,t),this.processContextPermissions(u),u}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,t,i,o,c,a,n,d,l,u){for(let h of r)for(let f of h)f?.user?.userId&&(e[f.user.userId]=O(v({},s.length&&{folders:this.buildFolderPermissions(s,f,c,d,u)}),{documents:this.buildDocumentPermissions(t,f,a,l,u),organization:{[i]:this.buildOrganizationPermission(o,f,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,t,i,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!i&&!!r,l=(s?.length??0)>0,u=(t?.length??0)>0;if(!d&&!l&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode})),l){e[n].folders||(e[n].folders={});for(let h of s)e[n].folders[h.id]||(e[n].folders[h.id]=v({error:this.getErrorMessage(h.errorCode,"folder"),errorCode:h.errorCode},h.errorCode===g.PERMISSION_DENIED&&{accessType:o[h.id]??a??A}))}if(u){e[n].documents||(e[n].documents={});for(let h of t)e[n].documents[h.id]||(e[n].documents[h.id]=v({error:this.getErrorMessage(h.errorCode,"document"),errorCode:h.errorCode},h.errorCode===g.PERMISSION_DENIED&&{accessType:c[h.id]??a??A}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case g.DOES_NOT_EXIST:return`${r} does not exist`;case g.PERMISSION_DENIED:return`User does not have access to ${r}`;case g.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,t,i){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=v({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===g.PERMISSION_DENIED&&{accessType:t[c]??i??A}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?p.VIEWER:p.EDITOR,accessType:t[c]??i??A},o},{})}buildDocumentPermissions(e,r,s,t,i){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=v({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===g.PERMISSION_DENIED&&{accessType:t[c]??i??A}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?p.VIEWER:p.EDITOR,accessType:t[c]??i??A},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?p.VIEWER:p.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[t]={accessRole:i??p.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[t]={accessRole:i??p.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[t]={accessRole:i??p.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let t=!0,i=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return i&&(e&&typeof e=="string"&&i?.[o]?.organization?.[e]&&(i?.[o]?.organization?.[e]?.accessRole===p.VIEWER||i?.[o]?.organization?.[e]?.errorCode===g.PERMISSION_DENIED)&&(t=!1),r&&typeof r=="string"&&i?.[o]?.folders?.[r]&&(i?.[o]?.folders?.[r]?.accessRole===p.VIEWER||i?.[o]?.folders?.[r]?.errorCode===g.PERMISSION_DENIED)&&(t=!1),s&&typeof s=="string"&&i?.[o]?.documents?.[s]&&(i?.[o]?.documents?.[s]?.accessRole===p.VIEWER||i?.[o]?.documents?.[s]?.errorCode===g.PERMISSION_DENIED)&&(t=!1)),t}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(F(V))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let t=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[t]){let i=k(t);r[s].organization&&(r[s].organization[i]=r[s].organization[t],delete r[s].organization[t])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([i,o])=>[D(i),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([i,o])=>[_(i),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(W(e=>this.refactorPermissionsWithServerIds(e)),F(V))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return m(this,null,function*(){let e=G();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(i=>{i.userId===s&&i.hasAccess&&(i.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(O(v({},i),{hasAccess:!1})):r.push(O(v({},i),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let i=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});i.success?this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:i,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:i,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return m(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let t=this.getPermissionsCache()??[];s.forEach(c=>{t=t.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(t);let i=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:i});o.success?this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(t){return m(this,arguments,function*({documentIds:e,folderId:r,context:s}){let i=G();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&H({input:s}).forEach(l=>{let u=JSON.stringify(l.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=i,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return m(this,arguments,function*({requests:e,userId:r}){let t={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?t.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:t})})}sendGetAccessToProxy(t){return m(this,arguments,function*({requests:e,userId:r,metadata:s}){return this.adapterSelectorService?.isPortableBackendActive()?this.sendGetAccessToPortableGateway({requests:e,retryConfig:s?.retryConfig,clientResolvedResults:s?.clientResolvedResults}):this.callHostedGetAccess({type:"getAccess",data:e,metadata:s},r)})}callHostedGetAccess(e,r){return m(this,null,function*(){let s=$(this.functions,x({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield K({methodName:"getAccess",data:e,getSdkProxy:s,userId:r})})}sendGetAccessToPortableGateway(t){return m(this,arguments,function*({requests:e,retryConfig:r,clientResolvedResults:s}){try{let i=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let c of T(e,w)){let a=this.buildPortableGetAccessChunkMetadata(r,this.selectClientResolvedResultsForChunk(s,c)),n=yield i.getAccess(a===void 0?{scope:"org",data:c}:{scope:"org",data:c,metadata:a});if(!n?.ok){let l=n?.code;return this.loggingService.catch("Tier B getAccess denied/failed at the gateway: ",n),{data:[],success:!1,statusCode:this.denialCodeToStatusCode(l)}}let d=n.data?.data??[];o.push(...this.dropUnrequestedEntries(d,c))}return{data:this.skipNotProvidedFolderEntries(o),success:!0,statusCode:200}}catch(i){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",i),{data:[],success:!1,statusCode:500}}})}skipNotProvidedFolderEntries(e){try{this.reportUnrecognizedFolderErrorCodes(e);let r=e.filter(s=>!(s?.type===I.FOLDER&&s?.errorCode==="not_provided"));return r.length!==e.length&&this.loggingService.log(`[WB] Tier B getAccess: ${e.length-r.length} folder answer(s) skipped (errorCode 'not_provided' \u2014 folder subsystem not provisioned on this gateway)`),r}catch(r){return this.loggingService.catch("Error in UserPermissionService skipNotProvidedFolderEntries: ",r),e}}dropUnrequestedEntries(e,r){try{if(!e?.length)return e??[];let s=this.portableGetAccessAskedKeys(r),t=e.filter(i=>s.has(this.portableGetAccessEntryKey(i)));return t.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(i=>!s.has(this.portableGetAccessEntryKey(i))),void 0,!0),t}catch(s){return this.loggingService.catch("Error in UserPermissionService dropUnrequestedEntries: ",s),e}}portableGetAccessEntryKey(e){return`${e?.userId}|${e?.resourceId}|${e?.organizationId}|${e?.type}`}portableGetAccessQueryKey(e){return`${e?.userId}|${e?.resource?.id}|${e?.resource?.organizationId}|${e?.resource?.type}`}portableGetAccessAskedKeys(e){return new Set((e??[]).map(r=>this.portableGetAccessQueryKey(r)))}selectClientResolvedResultsForChunk(e,r){try{if(!e?.length)return[];let s=this.portableGetAccessAskedKeys(r),t=e.filter(a=>s.has(this.portableGetAccessEntryKey(a)));if(t.length<=w)return t;let i=new Map,o=!1;for(let a of t){let n=this.portableGetAccessEntryKey(a),d=i.get(n);if(d===void 0){i.set(n,a);continue}let l=d.hasAccess===!0&&a.hasAccess===!0;o=o||d.hasAccess!==a.hasAccess,i.set(n,l===a.hasAccess?a:O(v({},a),{hasAccess:l}))}let c=Array.from(i.values());return this.loggingService.log(`[WB] Tier B getAccess: the resolver answered ${t.length} results for a ${r.length}-question chunk; duplicate keys collapsed to ${c.length} (the last occurrence per key, as the permissions cache keeps it; hasAccess deny-wins) to stay under the gateway's ${w}-entry cap on clientResolvedResults`),o&&!this.clientResolverContradictionWarned&&(this.clientResolverContradictionWarned=!0,console.warn("[Velt] The client-side dev permission resolver answered the same permission question more than once with contradicting hasAccess values. The answers were collapsed to a denial (deny wins) before being relayed to the self-hosted gateway. Fix the resolver to answer each question once.")),c}catch(s){return this.loggingService.catch("Error in UserPermissionService selectClientResolvedResultsForChunk: ",s),[]}}buildPortableGetAccessChunkMetadata(e,r){if(!(e===void 0&&!r?.length))return v(v({},e===void 0?{}:{retryConfig:e}),r?.length?{clientResolvedResults:r}:{})}reportUnrecognizedFolderErrorCodes(e){try{for(let r of e??[]){let s=r?.errorCode;!s||r?.type!==I.FOLDER||s==="not_provided"||this.reportedUnknownFolderErrorCodes.has(s)||(this.reportedUnknownFolderErrorCodes.add(s),console.warn(`Velt [portable backend]: a folder permission entry carried an unrecognised errorCode '${s}'. It is being consumed verbatim (hasAccess is honoured as sent). If your gateway means the folder subsystem is not provisioned, the expected literal is the exact lowercase 'not_provided' \u2014 anything else reads as a REAL denial and will withhold folder-scoped access.`))}}catch(r){this.loggingService.catch("Error in UserPermissionService reportUnrecognizedFolderErrorCodes: ",r)}}denialCodeToStatusCode(e){switch(e){case"unauthenticated":return 401;case"permission-denied":return 403;case"not-found":return 404;case"invalid-argument":return 400;case"failed-precondition":return 412;case"resource-exhausted":return 429;case"unimplemented":return 501;default:return 500}}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return m(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return m(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),t=r?.resolveTimeout??6e4,i=yield q(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),t),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!i||!i.success||i.statusCode!==200)throw new Error(i?.message??"Client permission resolver failed");let o=i.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return m(this,null,function*(){let s={data:{requests:e}},t=r.endpointConfig?.url?.trim();if(t)return X(t,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let i=yield r.resolvePermissions(s);if(Array.isArray(i))return{data:i,success:!0,statusCode:200};let o=i,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return m(this,null,function*(){if(!r||r<=0)return e();let s,t=new Promise((i,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),t])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(t){return m(this,arguments,function*({requests:e,userId:r,currentContext:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendRevokeAccessToPortableGateway({requests:e,metadata:this.buildRevokeAccessMetadata(s)});let i=$(this.functions,x({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield K({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:this.buildRevokeAccessMetadata(s)},getSdkProxy:i,userId:r})})}buildRevokeAccessMetadata(e){return v({retryConfig:this.getPermissionProviderRetryConfig()},e?.access&&{currentContext:e})}sendRevokeAccessToPortableGateway(s){return m(this,arguments,function*({requests:e,metadata:r}){try{let t=this.adapterSelectorService.resolveDbAdapter();for(let i of T(e,w)){let o=yield t.revokeAccess({scope:"org",data:i,metadata:r});if(!o?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",o),{success:!1}}return{success:!0}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",t),{success:!1}}})}onResourceAccessRequired(o){return m(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:t,fromCache:i=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&i&&(e.forEach(n=>{let d=a?.find(l=>l.resourceId===n.resource.id&&l.type===n.resource.type&&l.userId===n.userId&&l.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:i,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??t??""});return this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:i}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(t=>{let i=`${t.userId}_${t.resourceId}_${t.organizationId}_${t.type}`;r.set(i,t)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};C.PORTABLE_ACTIVATION_WAIT_MS=1e4,C.\u0275fac=function(r){return new(r||C)(R(ie),R(he),R(Y),R(ue),R(ae),R(de),R(te),R(B),R(Q),R(ge))},C.\u0275prov=L({token:C,factory:C.\u0275fac,providedIn:"root"});let M=C;return M})();export{$e as a};
|
|
1
|
+
import{Fa as ge}from"./chunk-7KXS2DSG.js";import{E as le,G as ue,H as he,b as oe,m as ne,n as ce,p as ae,s as de}from"./chunk-YKZV3FEU.js";import{$f as T,$j as se,Dk as te,He as b,Ii as E,Ik as ie,Ji as $,M as F,Pf as p,Qd as B,Qf as g,Uj as ee,Xj as re,_f as j,a as v,ag as _,b as O,ba as L,cg as k,dg as D,di as V,ea as R,ee as S,fa as z,g as m,gi as q,hi as X,kg as J,ki as H,l as N,mi as K,oi as x,qj as Y,rj as Q,sf as U,tf as P,uf as I,v as W,vg as G,wj as Z}from"./chunk-QUMZPTVX.js";var A="public",w=100,fe=50,$e=(()=>{let C=class C{constructor(e,r,s,t,i,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=t,this.usersService=i,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=z(Z),this.adapterSelectorService=z(se),this.currentUserPermissions$=new N(null),this.permissionsCache$=new N(null),this.permissionProvider$=new N(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",this.reportedPortablePermissionFailures=new Set,this.clientResolverContradictionWarned=!1,this.reportedUnknownFolderErrorCodes=new Set;try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(l){this.loggingService.catch("Error in UserPermissionService constructor:",l)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,t,i,o){try{return e.find(a=>a.resourceId===s&&a.type===t&&a.organizationId===i&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:i,type:t,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===t&&a.organizationId===i&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(b.DEFAULT_VELT_CONTEXT))return!0;let s=r.filter(i=>!J(i));if(!s.length){if(r.some(c=>c.startsWith(b.VISIBILITY_ORG_PREFIX)))return!0;let o=`${b.VISIBILITY_SELF_PREFIX}${j(e).toString()}`;return r.includes(o)}let t=this.contactService.getUserAccessFieldsByUserId(e);return t?.length?s.every(i=>t.includes(i)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}isMetadataProbeUnanswerable(e){try{return this.adapterSelectorService?.isPortableBackendActive()?!ne(e)&&!ce(e):!1}catch(r){return this.loggingService.catch("Error in UserPermissionService isMetadataProbeUnanswerable: ",r),!1}}organizationDetails(e){return m(this,null,function*(){try{if(this.isMetadataProbeUnanswerable("organizationMetadata"))return{error:!1};let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return m(this,arguments,function*({documentId:e,organizationId:r,clientDocumentId:s,clientOrganizationId:t}){try{if(this.isMetadataProbeUnanswerable("documentMetadata")){let d=yield this.docService.readPortableDocumentForProbe?.(e,s,t);return d?.missing?{errorCode:g.DOES_NOT_EXIST,error:!0}:d?.accessType?{error:!1,accessType:d.accessType}:{error:!1}}let o=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(o&&o?.errorCode)return{errorCode:g.PERMISSION_DENIED,error:!0};if(o&&!o?.metadata)return{errorCode:g.DOES_NOT_EXIST,error:!0};let c=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,v(v({},c),o?.metadata??{}));let a,n=o?.metadata?.veltFolderId;if(n)try{a=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:n,organizationId:r}}))?.folderIamConfig?.accessType}catch(d){this.loggingService.catch("Error fetching folder accessType for document:",d)}return a||(a=o?.docIamConfig?.accessType),{error:!1,accessType:a}}catch(o){return this.loggingService.catch("Error in UserPermissionService documentDetails:",o),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return m(this,arguments,function*({folderId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("folderMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return t&&t?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:t?.folderIamConfig?.accessType}}catch(t){return this.loggingService.catch("Error in UserPermissionService folderDetails:",t),{errorCode:g.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return m(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let i=this.adapterSelectorService?.isPortableSession?.()===!0;if(i&&this.adapterSelectorService?.isPortableBackendActive?.()!==!0&&(yield re(C.PORTABLE_ACTIVATION_WAIT_MS),s!==this.authService.getUser()?.userId))return{};let o=yield this.validateResources(t),c;if(i&&this.adapterSelectorService?.isPortableBackendActive?.()===!0){if(c=yield this.fetchPortableUserPermissions(t,o,s??""),s!==this.authService.getUser()?.userId)return{}}else{let[a,n]=yield this.fetchUserPermissionsFromDB(t),d=this.authService.getUser()?.userId;if(s!==d)return{};c=this.buildPermissionsResponse(t,o,a,n)}if(Object.keys(c).length>0){if(!e)this.setCurrentUserPermissions(c);else if(this.permissionsCacheGeneration===r){let a=this.buildPermissionsCacheKey(e);a!==null&&this.requestKeyedPermissionsCache.set(a,JSON.parse(JSON.stringify(c)))}}return c}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return m(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,t=this.requestKeyedPermissionsCache.get(r);if(t)return JSON.parse(JSON.stringify(t));let i=this.inFlightPermissionsRequests.get(r);if(i){let a=yield i;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.reportedPortablePermissionFailures?.clear(),this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let t=e[s];t!==void 0&&(r[s]=Array.isArray(t)?[...t].sort():t)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?k(o):void 0}}let t=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:t,organizationId:t?k(t):void 0}}validateResources(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t,clientOrganizationId:i}=e,o=[],c=[],a=r.length>0||s.length>0;t&&!a&&(o.push(this.organizationDetails(t)),c.push({id:i??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:t??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:t??"",clientDocumentId:u,clientOrganizationId:i})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),l=this.processValidationResults(n,c);return O(v({},this.suppressResolverGrantedFailures(l,i)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let t=this.getPermissionsCache()??[];if(t.length===0)return e;let i=(n,d,l)=>t.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!l||u?.organizationId===l)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&i(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&i(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===g.PERMISSION_DENIED&&r&&i(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return m(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],t=[],i,o={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let u=n.status==="fulfilled"?n.value.errorCode??g.SOMETHING_WENT_WRONG:g.SOMETHING_WENT_WRONG,h={id:d.id,errorCode:u};switch(d.type){case"organization":if(i=h,u===g.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(h);break;case"document":t.push(h);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:t,failedOrganizationId:i,folderAccessTypes:o,documentAccessTypes:c}}fetchPortableUserPermissions(e,r,s){return m(this,null,function*(){try{let t=e.clientOrganizationId??"";if(!s||!t)return{};let i=fe,o=T(e.folderIds??[],i),c=T(e.documentIds??[],i),a=Math.max(o.length,c.length,1),n={},d=this.adapterSelectorService.resolveDbAdapter();for(let h=0;h<a;h++){let f={organizationId:t,userIds:[s]};o[h]?.length&&(f.folderIds=o[h]),c[h]?.length&&(f.documentIds=c[h]);let y=yield ee(d,"getUserPermissions",{scope:"org",data:f});if(!y?.ok)return oe("getUserPermissions",y,{logCatch:(me,ve)=>this.loggingService.catch(me,ve,void 0,!0),reported:this.reportedPortablePermissionFailures,isOutcomeUnknown:le}),{};this.reportedPortablePermissionFailures.clear(),this.mergePortablePermissionsMap(n,this.readPortablePermissionsMap(y.data,s))}let l=n[s],u=l?{[s]:l}:{};return l&&(Object.entries(l.documents??{}).forEach(([h,f])=>{if(f&&!f.accessType){let y=r.documentAccessTypes?.[h]??r.defaultDocumentAccessType;y&&(f.accessType=y)}}),Object.entries(l.folders??{}).forEach(([h,f])=>{if(f&&!f.accessType){let y=r.folderAccessTypes?.[h]??r.defaultDocumentAccessType;y&&(f.accessType=y)}})),this.ensureCurrentUserFailuresRecorded(u,t,r.failedFolderIds,r.failedDocumentIds,r.failedOrganizationId,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processContextPermissions(u),u}catch(t){return this.loggingService.catch("Error in UserPermissionService fetchPortableUserPermissions: ",t),{}}})}readPortablePermissionsMap(e,r){let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(!s(e))return{};let t=new Set(["data","success","statusCode","message"]),i=Object.keys(e);return r!=="data"&&s(e.data)&&i.every(c=>t.has(c))?e.data:e}mergePortablePermissionsMap(e,r){Object.entries(r??{}).forEach(([s,t])=>{if(!t||typeof t!="object")return;let i=e[s]??(e[s]={});t.folders&&(i.folders=v(v({},i.folders??{}),t.folders)),t.documents&&(i.documents=v(v({},i.documents??{}),t.documents)),t.organization&&(i.organization=v(v({},i.organization??{}),t.organization)),t.context&&(i.context=t.context)})}fetchUserPermissionsFromDB(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t}=e,i=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),t??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:i,organizationId:t}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:i,organizationId:t,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,t){let{folderIds:i,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:l}=r,u={};return this.processRegularUserPermissions(u,s,i,o,c??"",a??"",n,d,l,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,l,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,t),this.processContextPermissions(u),u}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,t,i,o,c,a,n,d,l,u){for(let h of r)for(let f of h)f?.user?.userId&&(e[f.user.userId]=O(v({},s.length&&{folders:this.buildFolderPermissions(s,f,c,d,u)}),{documents:this.buildDocumentPermissions(t,f,a,l,u),organization:{[i]:this.buildOrganizationPermission(o,f,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,t,i,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!i&&!!r,l=(s?.length??0)>0,u=(t?.length??0)>0;if(!d&&!l&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode})),l){e[n].folders||(e[n].folders={});for(let h of s)e[n].folders[h.id]||(e[n].folders[h.id]=v({error:this.getErrorMessage(h.errorCode,"folder"),errorCode:h.errorCode},h.errorCode===g.PERMISSION_DENIED&&{accessType:o[h.id]??a??A}))}if(u){e[n].documents||(e[n].documents={});for(let h of t)e[n].documents[h.id]||(e[n].documents[h.id]=v({error:this.getErrorMessage(h.errorCode,"document"),errorCode:h.errorCode},h.errorCode===g.PERMISSION_DENIED&&{accessType:c[h.id]??a??A}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case g.DOES_NOT_EXIST:return`${r} does not exist`;case g.PERMISSION_DENIED:return`User does not have access to ${r}`;case g.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,t,i){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=v({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===g.PERMISSION_DENIED&&{accessType:t[c]??i??A}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?p.VIEWER:p.EDITOR,accessType:t[c]??i??A},o},{})}buildDocumentPermissions(e,r,s,t,i){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=v({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===g.PERMISSION_DENIED&&{accessType:t[c]??i??A}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?p.VIEWER:p.EDITOR,accessType:t[c]??i??A},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?p.VIEWER:p.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[t]={accessRole:i??p.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[t]={accessRole:i??p.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:t,role:i,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[t]={accessRole:i??p.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let t=!0,i=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return i&&(e&&typeof e=="string"&&i?.[o]?.organization?.[e]&&(i?.[o]?.organization?.[e]?.accessRole===p.VIEWER||i?.[o]?.organization?.[e]?.errorCode===g.PERMISSION_DENIED)&&(t=!1),r&&typeof r=="string"&&i?.[o]?.folders?.[r]&&(i?.[o]?.folders?.[r]?.accessRole===p.VIEWER||i?.[o]?.folders?.[r]?.errorCode===g.PERMISSION_DENIED)&&(t=!1),s&&typeof s=="string"&&i?.[o]?.documents?.[s]&&(i?.[o]?.documents?.[s]?.accessRole===p.VIEWER||i?.[o]?.documents?.[s]?.errorCode===g.PERMISSION_DENIED)&&(t=!1)),t}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(F(V))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let t=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[t]){let i=k(t);r[s].organization&&(r[s].organization[i]=r[s].organization[t],delete r[s].organization[t])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([i,o])=>[D(i),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([i,o])=>[_(i),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(W(e=>this.refactorPermissionsWithServerIds(e)),F(V))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return m(this,null,function*(){let e=G();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(i=>{i.userId===s&&i.hasAccess&&(i.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(O(v({},i),{hasAccess:!1})):r.push(O(v({},i),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let i=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});i.success?this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:i,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:i,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return m(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let t=this.getPermissionsCache()??[];s.forEach(c=>{t=t.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(t);let i=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:i});o.success?this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(t){return m(this,arguments,function*({documentIds:e,folderId:r,context:s}){let i=G();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&H({input:s}).forEach(l=>{let u=JSON.stringify(l.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=i,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:i,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return m(this,arguments,function*({requests:e,userId:r}){let t={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?t.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:t})})}sendGetAccessToProxy(t){return m(this,arguments,function*({requests:e,userId:r,metadata:s}){return this.adapterSelectorService?.isPortableBackendActive()?this.sendGetAccessToPortableGateway({requests:e,retryConfig:s?.retryConfig,clientResolvedResults:s?.clientResolvedResults}):this.callHostedGetAccess({type:"getAccess",data:e,metadata:s},r)})}callHostedGetAccess(e,r){return m(this,null,function*(){let s=$(this.functions,x({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield K({methodName:"getAccess",data:e,getSdkProxy:s,userId:r})})}sendGetAccessToPortableGateway(t){return m(this,arguments,function*({requests:e,retryConfig:r,clientResolvedResults:s}){try{let i=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let c of T(e,w)){let a=this.buildPortableGetAccessChunkMetadata(r,this.selectClientResolvedResultsForChunk(s,c)),n=yield i.getAccess(a===void 0?{scope:"org",data:c}:{scope:"org",data:c,metadata:a});if(!n?.ok){let l=n?.code;return this.loggingService.catch("Tier B getAccess denied/failed at the gateway: ",n),{data:[],success:!1,statusCode:this.denialCodeToStatusCode(l)}}let d=n.data?.data??[];o.push(...this.dropUnrequestedEntries(d,c))}return{data:this.skipNotProvidedFolderEntries(o),success:!0,statusCode:200}}catch(i){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",i),{data:[],success:!1,statusCode:500}}})}skipNotProvidedFolderEntries(e){try{this.reportUnrecognizedFolderErrorCodes(e);let r=e.filter(s=>!(s?.type===I.FOLDER&&s?.errorCode==="not_provided"));return r.length!==e.length&&this.loggingService.log(`[WB] Tier B getAccess: ${e.length-r.length} folder answer(s) skipped (errorCode 'not_provided' \u2014 folder subsystem not provisioned on this gateway)`),r}catch(r){return this.loggingService.catch("Error in UserPermissionService skipNotProvidedFolderEntries: ",r),e}}dropUnrequestedEntries(e,r){try{if(!e?.length)return e??[];let s=this.portableGetAccessAskedKeys(r),t=e.filter(i=>s.has(this.portableGetAccessEntryKey(i)));return t.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(i=>!s.has(this.portableGetAccessEntryKey(i))),void 0,!0),t}catch(s){return this.loggingService.catch("Error in UserPermissionService dropUnrequestedEntries: ",s),e}}portableGetAccessEntryKey(e){return`${e?.userId}|${e?.resourceId}|${e?.organizationId}|${e?.type}`}portableGetAccessQueryKey(e){return`${e?.userId}|${e?.resource?.id}|${e?.resource?.organizationId}|${e?.resource?.type}`}portableGetAccessAskedKeys(e){return new Set((e??[]).map(r=>this.portableGetAccessQueryKey(r)))}selectClientResolvedResultsForChunk(e,r){try{if(!e?.length)return[];let s=this.portableGetAccessAskedKeys(r),t=e.filter(a=>s.has(this.portableGetAccessEntryKey(a)));if(t.length<=w)return t;let i=new Map,o=!1;for(let a of t){let n=this.portableGetAccessEntryKey(a),d=i.get(n);if(d===void 0){i.set(n,a);continue}let l=d.hasAccess===!0&&a.hasAccess===!0;o=o||d.hasAccess!==a.hasAccess,i.set(n,l===a.hasAccess?a:O(v({},a),{hasAccess:l}))}let c=Array.from(i.values());return this.loggingService.log(`[WB] Tier B getAccess: the resolver answered ${t.length} results for a ${r.length}-question chunk; duplicate keys collapsed to ${c.length} (the last occurrence per key, as the permissions cache keeps it; hasAccess deny-wins) to stay under the gateway's ${w}-entry cap on clientResolvedResults`),o&&!this.clientResolverContradictionWarned&&(this.clientResolverContradictionWarned=!0,console.warn("[Velt] The client-side dev permission resolver answered the same permission question more than once with contradicting hasAccess values. The answers were collapsed to a denial (deny wins) before being relayed to the self-hosted gateway. Fix the resolver to answer each question once.")),c}catch(s){return this.loggingService.catch("Error in UserPermissionService selectClientResolvedResultsForChunk: ",s),[]}}buildPortableGetAccessChunkMetadata(e,r){if(!(e===void 0&&!r?.length))return v(v({},e===void 0?{}:{retryConfig:e}),r?.length?{clientResolvedResults:r}:{})}reportUnrecognizedFolderErrorCodes(e){try{for(let r of e??[]){let s=r?.errorCode;!s||r?.type!==I.FOLDER||s==="not_provided"||this.reportedUnknownFolderErrorCodes.has(s)||(this.reportedUnknownFolderErrorCodes.add(s),console.warn(`Velt [portable backend]: a folder permission entry carried an unrecognised errorCode '${s}'. It is being consumed verbatim (hasAccess is honoured as sent). If your gateway means the folder subsystem is not provisioned, the expected literal is the exact lowercase 'not_provided' \u2014 anything else reads as a REAL denial and will withhold folder-scoped access.`))}}catch(r){this.loggingService.catch("Error in UserPermissionService reportUnrecognizedFolderErrorCodes: ",r)}}denialCodeToStatusCode(e){switch(e){case"unauthenticated":return 401;case"permission-denied":return 403;case"not-found":return 404;case"invalid-argument":return 400;case"failed-precondition":return 412;case"resource-exhausted":return 429;case"unimplemented":return 501;default:return 500}}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return m(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return m(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),t=r?.resolveTimeout??6e4,i=yield q(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),t),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!i||!i.success||i.statusCode!==200)throw new Error(i?.message??"Client permission resolver failed");let o=i.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return m(this,null,function*(){let s={data:{requests:e}},t=r.endpointConfig?.url?.trim();if(t)return X(t,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let i=yield r.resolvePermissions(s);if(Array.isArray(i))return{data:i,success:!0,statusCode:200};let o=i,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return m(this,null,function*(){if(!r||r<=0)return e();let s,t=new Promise((i,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),t])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(t){return m(this,arguments,function*({requests:e,userId:r,currentContext:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendRevokeAccessToPortableGateway({requests:e,metadata:this.buildRevokeAccessMetadata(s)});let i=$(this.functions,x({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield K({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:this.buildRevokeAccessMetadata(s)},getSdkProxy:i,userId:r})})}buildRevokeAccessMetadata(e){return v({retryConfig:this.getPermissionProviderRetryConfig()},e?.access&&{currentContext:e})}sendRevokeAccessToPortableGateway(s){return m(this,arguments,function*({requests:e,metadata:r}){try{let t=this.adapterSelectorService.resolveDbAdapter();for(let i of T(e,w)){let o=yield t.revokeAccess({scope:"org",data:i,metadata:r});if(!o?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",o),{success:!1}}return{success:!0}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",t),{success:!1}}})}onResourceAccessRequired(o){return m(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:t,fromCache:i=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&i&&(e.forEach(n=>{let d=a?.find(l=>l.resourceId===n.resource.id&&l.type===n.resource.type&&l.userId===n.userId&&l.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:i,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??t??""});return this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(S.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:i}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(t=>{let i=`${t.userId}_${t.resourceId}_${t.organizationId}_${t.type}`;r.set(i,t)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};C.PORTABLE_ACTIVATION_WAIT_MS=1e4,C.\u0275fac=function(r){return new(r||C)(R(ie),R(he),R(Y),R(ue),R(ae),R(de),R(te),R(B),R(Q),R(ge))},C.\u0275prov=L({token:C,factory:C.\u0275fac,providedIn:"root"});let M=C;return M})();export{$e as a};
|