@veltdev/sdk-dev 6.0.34 → 6.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/app/models/data/comment-events.data.model.d.ts +5 -0
  2. package/app/models/data/comment-resolver.data.model.d.ts +1 -1
  3. package/app/models/data/comment-sidebar-config.model.d.ts +12 -0
  4. package/app/models/data/suggestion-events.data.model.d.ts +15 -0
  5. package/app/models/data/suggestion.data.model.d.ts +75 -0
  6. package/app/models/element/comment-element.model.d.ts +4 -2
  7. package/app/models/element/suggestion-element.model.d.ts +25 -0
  8. package/{chunk-XHGU5ZIA.js → chunk-3AXVWFWQ.js} +1 -1
  9. package/{chunk-BYI3X5XU.js → chunk-4GZINSJB.js} +1 -1
  10. package/{chunk-4JDKBL6T.js → chunk-5K23BJBD.js} +1 -1
  11. package/{chunk-HBFQOXCU.js → chunk-5OVPOQXM.js} +1 -1
  12. package/{chunk-ENEBYFM2.js → chunk-6456EREF.js} +1 -1
  13. package/{chunk-GXUATG32.js → chunk-74M4LLJN.js} +1 -1
  14. package/{chunk-XRSE2VTK.js → chunk-7CAYUDV6.js} +25 -25
  15. package/{chunk-67IFTVAR.js → chunk-B4ARTZCP.js} +1 -1
  16. package/{chunk-RA5LKFCC.js → chunk-C3KNUFAS.js} +1 -1
  17. package/{chunk-CABROX7X.js → chunk-CFURN7DG.js} +1 -1
  18. package/{chunk-CTRB5TVE.js → chunk-E4ZYSIOW.js} +1 -1
  19. package/{chunk-UGGDJCBS.js → chunk-ENKKDM6C.js} +1 -1
  20. package/{chunk-YCJV74EN.js → chunk-FPLYS2CV.js} +1 -1
  21. package/{chunk-FDBP2MR3.js → chunk-GSIBDB7Y.js} +1 -1
  22. package/chunk-H6I5XVHO.js +2 -0
  23. package/{chunk-HGX4FLFA.js → chunk-HJVIKKUT.js} +1 -1
  24. package/{chunk-ULT44YLH.js → chunk-JU4BFBOY.js} +1 -1
  25. package/{chunk-XCZQHLLQ.js → chunk-K7FVY4KN.js} +1 -1
  26. package/{chunk-BEFW7P3U.js → chunk-NHKDUTEY.js} +1 -1
  27. package/{chunk-EP7CZ3EM.js → chunk-NX5SHREB.js} +1 -1
  28. package/{chunk-R2ZBBZD3.js → chunk-OB5UEYMT.js} +1 -1
  29. package/{chunk-NFPV353N.js → chunk-SPPCMWKD.js} +1 -1
  30. package/{chunk-34LFLBX5.js → chunk-UW7EL7NW.js} +1 -1
  31. package/{chunk-E5X4SNAK.js → chunk-VGGU4K4I.js} +1 -1
  32. package/{chunk-B6EXKCBS.js → chunk-VI5OSZIQ.js} +1 -1
  33. package/{chunk-VS5M5ZP4.js → chunk-W3PIDHPP.js} +1 -1
  34. package/{chunk-5NN3THOV.js → chunk-W7JRUP3U.js} +1 -1
  35. package/{chunk-IBZ4MVH2.js → chunk-WAIRKNL2.js} +1 -1
  36. package/{chunk-EXDARMGC.js → chunk-WFVUCWNJ.js} +1 -1
  37. package/{chunk-4CIMEMHA.js → chunk-XFGIV7R7.js} +1 -1
  38. package/{chunk-KK5MKT6K.js → chunk-XM5YSR4I.js} +1 -1
  39. package/{chunk-TRW3DRCQ.js → chunk-XQXBBGCT.js} +1 -1
  40. package/{chunk-76PJTJAE.js → chunk-YBUWC65O.js} +1 -1
  41. package/{chunk-UFYGLYSF.js → chunk-YFONDDLR.js} +1 -1
  42. package/{chunk-NGQMBPNS.js → chunk-YGZDTBCO.js} +1 -1
  43. package/{chunk-QRWZNVD6.js → chunk-ZJPFBKE2.js} +1 -1
  44. package/package.json +1 -1
  45. package/velt-activity-log.js +1 -1
  46. package/velt-area.js +1 -1
  47. package/velt-arrow.js +1 -1
  48. package/velt-comment.js +32 -7
  49. package/velt-crdt.js +1 -1
  50. package/velt-cursor.js +1 -1
  51. package/velt-huddle.js +1 -1
  52. package/velt-live-state-sync.js +1 -1
  53. package/velt-notification.js +1 -1
  54. package/velt-portable.js +1 -1
  55. package/velt-presence.js +1 -1
  56. package/velt-reaction.js +1 -1
  57. package/velt-recorder.js +1 -1
  58. package/velt-rewriter.js +1 -1
  59. package/velt-selection.js +1 -1
  60. package/velt-tag.js +1 -1
  61. package/velt-user-invite.js +1 -1
  62. package/velt-user-request.js +1 -1
  63. package/velt-video-player.js +1 -1
  64. package/velt-views.js +1 -1
  65. package/velt.js +4 -4
  66. package/chunk-OE6TZOZO.js +0 -2
@@ -212,6 +212,11 @@ export interface DeleteCommentAnnotationEvent {
212
212
  commentAnnotation: CommentAnnotation;
213
213
  metadata: VeltEventMetadata;
214
214
  }
215
+ /**
216
+ * `suggestionAccepted` on the comment element. Also fires when the target could not be resolved; then
217
+ * `commentAnnotation.suggestion.status` is `'stale'` (the suggestion element fires `suggestionStale` instead of
218
+ * `suggestionApproved`). Fires only in the tab where the action ran.
219
+ */
215
220
  export interface SuggestionAcceptEvent {
216
221
  annotationId: string;
217
222
  commentAnnotation: CommentAnnotation;
@@ -118,7 +118,7 @@ export interface PartialCommentAnnotation {
118
118
  resolvedByUserId?: string | null;
119
119
  /**
120
120
  * The suggestion (comment-resolver iteration-3) — present when the annotation carries one. Its
121
- * content keys (`oldValue`, `newValue`, `summary`, `rejectReason`) are PII: they live only here,
121
+ * content keys (`oldValue`, `newValue`, `summary`, `rejectReason`, `metadata`, `textChange`) are PII: they live only here,
122
122
  * never in Velt. When sent it is always COMPLETE (the content your store already holds plus this
123
123
  * write), so a backend may replace the stored value wholesale. `resolvedBy` may be `{ userId }`
124
124
  * under a user resolver. On `get`, only the content keys are read back — Velt stays authoritative
@@ -94,4 +94,16 @@ export declare class CommentSidebarData {
94
94
  export declare class CommentSidebarDataOptions {
95
95
  grouping?: boolean;
96
96
  }
97
+ /**
98
+ * Optional config for `openCommentSidebar(config?)`.
99
+ */
100
+ export interface OpenCommentSidebarConfig {
101
+ /**
102
+ * Open the sidebar on this comment annotation. With `focusedThreadMode` and `openAnnotationInFocusMode` on, the
103
+ * thread opens in focused view (even if the list's filters hide it); otherwise its card is scrolled into view.
104
+ * Applied once the sidebar has loaded the annotation (up to 10 s); an unknown id logs one warning. Does not
105
+ * select the annotation (no pin dialog opens) and does not move keyboard focus. Sidebar V2 only.
106
+ */
107
+ annotationId?: string;
108
+ }
97
109
  export {};
@@ -47,6 +47,21 @@ export interface TargetEditCommitEvent {
47
47
  commitSuggestion: TargetEditCommitBuilder;
48
48
  timestamp: number;
49
49
  }
50
+ /**
51
+ * Suggestion events, as fired from the suggestion element (`getSuggestionElement().on(...)`).
52
+ *
53
+ * Which event fires for a suggestion's outcome, on which element:
54
+ *
55
+ * | Outcome | Suggestion element | Comment element (`getCommentElement().on(...)`) |
56
+ * |----------------------------------|-----------------------|---------------------------------------------------------|
57
+ * | Accept (target resolves) | `suggestionApproved` | `suggestionAccepted` |
58
+ * | Accept, target unresolvable | `suggestionStale` | `suggestionAccepted` (its annotation's `suggestion.status` is `'stale'`) |
59
+ * | Reject | `suggestionRejected` | `suggestionRejected` |
60
+ *
61
+ * A target resolves through its element on the page OR a getter registered with `registerTarget`; it is
62
+ * unresolvable only with neither. Events fire in the browser tab where Accept/Reject ran (from the sidebar card,
63
+ * an embedded thread or the API); other tabs see the change through the annotation itself.
64
+ */
50
65
  export type SuggestionEventTypesMap = {
51
66
  [SuggestionEventTypes.SUGGESTION_CREATED]: SuggestionCreatedEvent;
52
67
  [SuggestionEventTypes.SUGGESTION_APPROVED]: SuggestionApprovedEvent;
@@ -40,6 +40,36 @@ export type SuggestionTargetType = 'custom';
40
40
  export interface RegisterTargetConfig<T = unknown> {
41
41
  targetId: string;
42
42
  getter: TargetGetter<T>;
43
+ /**
44
+ * Writes a value into the target — the app's own write path (form state, store, save). With a setter the SDK
45
+ * puts the target back once an edit's suggestion is committed (see `restoreOnCommit`) and applies an accepted
46
+ * suggestion's value on the client that accepted it. Without one the SDK never writes to the target.
47
+ */
48
+ setter?: TargetSetter<T>;
49
+ /**
50
+ * With a `setter`: once the suggestion made from an edit is committed, call `setter(valueOnFocus, { reason:
51
+ * 'restore' })` so the target shows its saved value again. Default true. Accept applies through the setter
52
+ * either way.
53
+ */
54
+ restoreOnCommit?: boolean;
55
+ }
56
+ /**
57
+ * Registered with `registerTarget({ targetId, getter, setter })`. The SDK calls it:
58
+ * - `reason: 'restore'` — the suggestion made from an edit was committed; `value` is the target's value when the
59
+ * edit started (put the field back; there is nothing new to save while suggesting).
60
+ * - `reason: 'accept'` — a suggestion on this target was accepted on THIS client; `value` is the accepted value
61
+ * (save it). Called once, after the accepted status is saved and before `suggestionApproved` fires. Other
62
+ * clients don't call their setter: they get the value through the app's own data.
63
+ *
64
+ * While suggestion mode is on, don't save a registered target's edits yourself — save in the 'accept' call.
65
+ * A setter that throws (or rejects) is caught and logged; it never blocks the suggestion.
66
+ */
67
+ export type TargetSetter<T = unknown> = (value: T, context: TargetSetterContext<T>) => void | Promise<void>;
68
+ export interface TargetSetterContext<T = unknown> {
69
+ targetId: string;
70
+ reason: 'restore' | 'accept';
71
+ /** `reason: 'accept'` only: the accepted suggestion, as `suggestionApproved` carries it. */
72
+ suggestion?: Suggestion<T>;
43
73
  }
44
74
  /**
45
75
  * Function the customer registers via SuggestionElement.registerTarget(config).
@@ -118,6 +148,34 @@ export interface TargetEditCommitResult {
118
148
  summaryHtml?: string;
119
149
  /** Customer metadata persisted on the resulting suggestion (`Suggestion.metadata`). */
120
150
  metadata?: Record<string, unknown>;
151
+ /** Where the change sits in a text target (`Suggestion.textChange`). Overrides the one the SDK works out. */
152
+ textChange?: SuggestionTextChange;
153
+ }
154
+ /**
155
+ * Where a suggestion on TEXT sits: what it removes and adds, the unchanged text around it, and which
156
+ * occurrence of that text it is. Stored as `annotation.suggestion.textChange` and returned as
157
+ * `Suggestion.textChange`, the same for every kind of text target (contenteditable fields, rich-text
158
+ * editors), so any screen can find the change again and draw it in place.
159
+ *
160
+ * - Passed by an integration on `commitSuggestion`, or worked out by the SDK for a contenteditable
161
+ * target with no registered getter.
162
+ * - Never re-written after commit: readers find the spot again from the context each time.
163
+ * - Self-hosting: suggestion content — with a comment resolver it is stored by the resolver only,
164
+ * like `oldValue` / `newValue`.
165
+ * - The SDK may add optional keys later; unknown keys passed in are dropped (use `metadata` for your
166
+ * own data).
167
+ */
168
+ export interface SuggestionTextChange {
169
+ /** Text the suggestion removes ('' for a pure insertion). */
170
+ removed: string;
171
+ /** Text the suggestion adds ('' for a pure deletion). */
172
+ added: string;
173
+ /** Up to 32 characters of unchanged text right before the change. */
174
+ contextBefore: string;
175
+ /** Up to 32 characters of unchanged text right after the change. */
176
+ contextAfter: string;
177
+ /** Which non-overlapping match (1-based) of `contextBefore + removed + contextAfter` in the old text it is. */
178
+ occurrence: number;
121
179
  }
122
180
  /**
123
181
  * Return type of `onTargetEditStart`. Reserved for future fields; v1 has
@@ -209,6 +267,11 @@ export interface SuggestionData {
209
267
  * Self-hosting: content — with a comment resolver it is stored by the resolver only.
210
268
  */
211
269
  metadata?: Record<string, unknown>;
270
+ /**
271
+ * Where the change sits in a text target (absent when unknown). Self-hosting: content — with a
272
+ * comment resolver it is stored by the resolver only.
273
+ */
274
+ textChange?: SuggestionTextChange;
212
275
  }
213
276
  /**
214
277
  * Fields shared across every Suggestion regardless of status.
@@ -232,6 +295,11 @@ interface SuggestionBase<T = unknown> {
232
295
  * `{}` when none was given). Contains only the customer's keys.
233
296
  */
234
297
  metadata: Record<string, any>;
298
+ /**
299
+ * Where the change sits in a text target; null (or absent) when unknown — non-text targets such as plain fields
300
+ * and objects, and older suggestions. Optional so code that builds `Suggestion` values needs no change.
301
+ */
302
+ textChange?: SuggestionTextChange | null;
235
303
  /** True iff the live value at approve time differed from oldValue. */
236
304
  driftDetected: boolean;
237
305
  /**
@@ -311,6 +379,13 @@ export interface CommitSuggestionConfig<T = unknown> {
311
379
  * resolver (self-hosting) it is stored by the resolver only.
312
380
  */
313
381
  metadata?: Record<string, unknown>;
382
+ /**
383
+ * Optional: where the change sits in a text target. Integrations that know it (a rich-text editor)
384
+ * pass it; for a contenteditable target with no registered getter the SDK works it out when it is
385
+ * omitted. An invalid value is not saved (dev warning); the commit still succeeds. With a comment
386
+ * resolver (self-hosting) it is stored by the resolver only.
387
+ */
388
+ textChange?: SuggestionTextChange;
314
389
  }
315
390
  /**
316
391
  * Pre-bound builder attached to `targetEditCommit` payloads. Calling it
@@ -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 } from "../data/comment-sidebar-config.model";
10
+ import { CommentSidebarCustomActionEventData, CommentSidebarCustomActionsState, CommentSidebarData, CommentSidebarDataOptions, OpenCommentSidebarConfig } 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";
@@ -73,8 +73,10 @@ export declare class CommentElement {
73
73
 
74
74
  /**
75
75
  * To open comment sidebar
76
+ * @param config Optional. `{ annotationId }` opens the sidebar on that thread: focused view with
77
+ * `focusedThreadMode` + `openAnnotationInFocusMode`, otherwise its card is scrolled into view (sidebar V2).
76
78
  */
77
- openCommentSidebar: () => void;
79
+ openCommentSidebar: (config?: OpenCommentSidebarConfig) => void;
78
80
 
79
81
  /**
80
82
  * To close comment sidebar
@@ -29,6 +29,21 @@ export declare class SuggestionElement {
29
29
  */
30
30
  isSuggestionModeEnabled$: () => Observable<boolean>;
31
31
 
32
+ /**
33
+ * Draw pending suggestions inside contenteditable suggestion targets (the default): the removed text struck through,
34
+ * the added text in green, and a click on them opens the suggestion's thread. While suggesting, the change being
35
+ * typed in such a field is drawn as it is typed and separate edits become separate suggestions.
36
+ */
37
+ enableInlineSuggestions: () => void;
38
+
39
+ /**
40
+ * Never touch contenteditable suggestion targets: nothing is drawn inside them (what was drawn is taken out),
41
+ * typed changes are not tracked edit by edit (one suggestion per visit to a field), and their undo is left to the
42
+ * browser. Use when the field's DOM must stay the app's own (a framework-controlled field, an app that saves
43
+ * innerHTML). Suggestions still work and show in the sidebar and dialogs.
44
+ */
45
+ disableInlineSuggestions: () => void;
46
+
32
47
  /**
33
48
  * Register a getter that returns the current value of a tagged target.
34
49
  * Required for non-primitive (wrapper) targets — the SDK calls this on
@@ -36,6 +51,10 @@ export declare class SuggestionElement {
36
51
  *
37
52
  * The getter must reflect edit-time state (typically read from the DOM),
38
53
  * not the persisted customer state. See `RegisterTargetConfig`.
54
+ *
55
+ * Optional `setter`: the app's write path for the target. The SDK puts the target back once an edit's
56
+ * suggestion is committed (`restoreOnCommit`, default true) and applies an accepted suggestion's value on the
57
+ * client that accepted it. See `TargetSetter`.
39
58
  */
40
59
  registerTarget: <T = unknown>(config: RegisterTargetConfig<T>) => void;
41
60
 
@@ -115,6 +134,8 @@ export declare class SuggestionElement {
115
134
  * Reactive enable-flag stream; deduplicated.
116
135
  */
117
136
  private _isSuggestionModeEnabled$;
137
+ private _enableInlineSuggestions;
138
+ private _disableInlineSuggestions;
118
139
 
119
140
  /**
120
141
  * Register a getter that returns the current value of a tagged target.
@@ -123,6 +144,10 @@ export declare class SuggestionElement {
123
144
  *
124
145
  * The getter must reflect edit-time state (typically read from the DOM),
125
146
  * not the persisted customer state. See `RegisterTargetConfig`.
147
+ *
148
+ * Optional `setter`: the app's write path for the target. The SDK puts the target back once an edit's
149
+ * suggestion is committed (`restoreOnCommit`, default true) and applies an accepted suggestion's value on the
150
+ * client that accepted it. See `TargetSetter`.
126
151
  */
127
152
  private _registerTarget;
128
153
 
@@ -1,4 +1,4 @@
1
- import{c as Y}from"./chunk-GXUATG32.js";import{A as _,D as x,E as Q}from"./chunk-VS5M5ZP4.js";import{Ak as K,C as A,E as g,Jj as R,Ld as w,M as S,Mj as M,Nd as y,O as B,Od as U,Pd as O,U as F,V as H,Y as E,_f as D,ba as j,di as P,ea as b,g as $,l as C,p as k,qj as W,r as u,rj as L,v as m,w as z,zk as N}from"./chunk-XRSE2VTK.js";var he=(()=>{let p=class p{constructor(e,t,r,a,s,c,n,i,d,o){this.authService=e,this.commonDbService=t,this.databaseService=r,this.docService=a,this.domService=s,this.loggingService=c,this.metadataService=n,this.commonDbUtils=i,this.configService=d,this.realtimeAdapter=o,this.HEARTBEAT_DURATION=5*1e3,this.heartbeatEnabled$=new C(!1),this.subscriptions=[],this.heartbeatCreatedTimestamps=new Map,this.initializedHeartbeatIds=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: HeartbeatService","color: blue;"),this.heartbeatEnabled$.pipe(S()).subscribe(h=>{h?this.setupHeartbeat():this.teardownHeartbeat()}),this.docService.addPreDocumentIdChangeFunction("heartbeat-service",h=>h?.documentId?this.removeDocumentHeartbeat(h):Promise.resolve())}catch(h){this.loggingService.catch("Error in HeartbeatService constructor: ",h)}}setupWebWorker(e){try{let t=`
1
+ import{c as Y}from"./chunk-74M4LLJN.js";import{A as _,D as x,E as Q}from"./chunk-W3PIDHPP.js";import{Ak as K,C as A,E as g,Jj as R,Ld as w,M as S,Mj as M,Nd as y,O as B,Od as U,Pd as O,U as F,V as H,Y as E,_f as D,ba as j,di as P,ea as b,g as $,l as C,p as k,qj as W,r as u,rj as L,v as m,w as z,zk as N}from"./chunk-7CAYUDV6.js";var he=(()=>{let p=class p{constructor(e,t,r,a,s,c,n,i,d,o){this.authService=e,this.commonDbService=t,this.databaseService=r,this.docService=a,this.domService=s,this.loggingService=c,this.metadataService=n,this.commonDbUtils=i,this.configService=d,this.realtimeAdapter=o,this.HEARTBEAT_DURATION=5*1e3,this.heartbeatEnabled$=new C(!1),this.subscriptions=[],this.heartbeatCreatedTimestamps=new Map,this.initializedHeartbeatIds=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: HeartbeatService","color: blue;"),this.heartbeatEnabled$.pipe(S()).subscribe(h=>{h?this.setupHeartbeat():this.teardownHeartbeat()}),this.docService.addPreDocumentIdChangeFunction("heartbeat-service",h=>h?.documentId?this.removeDocumentHeartbeat(h):Promise.resolve())}catch(h){this.loggingService.catch("Error in HeartbeatService constructor: ",h)}}setupWebWorker(e){try{let t=`
2
2
  let intervalId;
3
3
  self.addEventListener('message', (event) => {
4
4
  if (event.data === 'start') {
@@ -1 +1 @@
1
- import{Fa as F}from"./chunk-IBZ4MVH2.js";import{D as C,E as w}from"./chunk-VS5M5ZP4.js";import{Ak as U,E as h,G as d,He as $,Ii as D,Jj as k,K as v,M as l,V as n,_f as g,ba as A,di as I,ea as s,l as p,nf as M,pj as E,qj as R,r as u,rj as y,v as c,we as a,xe as m}from"./chunk-XRSE2VTK.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.getUser(),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.user&&this.getDocumentIam(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.databaseService.getDbValue()&&this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(U),s(F),s(k),s(w),s(y),s(R),s(C))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
1
+ import{Fa as F}from"./chunk-WAIRKNL2.js";import{D as C,E as w}from"./chunk-W3PIDHPP.js";import{Ak as U,E as h,G as d,He as $,Ii as D,Jj as k,K as v,M as l,V as n,_f as g,ba as A,di as I,ea as s,l as p,nf as M,pj as E,qj as R,r as u,rj as y,v as c,we as a,xe as m}from"./chunk-7CAYUDV6.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.getUser(),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.user&&this.getDocumentIam(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.databaseService.getDbValue()&&this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(U),s(F),s(k),s(w),s(y),s(R),s(C))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
@@ -1 +1 @@
1
- import{Fa as ge}from"./chunk-IBZ4MVH2.js";import{B as le,D as ue,E as he,b as oe,m as ne,n as ce,p as ae,s as de}from"./chunk-VS5M5ZP4.js";import{$f as T,Ak as ie,He as b,Ii as E,Ji as $,M as F,Nj as ee,Pf as p,Qd as B,Qf as g,Qj as re,Uj as se,_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 H,kg as J,ki as X,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,vk as te,wj as Z}from"./chunk-XRSE2VTK.js";var A="public",w=100,fe=50,$e=(()=>{let C=class C{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,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,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&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(t=>!J(t));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 i=this.contactService.getUserAccessFieldsByUserId(e);return i?.length?s.every(t=>i.includes(t)):!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}){try{if(this.isMetadataProbeUnanswerable("documentMetadata")){let n=yield this.docService.readPortableDocumentForProbe?.(e,s);return n?.accessType?{error:!1,accessType:n.accessType}:{error:!1}}let t=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(t&&t?.errorCode)return{errorCode:g.PERMISSION_DENIED,error:!0};if(t&&!t?.metadata)return{errorCode:g.DOES_NOT_EXIST,error:!0};let o=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,v(v({},o),t?.metadata??{}));let c,a=t?.metadata?.veltFolderId;if(a)try{c=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:a,organizationId:r}}))?.folderIamConfig?.accessType}catch(n){this.loggingService.catch("Error fetching folder accessType for document:",n)}return c||(c=t?.docIamConfig?.accessType),{error:!1,accessType:c}}catch(t){return this.loggingService.catch("Error in UserPermissionService documentDetails:",t),{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 i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{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,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=this.adapterSelectorService?.isPortableSession?.()===!0;if(t&&this.adapterSelectorService?.isPortableBackendActive?.()!==!0&&(yield re(C.PORTABLE_ACTIVATION_WAIT_MS),s!==this.authService.getUser()?.userId))return{};let o=yield this.validateResources(i),c;if(t&&this.adapterSelectorService?.isPortableBackendActive?.()===!0){if(c=yield this.fetchPortableUserPermissions(i,o,s??""),s!==this.authService.getUser()?.userId)return{}}else{let[a,n]=yield this.fetchUserPermissionsFromDB(i),d=this.authService.getUser()?.userId;if(s!==d)return{};c=this.buildPermissionsResponse(i,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,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;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 i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),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 i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?k(i):void 0}}validateResources(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??"",clientDocumentId:u})),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,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,l)=>i.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&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===g.PERMISSION_DENIED&&r&&t(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=[],i=[],t,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(t=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":i.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:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchPortableUserPermissions(e,r,s){return m(this,null,function*(){try{let i=e.clientOrganizationId??"";if(!s||!i)return{};let t=fe,o=T(e.folderIds??[],t),c=T(e.documentIds??[],t),a=Math.max(o.length,c.length,1),n={},d=this.adapterSelectorService.resolveDbAdapter();for(let h=0;h<a;h++){let f={organizationId:i,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.processContextPermissions(u),u}catch(i){return this.loggingService.catch("Error in UserPermissionService fetchPortableUserPermissions: ",i),{}}})}readPortablePermissionsMap(e,r){let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(!s(e))return{};let i=new Set(["data","success","statusCode","message"]),t=Object.keys(e);return r!=="data"&&s(e.data)&&t.every(c=>i.has(c))?e.data:e}mergePortablePermissionsMap(e,r){Object.entries(r??{}).forEach(([s,i])=>{if(!i||typeof i!="object")return;let t=e[s]??(e[s]={});i.folders&&(t.folders=v(v({},t.folders??{}),i.folders)),i.documents&&(t.documents=v(v({},t.documents??{}),i.documents)),i.organization&&(t.organization=v(v({},t.organization??{}),i.organization)),i.context&&(t.context=i.context)})}fetchUserPermissionsFromDB(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:l}=r,u={};return this.processRegularUserPermissions(u,s,t,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,i),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,i,t,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(i,f,a,l,u),organization:{[t]:this.buildOrganizationPermission(o,f,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,l=(s?.length??0)>0,u=(i?.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(t.errorCode,"organization"),errorCode:t.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 i)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,i,t){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:i[c]??t??A}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?p.VIEWER:p.EDITOR,accessType:i[c]??t??A},o},{})}buildDocumentPermissions(e,r,s,i,t){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:i[c]??t??A}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?p.VIEWER:p.EDITOR,accessType:i[c]??t??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:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??p.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??p.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??p.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===p.VIEWER||t?.[o]?.organization?.[e]?.errorCode===g.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===p.VIEWER||t?.[o]?.folders?.[r]?.errorCode===g.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===p.VIEWER||t?.[o]?.documents?.[s]?.errorCode===g.PERMISSION_DENIED)&&(i=!1)),i}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 i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=k(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[D(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),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(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(O(v({},t),{hasAccess:!1})):r.push(O(v({},t),{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 t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.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:t,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:t,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 i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});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(i){return m(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=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()&&X({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:t,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:t,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,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:t,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 i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){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(i){return m(this,arguments,function*({requests:e,retryConfig:r,clientResolvedResults:s}){try{let t=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let c of T(e,w)){let a=this.buildPortableGetAccessChunkMetadata(r,this.selectClientResolvedResultsForChunk(s,c)),n=yield t.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(t){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",t),{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),i=e.filter(t=>s.has(this.portableGetAccessEntryKey(t)));return i.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(t=>!s.has(this.portableGetAccessEntryKey(t))),void 0,!0),i}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),i=e.filter(a=>s.has(this.portableGetAccessEntryKey(a)));if(i.length<=w)return i;let t=new Map,o=!1;for(let a of i){let n=this.portableGetAccessEntryKey(a),d=t.get(n);if(d===void 0){t.set(n,a);continue}let l=d.hasAccess===!0&&a.hasAccess===!0;o=o||d.hasAccess!==a.hasAccess,t.set(n,l===a.hasAccess?a:O(v({},a),{hasAccess:l}))}let c=Array.from(t.values());return this.loggingService.log(`[WB] Tier B getAccess: the resolver answered ${i.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(),i=r?.resolveTimeout??6e4,t=yield q(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.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}},i=r.endpointConfig?.url?.trim();if(i)return H(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,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,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}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(i){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 t=$(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:t,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 i=this.adapterSelectorService.resolveDbAdapter();for(let t of T(e,w)){let o=yield i.revokeAccess({scope:"org",data:t,metadata:r});if(!o?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",o),{success:!1}}return{success:!0}}catch(i){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",i),{success:!1}}})}onResourceAccessRequired(o){return m(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(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:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});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:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});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-WAIRKNL2.js";import{B as le,D as ue,E as he,b as oe,m as ne,n as ce,p as ae,s as de}from"./chunk-W3PIDHPP.js";import{$f as T,Ak as ie,He as b,Ii as E,Ji as $,M as F,Nj as ee,Pf as p,Qd as B,Qf as g,Qj as re,Uj as se,_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 H,kg as J,ki as X,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,vk as te,wj as Z}from"./chunk-7CAYUDV6.js";var A="public",w=100,fe=50,$e=(()=>{let C=class C{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,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,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&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(t=>!J(t));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 i=this.contactService.getUserAccessFieldsByUserId(e);return i?.length?s.every(t=>i.includes(t)):!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}){try{if(this.isMetadataProbeUnanswerable("documentMetadata")){let n=yield this.docService.readPortableDocumentForProbe?.(e,s);return n?.accessType?{error:!1,accessType:n.accessType}:{error:!1}}let t=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(t&&t?.errorCode)return{errorCode:g.PERMISSION_DENIED,error:!0};if(t&&!t?.metadata)return{errorCode:g.DOES_NOT_EXIST,error:!0};let o=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,v(v({},o),t?.metadata??{}));let c,a=t?.metadata?.veltFolderId;if(a)try{c=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:a,organizationId:r}}))?.folderIamConfig?.accessType}catch(n){this.loggingService.catch("Error fetching folder accessType for document:",n)}return c||(c=t?.docIamConfig?.accessType),{error:!1,accessType:c}}catch(t){return this.loggingService.catch("Error in UserPermissionService documentDetails:",t),{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 i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:g.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:g.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{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,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=this.adapterSelectorService?.isPortableSession?.()===!0;if(t&&this.adapterSelectorService?.isPortableBackendActive?.()!==!0&&(yield re(C.PORTABLE_ACTIVATION_WAIT_MS),s!==this.authService.getUser()?.userId))return{};let o=yield this.validateResources(i),c;if(t&&this.adapterSelectorService?.isPortableBackendActive?.()===!0){if(c=yield this.fetchPortableUserPermissions(i,o,s??""),s!==this.authService.getUser()?.userId)return{}}else{let[a,n]=yield this.fetchUserPermissionsFromDB(i),d=this.authService.getUser()?.userId;if(s!==d)return{};c=this.buildPermissionsResponse(i,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,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;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 i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),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 i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?k(i):void 0}}validateResources(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??"",clientDocumentId:u})),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,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,l)=>i.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&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===g.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===g.PERMISSION_DENIED&&r&&t(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=[],i=[],t,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(t=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":i.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:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchPortableUserPermissions(e,r,s){return m(this,null,function*(){try{let i=e.clientOrganizationId??"";if(!s||!i)return{};let t=fe,o=T(e.folderIds??[],t),c=T(e.documentIds??[],t),a=Math.max(o.length,c.length,1),n={},d=this.adapterSelectorService.resolveDbAdapter();for(let h=0;h<a;h++){let f={organizationId:i,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.processContextPermissions(u),u}catch(i){return this.loggingService.catch("Error in UserPermissionService fetchPortableUserPermissions: ",i),{}}})}readPortablePermissionsMap(e,r){let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c);if(!s(e))return{};let i=new Set(["data","success","statusCode","message"]),t=Object.keys(e);return r!=="data"&&s(e.data)&&t.every(c=>i.has(c))?e.data:e}mergePortablePermissionsMap(e,r){Object.entries(r??{}).forEach(([s,i])=>{if(!i||typeof i!="object")return;let t=e[s]??(e[s]={});i.folders&&(t.folders=v(v({},t.folders??{}),i.folders)),i.documents&&(t.documents=v(v({},t.documents??{}),i.documents)),i.organization&&(t.organization=v(v({},t.organization??{}),i.organization)),i.context&&(t.context=i.context)})}fetchUserPermissionsFromDB(e){return m(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:l}=r,u={};return this.processRegularUserPermissions(u,s,t,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,i),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,i,t,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(i,f,a,l,u),organization:{[t]:this.buildOrganizationPermission(o,f,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,l=(s?.length??0)>0,u=(i?.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(t.errorCode,"organization"),errorCode:t.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 i)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,i,t){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:i[c]??t??A}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?p.VIEWER:p.EDITOR,accessType:i[c]??t??A},o},{})}buildDocumentPermissions(e,r,s,i,t){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:i[c]??t??A}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?p.VIEWER:p.EDITOR,accessType:i[c]??t??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:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??p.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??p.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??p.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===p.VIEWER||t?.[o]?.organization?.[e]?.errorCode===g.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===p.VIEWER||t?.[o]?.folders?.[r]?.errorCode===g.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===p.VIEWER||t?.[o]?.documents?.[s]?.errorCode===g.PERMISSION_DENIED)&&(i=!1)),i}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 i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=k(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[D(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),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(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(O(v({},t),{hasAccess:!1})):r.push(O(v({},t),{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 t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.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:t,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:t,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 i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});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(i){return m(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=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()&&X({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:t,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:t,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,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:t,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 i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){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(i){return m(this,arguments,function*({requests:e,retryConfig:r,clientResolvedResults:s}){try{let t=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let c of T(e,w)){let a=this.buildPortableGetAccessChunkMetadata(r,this.selectClientResolvedResultsForChunk(s,c)),n=yield t.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(t){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",t),{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),i=e.filter(t=>s.has(this.portableGetAccessEntryKey(t)));return i.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(t=>!s.has(this.portableGetAccessEntryKey(t))),void 0,!0),i}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),i=e.filter(a=>s.has(this.portableGetAccessEntryKey(a)));if(i.length<=w)return i;let t=new Map,o=!1;for(let a of i){let n=this.portableGetAccessEntryKey(a),d=t.get(n);if(d===void 0){t.set(n,a);continue}let l=d.hasAccess===!0&&a.hasAccess===!0;o=o||d.hasAccess!==a.hasAccess,t.set(n,l===a.hasAccess?a:O(v({},a),{hasAccess:l}))}let c=Array.from(t.values());return this.loggingService.log(`[WB] Tier B getAccess: the resolver answered ${i.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(),i=r?.resolveTimeout??6e4,t=yield q(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.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}},i=r.endpointConfig?.url?.trim();if(i)return H(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,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,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}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(i){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 t=$(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:t,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 i=this.adapterSelectorService.resolveDbAdapter();for(let t of T(e,w)){let o=yield i.revokeAccess({scope:"org",data:t,metadata:r});if(!o?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",o),{success:!1}}return{success:!0}}catch(i){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",i),{success:!1}}})}onResourceAccessRequired(o){return m(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(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:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});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:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});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};