@memberjunction/core-entities-server 6.2.1 → 6.3.0-edge.0

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 (96) hide show
  1. package/README.md +19 -0
  2. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts +0 -14
  3. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationReadSecurityHook.js +27 -2
  5. package/dist/custom/AnchoredConversationReadSecurityHook.js.map +1 -1
  6. package/dist/custom/ConversationAndCommentDrivers.d.ts +82 -0
  7. package/dist/custom/ConversationAndCommentDrivers.d.ts.map +1 -0
  8. package/dist/custom/ConversationAndCommentDrivers.js +543 -0
  9. package/dist/custom/ConversationAndCommentDrivers.js.map +1 -0
  10. package/dist/custom/FieldSuggestionRecordChangeHook.d.ts +17 -0
  11. package/dist/custom/FieldSuggestionRecordChangeHook.d.ts.map +1 -0
  12. package/dist/custom/FieldSuggestionRecordChangeHook.js +142 -0
  13. package/dist/custom/FieldSuggestionRecordChangeHook.js.map +1 -0
  14. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts +11 -0
  15. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts.map +1 -1
  16. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js +41 -0
  17. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js.map +1 -1
  18. package/dist/custom/MJAIPromptRunEntityServer.server.d.ts +21 -0
  19. package/dist/custom/MJAIPromptRunEntityServer.server.d.ts.map +1 -1
  20. package/dist/custom/MJAIPromptRunEntityServer.server.js +76 -5
  21. package/dist/custom/MJAIPromptRunEntityServer.server.js.map +1 -1
  22. package/dist/custom/MJCommentEntityServer.server.d.ts +19 -0
  23. package/dist/custom/MJCommentEntityServer.server.d.ts.map +1 -0
  24. package/dist/custom/MJCommentEntityServer.server.js +137 -0
  25. package/dist/custom/MJCommentEntityServer.server.js.map +1 -0
  26. package/dist/custom/MJConversationEntityServer.server.d.ts.map +1 -1
  27. package/dist/custom/MJConversationEntityServer.server.js +16 -1
  28. package/dist/custom/MJConversationEntityServer.server.js.map +1 -1
  29. package/dist/custom/MJFieldSuggestionEntityServer.server.d.ts +29 -0
  30. package/dist/custom/MJFieldSuggestionEntityServer.server.d.ts.map +1 -0
  31. package/dist/custom/MJFieldSuggestionEntityServer.server.js +249 -0
  32. package/dist/custom/MJFieldSuggestionEntityServer.server.js.map +1 -0
  33. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +197 -0
  34. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -0
  35. package/dist/custom/MJGraphEdgeEntityServer.server.js +459 -0
  36. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -0
  37. package/dist/custom/MJGraphEdgeProviderEntityServer.server.d.ts +22 -0
  38. package/dist/custom/MJGraphEdgeProviderEntityServer.server.d.ts.map +1 -0
  39. package/dist/custom/MJGraphEdgeProviderEntityServer.server.js +85 -0
  40. package/dist/custom/MJGraphEdgeProviderEntityServer.server.js.map +1 -0
  41. package/dist/custom/MJGraphEdgeTypeEntityServer.server.d.ts +21 -0
  42. package/dist/custom/MJGraphEdgeTypeEntityServer.server.d.ts.map +1 -0
  43. package/dist/custom/MJGraphEdgeTypeEntityServer.server.js +88 -0
  44. package/dist/custom/MJGraphEdgeTypeEntityServer.server.js.map +1 -0
  45. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.d.ts +39 -0
  46. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.d.ts.map +1 -0
  47. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.js +124 -0
  48. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.js.map +1 -0
  49. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts +124 -0
  50. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts.map +1 -0
  51. package/dist/custom/MJMLPredictionUnitEntityServer.server.js +214 -0
  52. package/dist/custom/MJMLPredictionUnitEntityServer.server.js.map +1 -0
  53. package/dist/custom/MJMLTrainingPipelineEntityServer.server.d.ts +101 -1
  54. package/dist/custom/MJMLTrainingPipelineEntityServer.server.d.ts.map +1 -1
  55. package/dist/custom/MJMLTrainingPipelineEntityServer.server.js +266 -12
  56. package/dist/custom/MJMLTrainingPipelineEntityServer.server.js.map +1 -1
  57. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.d.ts +14 -0
  58. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.d.ts.map +1 -0
  59. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.js +42 -0
  60. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.js.map +1 -0
  61. package/dist/custom/MJQueryEntityServer.server.d.ts +2 -2
  62. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  63. package/dist/custom/MJQueryEntityServer.server.js +7 -5
  64. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  65. package/dist/custom/MJTaskDependencyEntityServer.server.d.ts +24 -0
  66. package/dist/custom/MJTaskDependencyEntityServer.server.d.ts.map +1 -0
  67. package/dist/custom/MJTaskDependencyEntityServer.server.js +75 -0
  68. package/dist/custom/MJTaskDependencyEntityServer.server.js.map +1 -0
  69. package/dist/custom/MJTaskEntityServer.server.d.ts +148 -0
  70. package/dist/custom/MJTaskEntityServer.server.d.ts.map +1 -0
  71. package/dist/custom/MJTaskEntityServer.server.js +413 -0
  72. package/dist/custom/MJTaskEntityServer.server.js.map +1 -0
  73. package/dist/custom/query-extraction/childRowWriter.d.ts +2 -2
  74. package/dist/custom/query-extraction/childRowWriter.d.ts.map +1 -1
  75. package/dist/custom/query-extraction/childRowWriter.js +7 -2
  76. package/dist/custom/query-extraction/childRowWriter.js.map +1 -1
  77. package/dist/custom/query-extraction/describeFacts.d.ts +2 -0
  78. package/dist/custom/query-extraction/describeFacts.d.ts.map +1 -1
  79. package/dist/custom/query-extraction/describeFacts.js +17 -10
  80. package/dist/custom/query-extraction/describeFacts.js.map +1 -1
  81. package/dist/custom/query-extraction/descriptionPass.d.ts.map +1 -1
  82. package/dist/custom/query-extraction/descriptionPass.js +4 -1
  83. package/dist/custom/query-extraction/descriptionPass.js.map +1 -1
  84. package/dist/custom/query-extraction/extractQuery.js +5 -3
  85. package/dist/custom/query-extraction/extractQuery.js.map +1 -1
  86. package/dist/custom/query-extraction/extractionTypes.d.ts +5 -0
  87. package/dist/custom/query-extraction/extractionTypes.d.ts.map +1 -1
  88. package/dist/custom/sessionConfigGuard.d.ts +7 -0
  89. package/dist/custom/sessionConfigGuard.d.ts.map +1 -1
  90. package/dist/custom/sessionConfigGuard.js +13 -1
  91. package/dist/custom/sessionConfigGuard.js.map +1 -1
  92. package/dist/index.d.ts +12 -0
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +12 -0
  95. package/dist/index.js.map +1 -1
  96. package/package.json +30 -30
@@ -0,0 +1,197 @@
1
+ import { AuthorizationInfo, EntityDeleteOptions, IMetadataProvider, UserInfo, ValidationErrorInfo, ValidationResult } from '@memberjunction/core';
2
+ import { MJGraphEdgeEntity, MJGraphEdgeTypeEntity } from '@memberjunction/core-entities';
3
+ /** Maximum character length permitted for `SourceRecordID` and `TargetRecordID`. */
4
+ export declare const MAX_GRAPH_EDGE_RECORD_ID_LENGTH = 400;
5
+ /** Named authorization required for every approval decision on `MJ: Graph Edges` (see {@link EvaluateGraphEdgeApproval}). */
6
+ export declare const GRAPH_APPROVE_EDGES_AUTHORIZATION = "Graph: Approve Edges";
7
+ /**
8
+ * Input snapshot of a `MJ: Graph Edges` row evaluated by {@link ValidateGraphEdgeInvariants}.
9
+ */
10
+ export interface GraphEdgeValidationInput {
11
+ readonly GraphID: string | null | undefined;
12
+ readonly EdgeTypeID: string | null | undefined;
13
+ readonly SourceEntityID: string | null | undefined;
14
+ readonly SourceRecordID: string | null | undefined;
15
+ readonly TargetEntityID: string | null | undefined;
16
+ readonly TargetRecordID: string | null | undefined;
17
+ }
18
+ /**
19
+ * Normalized endpoints for an undirected edge (lower `<entityID>|<recordID>` node key first).
20
+ */
21
+ export interface CanonicalGraphEdgeEndpoints {
22
+ readonly SourceEntityID: string;
23
+ readonly SourceRecordID: string;
24
+ readonly TargetEntityID: string;
25
+ readonly TargetRecordID: string;
26
+ readonly Swapped: boolean;
27
+ }
28
+ /**
29
+ * Canonicalize endpoints for an undirected edge (`IsDirected === false`) so the lower
30
+ * `<entityID>|<recordID>` key always occupies the `Source*` columns.
31
+ */
32
+ export declare function CanonicalizeUndirectedEdgeEndpoints(sourceEntityID: string, sourceRecordID: string, targetEntityID: string, targetRecordID: string): CanonicalGraphEdgeEndpoints;
33
+ /**
34
+ * Pure invariant check for a `MJ: Graph Edges` record (Phase G1.3):
35
+ * 1. No self-loop (`SourceEntityID === TargetEntityID` and `SourceRecordID === TargetRecordID`).
36
+ * 2. `SourceRecordID` and `TargetRecordID` are non-empty and at most 400 characters.
37
+ * 3. `EdgeTypeID` resolves to an edge type with `AllowStored === true` (refuses provider-only types)
38
+ * that belongs to the edge's `GraphID` or is global (`GraphID === null`).
39
+ * 4. `SourceEntityID` and `TargetEntityID` satisfy `GraphEngine.ValidateEdgeEndpoint` constraints.
40
+ *
41
+ * Who may create an edge that starts `Approved` is not an invariant of the row: it is the approval
42
+ * gate's decision ({@link EvaluateGraphEdgeApproval}), and it applies to every `Origin`.
43
+ */
44
+ export declare function ValidateGraphEdgeInvariants(input: GraphEdgeValidationInput, edgeType: Pick<MJGraphEdgeTypeEntity, 'ID' | 'Name' | 'GraphID' | 'IsDirected' | 'AllowStored'> | undefined, validateEndpoint?: (edgeTypeId: string, side: 'Source' | 'Target', entityId: string) => boolean): ValidationErrorInfo[];
45
+ /**
46
+ * Inputs to {@link EvaluateGraphEdgeApproval}: what is being saved, by whom, and the authorizations
47
+ * the caller's provider holds.
48
+ */
49
+ export interface GraphEdgeApprovalInput {
50
+ /** `true` for an update of an existing row, `false` for a create. */
51
+ readonly IsSaved: boolean;
52
+ /** The `Origin` being saved. */
53
+ readonly Origin: MJGraphEdgeEntity['Origin'] | null | undefined;
54
+ /** The stored `Status` before this save (the field's `OldValue`); ignored for a create. */
55
+ readonly PreviousStatus: MJGraphEdgeEntity['Status'] | null | undefined;
56
+ /** The `Status` being saved. */
57
+ readonly NextStatus: MJGraphEdgeEntity['Status'] | null | undefined;
58
+ /**
59
+ * `true` when an update changes what the edge connects or means: `GraphID`, `EdgeTypeID`, or any
60
+ * `Source*` / `Target*` column. Re-pointing an approved edge approves a different edge.
61
+ */
62
+ readonly IdentityChanged: boolean;
63
+ /**
64
+ * `true` when an update changes what the edge says: `Description`, `Weight`, `Origin`, `Attributes`
65
+ * or `Confidence`. Rewriting an approved edge's content approves content nobody reviewed.
66
+ */
67
+ readonly ContentChanged: boolean;
68
+ readonly User: UserInfo | undefined;
69
+ readonly Authorizations: AuthorizationInfo[] | undefined;
70
+ /**
71
+ * `true` when the save runs inside the Content Pipeline's {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION}
72
+ * server operation scope for this caller ({@link IsInGraphPipelineApprovalScope}).
73
+ */
74
+ readonly InPipelineApprovalScope: boolean;
75
+ }
76
+ /**
77
+ * Result of {@link EvaluateGraphEdgeApproval}.
78
+ */
79
+ export interface GraphEdgeApprovalVerdict {
80
+ readonly Error: ValidationErrorInfo | null;
81
+ /** `true` when the save is an approval decision that passed, so the reviewer is stamped. */
82
+ readonly ShouldStampReview: boolean;
83
+ }
84
+ /**
85
+ * True when saving these values is an approval decision that `Graph: Approve Edges` must authorize:
86
+ * - creating an edge that does not start out `Proposed` or `Rejected`, whatever its `Origin`. A null `Status` counts:
87
+ * `spCreateGraphEdge` stores the column default, `Approved`;
88
+ * - changing `Status` to `Approved` or `Rejected`, or away from `Approved` or `Rejected` (a review decision, or undoing one);
89
+ * - changing what an `Approved` edge connects (`IdentityChanged`) or says (`ContentChanged`).
90
+ */
91
+ export declare function GraphEdgeSaveNeedsApproval(input: GraphEdgeApprovalInput): boolean;
92
+ /**
93
+ * True when this save is the Content Pipeline creating an `Inferred` edge its content source's
94
+ * `GraphOverlay` policy approves: a create, `Origin = 'Inferred'`, `Status = 'Approved'`, inside the
95
+ * {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION} scope. Nothing else (a `Declared` edge, a status
96
+ * change, a re-pointed or edited edge) is covered by the pipeline's policy.
97
+ */
98
+ export declare function IsPipelinePolicyApprovedCreate(input: GraphEdgeApprovalInput): boolean;
99
+ /**
100
+ * Pure fail-closed gate for approval decisions on `MJ: Graph Edges` (see {@link GraphEdgeSaveNeedsApproval}).
101
+ *
102
+ * The caller must hold `Graph: Approve Edges` (or an ancestor) through `EvaluateAuthorizationChecks`,
103
+ * MJ's role-based evaluation, whatever the edge's `Origin`. There is no bypass for any user type: an
104
+ * authorization that is not seeded, an empty authorization list, or a missing caller all deny,
105
+ * because each of them means nobody has been granted the right.
106
+ *
107
+ * The one exception is {@link IsPipelinePolicyApprovedCreate}. The Content Pipeline `Graph` stage
108
+ * (`EntityGraphOverlayStore.UpsertEdges`) saves as the run's user: the scheduler's user, whoever ran
109
+ * the Record Process on demand, or whoever uploaded the document, most of whom hold no
110
+ * `Graph: Approve Edges`. Its `Approved` status is not that user's decision but the content source's
111
+ * configured `GraphOverlay.ConceptTaxonomyMode`, so tying it to the run user would break `auto-grow`
112
+ * for every run but a developer's. The stage therefore saves inside a server operation scope instead,
113
+ * which no API caller can enter (see {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION}). Such an edge is
114
+ * not stamped as reviewed: no person reviewed it.
115
+ */
116
+ export declare function EvaluateGraphEdgeApproval(input: GraphEdgeApprovalInput): GraphEdgeApprovalVerdict;
117
+ /**
118
+ * Why `user` may not exercise `Graph: Approve Edges`, or `null` when it may. Fail closed: a missing
119
+ * caller, an unseeded authorization and an empty authorization list all deny.
120
+ */
121
+ export declare function ApproveEdgesDenialReason(user: UserInfo | undefined, authorizations: AuthorizationInfo[] | undefined): string | null;
122
+ /**
123
+ * The refusal for deleting an edge whose stored `Status` is `storedStatus`, or `null` when allowed.
124
+ * Removing an `Approved` edge undoes a review decision, so it needs `Graph: Approve Edges`; a
125
+ * `Proposed` or `Rejected` edge may be deleted by anyone the entity permissions allow.
126
+ */
127
+ export declare function GraphEdgeDeleteRefusal(storedStatus: MJGraphEdgeEntity['Status'] | null | undefined, user: UserInfo | undefined, authorizations: AuthorizationInfo[] | undefined): string | null;
128
+ /** `Attributes` keys the server writes when an edge is approved or rejected; a caller never sets them. */
129
+ export declare const GRAPH_EDGE_REVIEW_ATTRIBUTE_KEYS: readonly string[];
130
+ /**
131
+ * The first review-stamp key ({@link GRAPH_EDGE_REVIEW_ATTRIBUTE_KEYS}) whose value differs between
132
+ * the stored and the new `Attributes` JSON, or `null`. A save that is not itself a stamped review
133
+ * decision may not add, change or remove one: the stamp would otherwise be forgeable.
134
+ */
135
+ export declare function FindReviewStampChange(storedAttributes: string | null | undefined, nextAttributes: string | null | undefined): string | null;
136
+ /**
137
+ * True while the current async call chain is inside a {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION}
138
+ * server operation scope bound to `user` (`ServerOperationScopeManager.IsOperationActive`). Frames
139
+ * outside the innermost client CRUD boundary are masked, so a GraphQL, REST or transaction-group save
140
+ * never sees one.
141
+ */
142
+ export declare function IsInGraphPipelineApprovalScope(user: UserInfo | undefined): boolean;
143
+ /**
144
+ * Batched `RunViews` (`ResultType: 'count_only'`) existence check for `Source` and `Target` endpoint
145
+ * records, run as `user` so an endpoint the caller cannot read (entity permission or row-level
146
+ * security) is refused exactly like one that does not exist.
147
+ *
148
+ * Fails closed: an endpoint entity missing from metadata, a failed read, or an exception is a
149
+ * validation error, never a silent pass.
150
+ */
151
+ export declare function CheckGraphEdgeEndpointsExist(input: {
152
+ readonly SourceEntityID: string | null | undefined;
153
+ readonly SourceRecordID: string | null | undefined;
154
+ readonly TargetEntityID: string | null | undefined;
155
+ readonly TargetRecordID: string | null | undefined;
156
+ }, provider: IMetadataProvider, user: UserInfo | undefined): Promise<ValidationErrorInfo[]>;
157
+ /**
158
+ * Server-side `MJ: Graph Edges` entity enforcing Phase G1.3 write-time invariants:
159
+ * - No self-loops
160
+ * - Record ID length <= 400 chars
161
+ * - Refuses an `EdgeTypeID` that is unknown, provider-only (`AllowStored = false`) or scoped to another graph
162
+ * - Enforces `MJ: Graph Edge Type Endpoints` source/target entity constraints via `GraphEngine.Instance.ValidateEdgeEndpoint`
163
+ * - Canonicalizes undirected (`IsDirected = false`) edge endpoint orientation (lower `<entityID>|<recordID>` key first)
164
+ * - Requires `Graph: Approve Edges` for every approval decision, whatever the `Origin`, including creating
165
+ * an edge that starts `Approved` and editing or deleting an `Approved` edge ({@link EvaluateGraphEdgeApproval},
166
+ * {@link GraphEdgeDeleteRefusal}), and stamps `ReviewedByUserID` / `ReviewedAt` into `Attributes`; the
167
+ * Content Pipeline's policy-approved `Inferred` edges are the one exception ({@link IsPipelinePolicyApprovedCreate})
168
+ * - Refuses any other save that sets, changes or removes that review stamp ({@link FindReviewStampChange})
169
+ * - Verifies `Source` and `Target` endpoint records exist, as the caller, via batched `RunViews` (`count_only`)
170
+ *
171
+ * Every check fails closed: graph metadata that cannot be loaded is a validation error, not a pass.
172
+ */
173
+ export declare class MJGraphEdgeEntityServer extends MJGraphEdgeEntity {
174
+ get DefaultSkipAsyncValidation(): boolean;
175
+ ValidateAsync(): Promise<ValidationResult>;
176
+ /**
177
+ * Makes sure `GraphEngine` has its edge types and endpoint constraints. `Config` is a no-op once
178
+ * loaded; on a server `BaseEngine` loads it as the system user, so the shared cache never takes
179
+ * this caller's scope. A failure is returned as an error: validating against an empty cache
180
+ * would skip the edge-type checks.
181
+ */
182
+ private ensureGraphEngine;
183
+ private canonicalizeUndirectedEndpoints;
184
+ /**
185
+ * Refuses deleting an `Approved` edge without `Graph: Approve Edges` ({@link GraphEdgeDeleteRefusal}).
186
+ * The delete path loads the stored row first, so `Status` is the stored value.
187
+ */
188
+ Delete(options?: EntityDeleteOptions): Promise<boolean>;
189
+ /** The stored `Attributes` before this save; `null` for a create. */
190
+ private storedAttributes;
191
+ private previousStatus;
192
+ private stampReview;
193
+ private endpointsDirty;
194
+ private fail;
195
+ private resolveEdgeType;
196
+ }
197
+ //# sourceMappingURL=MJGraphEdgeEntityServer.server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MJGraphEdgeEntityServer.server.d.ts","sourceRoot":"","sources":["../../src/custom/MJGraphEdgeEntityServer.server.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,459 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseEntity, BaseEntityResult, RunView, ServerOperationScopeManager, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/core';
8
+ import { EscapeSQLString, RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
+ import { EvaluateAuthorizationChecks, FormatGraphNodeKey, GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION, GraphEngine, IsGraphDataProvider, MJGraphEdgeEntity, } from '@memberjunction/core-entities';
10
+ /** Maximum character length permitted for `SourceRecordID` and `TargetRecordID`. */
11
+ export const MAX_GRAPH_EDGE_RECORD_ID_LENGTH = 400;
12
+ /** Named authorization required for every approval decision on `MJ: Graph Edges` (see {@link EvaluateGraphEdgeApproval}). */
13
+ export const GRAPH_APPROVE_EDGES_AUTHORIZATION = 'Graph: Approve Edges';
14
+ const GRAPH_EDGES_ENTITY_NAME = 'MJ: Graph Edges';
15
+ /**
16
+ * Canonicalize endpoints for an undirected edge (`IsDirected === false`) so the lower
17
+ * `<entityID>|<recordID>` key always occupies the `Source*` columns.
18
+ */
19
+ export function CanonicalizeUndirectedEdgeEndpoints(sourceEntityID, sourceRecordID, targetEntityID, targetRecordID) {
20
+ const sourceKey = FormatGraphNodeKey(sourceEntityID, sourceRecordID);
21
+ const targetKey = FormatGraphNodeKey(targetEntityID, targetRecordID);
22
+ if (sourceKey > targetKey) {
23
+ return {
24
+ SourceEntityID: targetEntityID,
25
+ SourceRecordID: targetRecordID,
26
+ TargetEntityID: sourceEntityID,
27
+ TargetRecordID: sourceRecordID,
28
+ Swapped: true,
29
+ };
30
+ }
31
+ return {
32
+ SourceEntityID: sourceEntityID,
33
+ SourceRecordID: sourceRecordID,
34
+ TargetEntityID: targetEntityID,
35
+ TargetRecordID: targetRecordID,
36
+ Swapped: false,
37
+ };
38
+ }
39
+ /**
40
+ * Pure invariant check for a `MJ: Graph Edges` record (Phase G1.3):
41
+ * 1. No self-loop (`SourceEntityID === TargetEntityID` and `SourceRecordID === TargetRecordID`).
42
+ * 2. `SourceRecordID` and `TargetRecordID` are non-empty and at most 400 characters.
43
+ * 3. `EdgeTypeID` resolves to an edge type with `AllowStored === true` (refuses provider-only types)
44
+ * that belongs to the edge's `GraphID` or is global (`GraphID === null`).
45
+ * 4. `SourceEntityID` and `TargetEntityID` satisfy `GraphEngine.ValidateEdgeEndpoint` constraints.
46
+ *
47
+ * Who may create an edge that starts `Approved` is not an invariant of the row: it is the approval
48
+ * gate's decision ({@link EvaluateGraphEdgeApproval}), and it applies to every `Origin`.
49
+ */
50
+ export function ValidateGraphEdgeInvariants(input, edgeType, validateEndpoint = (edgeTypeId, side, entityId) => GraphEngine.Instance.ValidateEdgeEndpoint(edgeTypeId, side, entityId)) {
51
+ const errors = [];
52
+ const srcRec = input.SourceRecordID ?? '';
53
+ const tgtRec = input.TargetRecordID ?? '';
54
+ if (srcRec.trim().length === 0) {
55
+ errors.push(new ValidationErrorInfo('SourceRecordID', 'SourceRecordID cannot be empty.', input.SourceRecordID, ValidationErrorType.Failure));
56
+ }
57
+ else if (srcRec.length > MAX_GRAPH_EDGE_RECORD_ID_LENGTH) {
58
+ errors.push(new ValidationErrorInfo('SourceRecordID', `SourceRecordID cannot exceed ${MAX_GRAPH_EDGE_RECORD_ID_LENGTH} characters (got ${srcRec.length}).`, input.SourceRecordID, ValidationErrorType.Failure));
59
+ }
60
+ if (tgtRec.trim().length === 0) {
61
+ errors.push(new ValidationErrorInfo('TargetRecordID', 'TargetRecordID cannot be empty.', input.TargetRecordID, ValidationErrorType.Failure));
62
+ }
63
+ else if (tgtRec.length > MAX_GRAPH_EDGE_RECORD_ID_LENGTH) {
64
+ errors.push(new ValidationErrorInfo('TargetRecordID', `TargetRecordID cannot exceed ${MAX_GRAPH_EDGE_RECORD_ID_LENGTH} characters (got ${tgtRec.length}).`, input.TargetRecordID, ValidationErrorType.Failure));
65
+ }
66
+ if (input.SourceEntityID &&
67
+ input.TargetEntityID &&
68
+ srcRec.trim().length > 0 &&
69
+ UUIDsEqual(input.SourceEntityID, input.TargetEntityID) &&
70
+ srcRec.trim().toLowerCase() === tgtRec.trim().toLowerCase()) {
71
+ errors.push(new ValidationErrorInfo('SourceRecordID', 'Graph edge cannot connect a node to itself (self-loop is not allowed).', input.SourceRecordID, ValidationErrorType.Failure));
72
+ }
73
+ if (edgeType) {
74
+ if (!edgeType.AllowStored) {
75
+ errors.push(new ValidationErrorInfo('EdgeTypeID', `Edge type "${edgeType.Name}" is provider-only (AllowStored = false) and cannot be persisted in MJ: Graph Edges.`, input.EdgeTypeID, ValidationErrorType.Failure));
76
+ }
77
+ if (edgeType.GraphID != null && input.GraphID != null && !UUIDsEqual(edgeType.GraphID, input.GraphID)) {
78
+ errors.push(new ValidationErrorInfo('EdgeTypeID', `Edge type "${edgeType.Name}" is scoped to a different graph and cannot be used in graph "${input.GraphID}".`, input.EdgeTypeID, ValidationErrorType.Failure));
79
+ }
80
+ }
81
+ if (input.EdgeTypeID && input.SourceEntityID) {
82
+ if (!validateEndpoint(input.EdgeTypeID, 'Source', input.SourceEntityID)) {
83
+ errors.push(new ValidationErrorInfo('SourceEntityID', `Entity "${input.SourceEntityID}" is not permitted as a Source endpoint for edge type "${edgeType?.Name ?? input.EdgeTypeID}".`, input.SourceEntityID, ValidationErrorType.Failure));
84
+ }
85
+ }
86
+ if (input.EdgeTypeID && input.TargetEntityID) {
87
+ if (!validateEndpoint(input.EdgeTypeID, 'Target', input.TargetEntityID)) {
88
+ errors.push(new ValidationErrorInfo('TargetEntityID', `Entity "${input.TargetEntityID}" is not permitted as a Target endpoint for edge type "${edgeType?.Name ?? input.EdgeTypeID}".`, input.TargetEntityID, ValidationErrorType.Failure));
89
+ }
90
+ }
91
+ return errors;
92
+ }
93
+ /**
94
+ * True when saving these values is an approval decision that `Graph: Approve Edges` must authorize:
95
+ * - creating an edge that does not start out `Proposed` or `Rejected`, whatever its `Origin`. A null `Status` counts:
96
+ * `spCreateGraphEdge` stores the column default, `Approved`;
97
+ * - changing `Status` to `Approved` or `Rejected`, or away from `Approved` or `Rejected` (a review decision, or undoing one);
98
+ * - changing what an `Approved` edge connects (`IdentityChanged`) or says (`ContentChanged`).
99
+ */
100
+ export function GraphEdgeSaveNeedsApproval(input) {
101
+ if (!input.IsSaved) {
102
+ return input.NextStatus !== 'Proposed' && input.NextStatus !== 'Rejected';
103
+ }
104
+ const statusChanged = input.PreviousStatus !== input.NextStatus;
105
+ const reviewed = input.PreviousStatus === 'Approved' || input.PreviousStatus === 'Rejected';
106
+ if (statusChanged && (input.NextStatus === 'Approved' || input.NextStatus === 'Rejected' || reviewed)) {
107
+ return true;
108
+ }
109
+ return input.NextStatus === 'Approved' && (input.IdentityChanged || input.ContentChanged);
110
+ }
111
+ /**
112
+ * True when this save is the Content Pipeline creating an `Inferred` edge its content source's
113
+ * `GraphOverlay` policy approves: a create, `Origin = 'Inferred'`, `Status = 'Approved'`, inside the
114
+ * {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION} scope. Nothing else (a `Declared` edge, a status
115
+ * change, a re-pointed or edited edge) is covered by the pipeline's policy.
116
+ */
117
+ export function IsPipelinePolicyApprovedCreate(input) {
118
+ return input.InPipelineApprovalScope && !input.IsSaved && input.Origin === 'Inferred' && input.NextStatus === 'Approved';
119
+ }
120
+ /**
121
+ * Pure fail-closed gate for approval decisions on `MJ: Graph Edges` (see {@link GraphEdgeSaveNeedsApproval}).
122
+ *
123
+ * The caller must hold `Graph: Approve Edges` (or an ancestor) through `EvaluateAuthorizationChecks`,
124
+ * MJ's role-based evaluation, whatever the edge's `Origin`. There is no bypass for any user type: an
125
+ * authorization that is not seeded, an empty authorization list, or a missing caller all deny,
126
+ * because each of them means nobody has been granted the right.
127
+ *
128
+ * The one exception is {@link IsPipelinePolicyApprovedCreate}. The Content Pipeline `Graph` stage
129
+ * (`EntityGraphOverlayStore.UpsertEdges`) saves as the run's user: the scheduler's user, whoever ran
130
+ * the Record Process on demand, or whoever uploaded the document, most of whom hold no
131
+ * `Graph: Approve Edges`. Its `Approved` status is not that user's decision but the content source's
132
+ * configured `GraphOverlay.ConceptTaxonomyMode`, so tying it to the run user would break `auto-grow`
133
+ * for every run but a developer's. The stage therefore saves inside a server operation scope instead,
134
+ * which no API caller can enter (see {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION}). Such an edge is
135
+ * not stamped as reviewed: no person reviewed it.
136
+ */
137
+ export function EvaluateGraphEdgeApproval(input) {
138
+ if (!GraphEdgeSaveNeedsApproval(input) || IsPipelinePolicyApprovedCreate(input)) {
139
+ return { Error: null, ShouldStampReview: false };
140
+ }
141
+ const denial = ApproveEdgesDenialReason(input.User, input.Authorizations);
142
+ if (denial) {
143
+ return { Error: approvalError(denial, input.NextStatus), ShouldStampReview: false };
144
+ }
145
+ return { Error: null, ShouldStampReview: true };
146
+ }
147
+ /**
148
+ * Why `user` may not exercise `Graph: Approve Edges`, or `null` when it may. Fail closed: a missing
149
+ * caller, an unseeded authorization and an empty authorization list all deny.
150
+ */
151
+ export function ApproveEdgesDenialReason(user, authorizations) {
152
+ if (!user) {
153
+ return `requires an authenticated caller with "${GRAPH_APPROVE_EDGES_AUTHORIZATION}"`;
154
+ }
155
+ const [check] = EvaluateAuthorizationChecks([GRAPH_APPROVE_EDGES_AUTHORIZATION], user, authorizations ?? []);
156
+ if (!check || check.Unknown) {
157
+ return `requires "${GRAPH_APPROVE_EDGES_AUTHORIZATION}", which is not configured in this system`;
158
+ }
159
+ if (!check.Allowed) {
160
+ return `requires "${GRAPH_APPROVE_EDGES_AUTHORIZATION}", which the caller does not hold`;
161
+ }
162
+ return null;
163
+ }
164
+ /**
165
+ * The refusal for deleting an edge whose stored `Status` is `storedStatus`, or `null` when allowed.
166
+ * Removing an `Approved` edge undoes a review decision, so it needs `Graph: Approve Edges`; a
167
+ * `Proposed` or `Rejected` edge may be deleted by anyone the entity permissions allow.
168
+ */
169
+ export function GraphEdgeDeleteRefusal(storedStatus, user, authorizations) {
170
+ if (storedStatus !== 'Approved') {
171
+ return null;
172
+ }
173
+ const denial = ApproveEdgesDenialReason(user, authorizations);
174
+ return denial ? `Deleting an approved graph edge is a review decision and ${denial}.` : null;
175
+ }
176
+ /** `Attributes` keys the server writes when an edge is approved or rejected; a caller never sets them. */
177
+ export const GRAPH_EDGE_REVIEW_ATTRIBUTE_KEYS = ['ReviewedByUserID', 'ReviewedAt'];
178
+ /**
179
+ * The first review-stamp key ({@link GRAPH_EDGE_REVIEW_ATTRIBUTE_KEYS}) whose value differs between
180
+ * the stored and the new `Attributes` JSON, or `null`. A save that is not itself a stamped review
181
+ * decision may not add, change or remove one: the stamp would otherwise be forgeable.
182
+ */
183
+ export function FindReviewStampChange(storedAttributes, nextAttributes) {
184
+ const stored = parseAttributeObject(storedAttributes);
185
+ const next = parseAttributeObject(nextAttributes);
186
+ for (const key of GRAPH_EDGE_REVIEW_ATTRIBUTE_KEYS) {
187
+ if (JSON.stringify(stored[key]) !== JSON.stringify(next[key])) {
188
+ return key;
189
+ }
190
+ }
191
+ return null;
192
+ }
193
+ function parseAttributeObject(raw) {
194
+ if (!raw || raw.trim().length === 0) {
195
+ return {};
196
+ }
197
+ try {
198
+ const parsed = JSON.parse(raw);
199
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? { ...parsed } : {};
200
+ }
201
+ catch {
202
+ return {};
203
+ }
204
+ }
205
+ /**
206
+ * True while the current async call chain is inside a {@link GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION}
207
+ * server operation scope bound to `user` (`ServerOperationScopeManager.IsOperationActive`). Frames
208
+ * outside the innermost client CRUD boundary are masked, so a GraphQL, REST or transaction-group save
209
+ * never sees one.
210
+ */
211
+ export function IsInGraphPipelineApprovalScope(user) {
212
+ if (!user) {
213
+ return false;
214
+ }
215
+ return ServerOperationScopeManager.Instance.IsOperationActive([GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION], GRAPH_EDGES_ENTITY_NAME, user);
216
+ }
217
+ function approvalError(reason, nextStatus) {
218
+ return new ValidationErrorInfo('Status', `Saving this graph edge as "${nextStatus ?? ''}" is an approval decision and ${reason}. ` +
219
+ 'Save it as "Proposed" for a reviewer instead.', nextStatus, ValidationErrorType.Failure);
220
+ }
221
+ /**
222
+ * Batched `RunViews` (`ResultType: 'count_only'`) existence check for `Source` and `Target` endpoint
223
+ * records, run as `user` so an endpoint the caller cannot read (entity permission or row-level
224
+ * security) is refused exactly like one that does not exist.
225
+ *
226
+ * Fails closed: an endpoint entity missing from metadata, a failed read, or an exception is a
227
+ * validation error, never a silent pass.
228
+ */
229
+ export async function CheckGraphEdgeEndpointsExist(input, provider, user) {
230
+ if (!user) {
231
+ return [endpointError('SourceRecordID', 'Graph edge endpoints can only be checked for an authenticated caller.', input.SourceRecordID)];
232
+ }
233
+ const errors = [];
234
+ const checks = [];
235
+ const addCheck = (field, entityId, recordId) => {
236
+ const trimmedId = recordId?.trim();
237
+ if (!entityId || !trimmedId) {
238
+ return; // emptiness is reported by ValidateGraphEdgeInvariants
239
+ }
240
+ const entityInfo = provider.EntityByID(entityId);
241
+ const pkName = entityInfo?.FirstPrimaryKey?.Name; // first-pk-ok: Graph edge endpoint record existence check uses FirstPrimaryKey
242
+ if (!entityInfo || !pkName) {
243
+ errors.push(endpointError(field, `Endpoint entity "${entityId}" is not a known entity.`, entityId));
244
+ return;
245
+ }
246
+ checks.push({
247
+ Field: field,
248
+ EntityName: entityInfo.Name,
249
+ RecordID: trimmedId,
250
+ Param: {
251
+ EntityName: entityInfo.Name,
252
+ ExtraFilter: `[${pkName}] = '${EscapeSQLString(trimmedId)}'`,
253
+ ResultType: 'count_only',
254
+ },
255
+ });
256
+ };
257
+ addCheck('SourceRecordID', input.SourceEntityID, input.SourceRecordID);
258
+ addCheck('TargetRecordID', input.TargetEntityID, input.TargetRecordID);
259
+ if (checks.length === 0) {
260
+ return errors;
261
+ }
262
+ try {
263
+ const results = await RunView.FromMetadataProvider(provider).RunViews(checks.map((c) => c.Param), user);
264
+ for (let i = 0; i < checks.length; i++) {
265
+ const check = checks[i];
266
+ const res = results[i];
267
+ if (!res?.Success) {
268
+ errors.push(endpointError(check.Field, `Could not verify endpoint record "${check.RecordID}" in entity "${check.EntityName}": ${res?.ErrorMessage ?? 'no result'}.`, check.RecordID));
269
+ }
270
+ else if (res.TotalRowCount === 0) {
271
+ errors.push(endpointError(check.Field, `Endpoint record "${check.RecordID}" in entity "${check.EntityName}" does not exist or is not readable by the caller.`, check.RecordID));
272
+ }
273
+ }
274
+ }
275
+ catch (err) {
276
+ const msg = err instanceof Error ? err.message : String(err);
277
+ errors.push(endpointError('SourceRecordID', `Could not verify graph edge endpoints: ${msg}`, input.SourceRecordID));
278
+ }
279
+ return errors;
280
+ }
281
+ function endpointError(field, message, value) {
282
+ return new ValidationErrorInfo(field, message, value, ValidationErrorType.Failure);
283
+ }
284
+ /** Columns whose change on an `Approved` edge re-approves a different edge. */
285
+ const IDENTITY_FIELDS = ['GraphID', 'EdgeTypeID', 'SourceEntityID', 'SourceRecordID', 'TargetEntityID', 'TargetRecordID'];
286
+ /** Columns whose change on an `Approved` edge re-approves different content. */
287
+ const CONTENT_FIELDS = ['Description', 'Weight', 'Origin', 'Attributes', 'Confidence'];
288
+ /**
289
+ * Server-side `MJ: Graph Edges` entity enforcing Phase G1.3 write-time invariants:
290
+ * - No self-loops
291
+ * - Record ID length <= 400 chars
292
+ * - Refuses an `EdgeTypeID` that is unknown, provider-only (`AllowStored = false`) or scoped to another graph
293
+ * - Enforces `MJ: Graph Edge Type Endpoints` source/target entity constraints via `GraphEngine.Instance.ValidateEdgeEndpoint`
294
+ * - Canonicalizes undirected (`IsDirected = false`) edge endpoint orientation (lower `<entityID>|<recordID>` key first)
295
+ * - Requires `Graph: Approve Edges` for every approval decision, whatever the `Origin`, including creating
296
+ * an edge that starts `Approved` and editing or deleting an `Approved` edge ({@link EvaluateGraphEdgeApproval},
297
+ * {@link GraphEdgeDeleteRefusal}), and stamps `ReviewedByUserID` / `ReviewedAt` into `Attributes`; the
298
+ * Content Pipeline's policy-approved `Inferred` edges are the one exception ({@link IsPipelinePolicyApprovedCreate})
299
+ * - Refuses any other save that sets, changes or removes that review stamp ({@link FindReviewStampChange})
300
+ * - Verifies `Source` and `Target` endpoint records exist, as the caller, via batched `RunViews` (`count_only`)
301
+ *
302
+ * Every check fails closed: graph metadata that cannot be loaded is a validation error, not a pass.
303
+ */
304
+ let MJGraphEdgeEntityServer = class MJGraphEdgeEntityServer extends MJGraphEdgeEntity {
305
+ get DefaultSkipAsyncValidation() {
306
+ return false;
307
+ }
308
+ async ValidateAsync() {
309
+ const result = await super.ValidateAsync();
310
+ if (!result.Success) {
311
+ return result;
312
+ }
313
+ const provider = this.ProviderToUse;
314
+ if (!IsGraphDataProvider(provider)) {
315
+ return this.fail(result, new ValidationErrorInfo('EdgeTypeID', 'Graph edges can only be validated against a metadata provider.', this.EdgeTypeID, ValidationErrorType.Failure));
316
+ }
317
+ const engineError = await this.ensureGraphEngine(provider);
318
+ if (engineError) {
319
+ return this.fail(result, engineError);
320
+ }
321
+ const edgeType = this.resolveEdgeType(this.EdgeTypeID);
322
+ this.canonicalizeUndirectedEndpoints(edgeType);
323
+ const errors = ValidateGraphEdgeInvariants({
324
+ GraphID: this.GraphID,
325
+ EdgeTypeID: this.EdgeTypeID,
326
+ SourceEntityID: this.SourceEntityID,
327
+ SourceRecordID: this.SourceRecordID,
328
+ TargetEntityID: this.TargetEntityID,
329
+ TargetRecordID: this.TargetRecordID,
330
+ }, edgeType);
331
+ if (this.EdgeTypeID && !edgeType) {
332
+ errors.push(new ValidationErrorInfo('EdgeTypeID', `Edge type "${this.EdgeTypeID}" is not a known graph edge type.`, this.EdgeTypeID, ValidationErrorType.Failure));
333
+ }
334
+ const approval = EvaluateGraphEdgeApproval({
335
+ IsSaved: this.IsSaved,
336
+ Origin: this.Origin,
337
+ PreviousStatus: this.previousStatus(),
338
+ NextStatus: this.Status,
339
+ IdentityChanged: this.IsSaved && IDENTITY_FIELDS.some((f) => this.GetFieldByName(f)?.Dirty === true),
340
+ ContentChanged: this.IsSaved && CONTENT_FIELDS.some((f) => this.GetFieldByName(f)?.Dirty === true),
341
+ User: this.ContextCurrentUser,
342
+ Authorizations: provider.Authorizations,
343
+ InPipelineApprovalScope: IsInGraphPipelineApprovalScope(this.ContextCurrentUser),
344
+ });
345
+ if (approval.Error) {
346
+ errors.push(approval.Error);
347
+ }
348
+ else if (approval.ShouldStampReview && this.ContextCurrentUser?.ID) {
349
+ this.stampReview(this.ContextCurrentUser.ID);
350
+ }
351
+ else {
352
+ const forgedKey = FindReviewStampChange(this.storedAttributes(), this.Attributes);
353
+ if (forgedKey) {
354
+ errors.push(new ValidationErrorInfo('Attributes', `"${forgedKey}" in Attributes is recorded by the server when an edge is reviewed; it cannot be set, changed or removed.`, this.Attributes, ValidationErrorType.Failure));
355
+ }
356
+ }
357
+ if (errors.length === 0 && this.endpointsDirty()) {
358
+ errors.push(...(await CheckGraphEdgeEndpointsExist({
359
+ SourceEntityID: this.SourceEntityID,
360
+ SourceRecordID: this.SourceRecordID,
361
+ TargetEntityID: this.TargetEntityID,
362
+ TargetRecordID: this.TargetRecordID,
363
+ }, provider, this.ContextCurrentUser)));
364
+ }
365
+ if (errors.length > 0) {
366
+ result.Errors.push(...errors);
367
+ result.Success = false;
368
+ }
369
+ return result;
370
+ }
371
+ /**
372
+ * Makes sure `GraphEngine` has its edge types and endpoint constraints. `Config` is a no-op once
373
+ * loaded; on a server `BaseEngine` loads it as the system user, so the shared cache never takes
374
+ * this caller's scope. A failure is returned as an error: validating against an empty cache
375
+ * would skip the edge-type checks.
376
+ */
377
+ async ensureGraphEngine(provider) {
378
+ try {
379
+ await GraphEngine.Instance.Config(false, this.ContextCurrentUser, provider);
380
+ return GraphEngine.Instance.Loaded
381
+ ? null
382
+ : new ValidationErrorInfo('EdgeTypeID', 'Graph metadata could not be loaded to validate this edge.', this.EdgeTypeID, ValidationErrorType.Failure);
383
+ }
384
+ catch (err) {
385
+ const msg = err instanceof Error ? err.message : String(err);
386
+ return new ValidationErrorInfo('EdgeTypeID', `Graph metadata could not be loaded to validate this edge: ${msg}`, this.EdgeTypeID, ValidationErrorType.Failure);
387
+ }
388
+ }
389
+ canonicalizeUndirectedEndpoints(edgeType) {
390
+ if (!edgeType || edgeType.IsDirected || !this.SourceEntityID || !this.TargetEntityID || !this.SourceRecordID || !this.TargetRecordID) {
391
+ return;
392
+ }
393
+ const canonical = CanonicalizeUndirectedEdgeEndpoints(this.SourceEntityID, this.SourceRecordID, this.TargetEntityID, this.TargetRecordID);
394
+ if (canonical.Swapped) {
395
+ this.SourceEntityID = canonical.SourceEntityID;
396
+ this.SourceRecordID = canonical.SourceRecordID;
397
+ this.TargetEntityID = canonical.TargetEntityID;
398
+ this.TargetRecordID = canonical.TargetRecordID;
399
+ }
400
+ }
401
+ /**
402
+ * Refuses deleting an `Approved` edge without `Graph: Approve Edges` ({@link GraphEdgeDeleteRefusal}).
403
+ * The delete path loads the stored row first, so `Status` is the stored value.
404
+ */
405
+ async Delete(options) {
406
+ const provider = this.ProviderToUse;
407
+ const authorizations = IsGraphDataProvider(provider) ? provider.Authorizations : undefined;
408
+ const refusal = GraphEdgeDeleteRefusal(this.previousStatus() ?? this.Status, this.ContextCurrentUser, authorizations);
409
+ if (refusal) {
410
+ const result = new BaseEntityResult();
411
+ result.Success = false;
412
+ result.Type = 'delete';
413
+ result.Message = refusal;
414
+ result.StartedAt = new Date();
415
+ result.EndedAt = new Date();
416
+ this.RegisterResultHistoryEntry(result);
417
+ return false;
418
+ }
419
+ return super.Delete(options);
420
+ }
421
+ /** The stored `Attributes` before this save; `null` for a create. */
422
+ storedAttributes() {
423
+ if (!this.IsSaved) {
424
+ return null;
425
+ }
426
+ const oldValue = this.GetFieldByName('Attributes')?.OldValue;
427
+ return typeof oldValue === 'string' ? oldValue : null;
428
+ }
429
+ previousStatus() {
430
+ const oldValue = this.GetFieldByName('Status')?.OldValue;
431
+ return oldValue === 'Approved' || oldValue === 'Proposed' || oldValue === 'Rejected' ? oldValue : null;
432
+ }
433
+ stampReview(userId) {
434
+ const attrObj = parseAttributeObject(this.Attributes);
435
+ attrObj['ReviewedByUserID'] = userId;
436
+ attrObj['ReviewedAt'] = new Date().toISOString();
437
+ this.Attributes = JSON.stringify(attrObj);
438
+ }
439
+ endpointsDirty() {
440
+ return (!this.IsSaved ||
441
+ ['SourceEntityID', 'SourceRecordID', 'TargetEntityID', 'TargetRecordID'].some((f) => this.GetFieldByName(f)?.Dirty === true));
442
+ }
443
+ fail(result, error) {
444
+ result.Errors.push(error);
445
+ result.Success = false;
446
+ return result;
447
+ }
448
+ resolveEdgeType(edgeTypeId) {
449
+ if (!edgeTypeId) {
450
+ return undefined;
451
+ }
452
+ return GraphEngine.Instance.EdgeTypes.find((et) => UUIDsEqual(et.ID, edgeTypeId));
453
+ }
454
+ };
455
+ MJGraphEdgeEntityServer = __decorate([
456
+ RegisterClass(BaseEntity, 'MJ: Graph Edges')
457
+ ], MJGraphEdgeEntityServer);
458
+ export { MJGraphEdgeEntityServer };
459
+ //# sourceMappingURL=MJGraphEdgeEntityServer.server.js.map