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

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 (200) hide show
  1. package/dist/custom/AgentChannelConversationDriver.server.d.ts +87 -0
  2. package/dist/custom/AgentChannelConversationDriver.server.d.ts.map +1 -0
  3. package/dist/custom/AgentChannelConversationDriver.server.js +216 -0
  4. package/dist/custom/AgentChannelConversationDriver.server.js.map +1 -0
  5. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts +1 -0
  6. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts.map +1 -1
  7. package/dist/custom/AnchoredConversationReadSecurityHook.js +23 -10
  8. package/dist/custom/AnchoredConversationReadSecurityHook.js.map +1 -1
  9. package/dist/custom/ArtifactSecurityHookHelpers.d.ts +223 -0
  10. package/dist/custom/ArtifactSecurityHookHelpers.d.ts.map +1 -0
  11. package/dist/custom/ArtifactSecurityHookHelpers.js +1402 -0
  12. package/dist/custom/ArtifactSecurityHookHelpers.js.map +1 -0
  13. package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts +25 -0
  14. package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts.map +1 -0
  15. package/dist/custom/AudienceNamedPersonAgentRequestService.js +304 -0
  16. package/dist/custom/AudienceNamedPersonAgentRequestService.js.map +1 -0
  17. package/dist/custom/ConversationDetailWritePermissionProvider.d.ts +113 -0
  18. package/dist/custom/ConversationDetailWritePermissionProvider.d.ts.map +1 -0
  19. package/dist/custom/ConversationDetailWritePermissionProvider.js +200 -0
  20. package/dist/custom/ConversationDetailWritePermissionProvider.js.map +1 -0
  21. package/dist/custom/ConversationReadSecurityHook.d.ts +61 -0
  22. package/dist/custom/ConversationReadSecurityHook.d.ts.map +1 -0
  23. package/dist/custom/ConversationReadSecurityHook.js +587 -0
  24. package/dist/custom/ConversationReadSecurityHook.js.map +1 -0
  25. package/dist/custom/MJAIAgentEntityServer.server.d.ts +80 -34
  26. package/dist/custom/MJAIAgentEntityServer.server.d.ts.map +1 -1
  27. package/dist/custom/MJAIAgentEntityServer.server.js +383 -43
  28. package/dist/custom/MJAIAgentEntityServer.server.js.map +1 -1
  29. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts +23 -0
  30. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts.map +1 -0
  31. package/dist/custom/MJAIAgentPersonaEntityServer.server.js +93 -0
  32. package/dist/custom/MJAIAgentPersonaEntityServer.server.js.map +1 -0
  33. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts +24 -13
  34. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts.map +1 -1
  35. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js +167 -24
  36. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js.map +1 -1
  37. package/dist/custom/MJAIBridgeAgentIdentityEntityServer.server.js +2 -2
  38. package/dist/custom/MJAIBridgeAgentIdentityEntityServer.server.js.map +1 -1
  39. package/dist/custom/MJArtifactEntityServer.server.d.ts +38 -0
  40. package/dist/custom/MJArtifactEntityServer.server.d.ts.map +1 -0
  41. package/dist/custom/MJArtifactEntityServer.server.js +436 -0
  42. package/dist/custom/MJArtifactEntityServer.server.js.map +1 -0
  43. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.d.ts +32 -0
  44. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.d.ts.map +1 -0
  45. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.js +434 -0
  46. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.js.map +1 -0
  47. package/dist/custom/MJArtifactPermissionEntityServer.server.d.ts +18 -0
  48. package/dist/custom/MJArtifactPermissionEntityServer.server.d.ts.map +1 -0
  49. package/dist/custom/MJArtifactPermissionEntityServer.server.js +194 -0
  50. package/dist/custom/MJArtifactPermissionEntityServer.server.js.map +1 -0
  51. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.d.ts +22 -0
  52. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.d.ts.map +1 -0
  53. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.js +312 -0
  54. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.js.map +1 -0
  55. package/dist/custom/MJArtifactVersionEntityServer.server.d.ts +76 -12
  56. package/dist/custom/MJArtifactVersionEntityServer.server.d.ts.map +1 -1
  57. package/dist/custom/MJArtifactVersionEntityServer.server.js +934 -55
  58. package/dist/custom/MJArtifactVersionEntityServer.server.js.map +1 -1
  59. package/dist/custom/MJArtifactWorkingStateEntityServer.server.d.ts +42 -0
  60. package/dist/custom/MJArtifactWorkingStateEntityServer.server.d.ts.map +1 -0
  61. package/dist/custom/MJArtifactWorkingStateEntityServer.server.js +547 -0
  62. package/dist/custom/MJArtifactWorkingStateEntityServer.server.js.map +1 -0
  63. package/dist/custom/MJCollectionArtifactEntityServer.server.d.ts +36 -0
  64. package/dist/custom/MJCollectionArtifactEntityServer.server.d.ts.map +1 -0
  65. package/dist/custom/MJCollectionArtifactEntityServer.server.js +533 -0
  66. package/dist/custom/MJCollectionArtifactEntityServer.server.js.map +1 -0
  67. package/dist/custom/MJCollectionEntityServer.server.d.ts +23 -0
  68. package/dist/custom/MJCollectionEntityServer.server.d.ts.map +1 -0
  69. package/dist/custom/MJCollectionEntityServer.server.js +555 -0
  70. package/dist/custom/MJCollectionEntityServer.server.js.map +1 -0
  71. package/dist/custom/MJCollectionPermissionEntityServer.server.d.ts +18 -0
  72. package/dist/custom/MJCollectionPermissionEntityServer.server.d.ts.map +1 -0
  73. package/dist/custom/MJCollectionPermissionEntityServer.server.js +196 -0
  74. package/dist/custom/MJCollectionPermissionEntityServer.server.js.map +1 -0
  75. package/dist/custom/MJConversationDetailEntityServer.server.d.ts +27 -2
  76. package/dist/custom/MJConversationDetailEntityServer.server.d.ts.map +1 -1
  77. package/dist/custom/MJConversationDetailEntityServer.server.js +300 -4
  78. package/dist/custom/MJConversationDetailEntityServer.server.js.map +1 -1
  79. package/dist/custom/MJConversationEntityServer.server.d.ts +6 -20
  80. package/dist/custom/MJConversationEntityServer.server.d.ts.map +1 -1
  81. package/dist/custom/MJConversationEntityServer.server.js +293 -16
  82. package/dist/custom/MJConversationEntityServer.server.js.map +1 -1
  83. package/dist/custom/MJEntityEntityServer.server.d.ts +9 -0
  84. package/dist/custom/MJEntityEntityServer.server.d.ts.map +1 -1
  85. package/dist/custom/MJEntityEntityServer.server.js +31 -2
  86. package/dist/custom/MJEntityEntityServer.server.js.map +1 -1
  87. package/dist/custom/MJGraphConceptEntityServer.server.d.ts +92 -0
  88. package/dist/custom/MJGraphConceptEntityServer.server.d.ts.map +1 -0
  89. package/dist/custom/MJGraphConceptEntityServer.server.js +203 -0
  90. package/dist/custom/MJGraphConceptEntityServer.server.js.map +1 -0
  91. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +16 -2
  92. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -1
  93. package/dist/custom/MJGraphEdgeEntityServer.server.js +26 -4
  94. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -1
  95. package/dist/custom/MJListEntityServer.server.d.ts +26 -10
  96. package/dist/custom/MJListEntityServer.server.d.ts.map +1 -1
  97. package/dist/custom/MJListEntityServer.server.js +118 -20
  98. package/dist/custom/MJListEntityServer.server.js.map +1 -1
  99. package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts +31 -0
  100. package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts.map +1 -0
  101. package/dist/custom/MJMLModelPublishRecordEntityServer.server.js +68 -0
  102. package/dist/custom/MJMLModelPublishRecordEntityServer.server.js.map +1 -0
  103. package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts +78 -0
  104. package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts.map +1 -0
  105. package/dist/custom/MJMLModelScoringBindingEntityServer.server.js +273 -0
  106. package/dist/custom/MJMLModelScoringBindingEntityServer.server.js.map +1 -0
  107. package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts +18 -0
  108. package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts.map +1 -0
  109. package/dist/custom/MJMLOutputBindingEntityServer.server.js +61 -0
  110. package/dist/custom/MJMLOutputBindingEntityServer.server.js.map +1 -0
  111. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts +3 -3
  112. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts.map +1 -1
  113. package/dist/custom/MJMLPredictionUnitEntityServer.server.js +4 -4
  114. package/dist/custom/MJMLPredictionUnitEntityServer.server.js.map +1 -1
  115. package/dist/custom/MJProjectEntityServer.server.d.ts +28 -2
  116. package/dist/custom/MJProjectEntityServer.server.d.ts.map +1 -1
  117. package/dist/custom/MJProjectEntityServer.server.js +115 -2
  118. package/dist/custom/MJProjectEntityServer.server.js.map +1 -1
  119. package/dist/custom/MJQueryEntityServer.server.d.ts +41 -4
  120. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  121. package/dist/custom/MJQueryEntityServer.server.js +99 -14
  122. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  123. package/dist/custom/MJQuerySQLEntityServer.server.d.ts +13 -1
  124. package/dist/custom/MJQuerySQLEntityServer.server.d.ts.map +1 -1
  125. package/dist/custom/MJQuerySQLEntityServer.server.js +37 -3
  126. package/dist/custom/MJQuerySQLEntityServer.server.js.map +1 -1
  127. package/dist/custom/MJResourcePermissionEntityServer.server.d.ts +28 -0
  128. package/dist/custom/MJResourcePermissionEntityServer.server.d.ts.map +1 -0
  129. package/dist/custom/MJResourcePermissionEntityServer.server.js +206 -0
  130. package/dist/custom/MJResourcePermissionEntityServer.server.js.map +1 -0
  131. package/dist/custom/MJScheduledJobEntityServer.server.d.ts +27 -0
  132. package/dist/custom/MJScheduledJobEntityServer.server.d.ts.map +1 -0
  133. package/dist/custom/MJScheduledJobEntityServer.server.js +56 -0
  134. package/dist/custom/MJScheduledJobEntityServer.server.js.map +1 -0
  135. package/dist/custom/MJScopedNotificationConfigEntityServer.server.d.ts +15 -0
  136. package/dist/custom/MJScopedNotificationConfigEntityServer.server.d.ts.map +1 -0
  137. package/dist/custom/MJScopedNotificationConfigEntityServer.server.js +48 -0
  138. package/dist/custom/MJScopedNotificationConfigEntityServer.server.js.map +1 -0
  139. package/dist/custom/MJTagEntityServer.server.d.ts +11 -1
  140. package/dist/custom/MJTagEntityServer.server.d.ts.map +1 -1
  141. package/dist/custom/MJTagEntityServer.server.js +28 -3
  142. package/dist/custom/MJTagEntityServer.server.js.map +1 -1
  143. package/dist/custom/MJUserEntityServer.server.d.ts +2 -1
  144. package/dist/custom/MJUserEntityServer.server.d.ts.map +1 -1
  145. package/dist/custom/MJUserEntityServer.server.js +2 -1
  146. package/dist/custom/MJUserEntityServer.server.js.map +1 -1
  147. package/dist/custom/MJUserRoutineEntityServer.server.d.ts +23 -0
  148. package/dist/custom/MJUserRoutineEntityServer.server.d.ts.map +1 -1
  149. package/dist/custom/MJUserRoutineEntityServer.server.js +320 -3
  150. package/dist/custom/MJUserRoutineEntityServer.server.js.map +1 -1
  151. package/dist/custom/MJUserViewEntityServer.server.d.ts +8 -2
  152. package/dist/custom/MJUserViewEntityServer.server.d.ts.map +1 -1
  153. package/dist/custom/MJUserViewEntityServer.server.js +25 -12
  154. package/dist/custom/MJUserViewEntityServer.server.js.map +1 -1
  155. package/dist/custom/RestrictedFieldCommentClassifier.d.ts +9 -3
  156. package/dist/custom/RestrictedFieldCommentClassifier.d.ts.map +1 -1
  157. package/dist/custom/RestrictedFieldCommentClassifier.js +91 -15
  158. package/dist/custom/RestrictedFieldCommentClassifier.js.map +1 -1
  159. package/dist/custom/RestrictedFieldDecision.d.ts +121 -0
  160. package/dist/custom/RestrictedFieldDecision.d.ts.map +1 -0
  161. package/dist/custom/RestrictedFieldDecision.js +168 -0
  162. package/dist/custom/RestrictedFieldDecision.js.map +1 -0
  163. package/dist/custom/SpreadsheetWorkerEntry.d.ts +25 -0
  164. package/dist/custom/SpreadsheetWorkerEntry.d.ts.map +1 -0
  165. package/dist/custom/SpreadsheetWorkerEntry.js +37 -0
  166. package/dist/custom/SpreadsheetWorkerEntry.js.map +1 -0
  167. package/dist/custom/SpreadsheetWorkerRunner.d.ts +45 -0
  168. package/dist/custom/SpreadsheetWorkerRunner.d.ts.map +1 -0
  169. package/dist/custom/SpreadsheetWorkerRunner.js +243 -0
  170. package/dist/custom/SpreadsheetWorkerRunner.js.map +1 -0
  171. package/dist/custom/approvalStamp.d.ts +19 -3
  172. package/dist/custom/approvalStamp.d.ts.map +1 -1
  173. package/dist/custom/approvalStamp.js +13 -3
  174. package/dist/custom/approvalStamp.js.map +1 -1
  175. package/dist/custom/fieldPermissionDelta.d.ts +15 -1
  176. package/dist/custom/fieldPermissionDelta.d.ts.map +1 -1
  177. package/dist/custom/fieldPermissionDelta.js +28 -7
  178. package/dist/custom/fieldPermissionDelta.js.map +1 -1
  179. package/dist/custom/fieldPermissionReconciler.d.ts +4 -1
  180. package/dist/custom/fieldPermissionReconciler.d.ts.map +1 -1
  181. package/dist/custom/fieldPermissionReconciler.js +4 -2
  182. package/dist/custom/fieldPermissionReconciler.js.map +1 -1
  183. package/dist/custom/graph/GraphFindPathServerOperation.d.ts +24 -0
  184. package/dist/custom/graph/GraphFindPathServerOperation.d.ts.map +1 -0
  185. package/dist/custom/graph/GraphFindPathServerOperation.js +88 -0
  186. package/dist/custom/graph/GraphFindPathServerOperation.js.map +1 -0
  187. package/dist/custom/graph/index.d.ts +2 -0
  188. package/dist/custom/graph/index.d.ts.map +1 -0
  189. package/dist/custom/graph/index.js +2 -0
  190. package/dist/custom/graph/index.js.map +1 -0
  191. package/dist/custom/list-refresh/ListRefreshRoutine.d.ts +40 -0
  192. package/dist/custom/list-refresh/ListRefreshRoutine.d.ts.map +1 -0
  193. package/dist/custom/list-refresh/ListRefreshRoutine.js +114 -0
  194. package/dist/custom/list-refresh/ListRefreshRoutine.js.map +1 -0
  195. package/dist/index.d.ts +24 -0
  196. package/dist/index.d.ts.map +1 -1
  197. package/dist/index.js +33 -0
  198. package/dist/index.js.map +1 -1
  199. package/dist/tsconfig.tsbuildinfo +1 -0
  200. package/package.json +31 -30
@@ -4,10 +4,330 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
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
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import { BaseEntity, RunView, LogError } from "@memberjunction/core";
8
- import { MJArtifactVersionEntity, ArtifactExtractor } from "@memberjunction/core-entities";
9
- import { RegisterClass } from "@memberjunction/global";
7
+ import { BaseEntity, BaseEntityResult, CompositeKey, GetDataHooks, LogError, Metadata, RegisterDataHook, RunView, WellKnownUserSource } from '@memberjunction/core';
8
+ import { ArtifactExtractor, ArtifactPermissionEngine, MakePreParsedWorkbookCacheKey, MJArtifactVersionEntity, SpreadsheetEngine, ValidateArtifactContentMutationAgainstLocks } from '@memberjunction/core-entities';
9
+ import { UserCache } from '@memberjunction/generic-database-provider';
10
+ import { EscapeSQLString, GetGlobalObjectStore, IsValidUUID, MJEventType, MJGlobal, NormalizeUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
10
11
  import { createHash } from 'crypto';
12
+ import { BuildSqlArtifactReadablePredicateAsync, CascadeDeleteArtifactGuestShareLinks, CascadeDeleteArtifactVersionAttributes, ConsumePreResolvedIdsForParams, EmptyPostRunViewResult, FinalizePostRunViewResult, GetWorkingStateContentDeserializer, PrepareScopedPreRunView, QualifyOuterEntityColumnAsync, ShouldBypassPostRunViewAsync, StripSyntheticFieldsFromRow } from './ArtifactSecurityHookHelpers.js';
13
+ export const ARTIFACT_VERSION_SAVED_EVENT_CODE = 'MJ_ARTIFACT_VERSION_SAVED';
14
+ const ARTIFACT_VERSION_ENTITY_NAME = 'MJ: Artifact Versions';
15
+ const GLOBAL_KEY_TRUSTED_RESTORE = '__MJ_TRUSTED_SERVER_RESTORE_ENTITIES__';
16
+ const GLOBAL_KEY_TRUSTED_AGENT_DRAFT = '__MJ_TRUSTED_AGENT_DRAFT_VERSION_ENTITIES__';
17
+ const GLOBAL_KEY_TRUSTED_COMPACTION = '__MJ_TRUSTED_COMPACTION_VERSION_ENTITIES__';
18
+ const GLOBAL_KEY_INTERNAL_VERSION_PARAMS = '__MJ_INTERNAL_VERSION_SECURITY_QUERY_PARAMS__';
19
+ const GLOBAL_KEY_ORIGINAL_VERSION_FIELDS = '__MJ_ORIGINAL_VERSION_FIELDS_BY_PARAMS__';
20
+ const GLOBAL_KEY_SQL_SCOPED_VERSION_PARAMS = '__MJ_SQL_SCOPED_VERSION_PARAMS__';
21
+ /**
22
+ * Marks an in-process agent run draft `MJ: Artifact Versions` entity so sequential tool calls
23
+ * during that agent run may update its `Content` (still subject to lock validation and
24
+ * unshared-link verification in {@link MJArtifactVersionEntityServer.Save}, `B3`).
25
+ */
26
+ export function MarkTrustedAgentRunDraftVersionSave(entity) {
27
+ if (entity && typeof entity === 'object') {
28
+ getGlobalWeakSet(GLOBAL_KEY_TRUSTED_AGENT_DRAFT).add(entity);
29
+ }
30
+ }
31
+ /**
32
+ * Marks an in-process `ArtifactCollaborationServer` room compaction save (`N3`). Every frame
33
+ * admitted into the Yjs room already passed per-connection lock checks, so compaction can persist
34
+ * the combined room state without attributing an owner's earlier locked edits to the triggering user.
35
+ */
36
+ export function MarkTrustedCompactionVersionSave(entity) {
37
+ if (entity && typeof entity === 'object') {
38
+ getGlobalWeakSet(GLOBAL_KEY_TRUSTED_COMPACTION).add(entity);
39
+ }
40
+ }
41
+ function getGlobalWeakSet(key) {
42
+ const store = GetGlobalObjectStore();
43
+ if (store) {
44
+ const existing = store[key];
45
+ if (existing instanceof WeakSet) {
46
+ return existing;
47
+ }
48
+ const created = new WeakSet();
49
+ store[key] = created;
50
+ return created;
51
+ }
52
+ return new WeakSet();
53
+ }
54
+ function getOriginalVersionFieldsMap() {
55
+ const store = GetGlobalObjectStore();
56
+ if (store) {
57
+ const existing = store[GLOBAL_KEY_ORIGINAL_VERSION_FIELDS];
58
+ if (existing instanceof WeakMap) {
59
+ return existing;
60
+ }
61
+ const created = new WeakMap();
62
+ store[GLOBAL_KEY_ORIGINAL_VERSION_FIELDS] = created;
63
+ return created;
64
+ }
65
+ return new WeakMap();
66
+ }
67
+ export function MarkTrustedServerRestoreSave(entity) {
68
+ if (entity && typeof entity === 'object') {
69
+ getGlobalWeakSet(GLOBAL_KEY_TRUSTED_RESTORE).add(entity);
70
+ }
71
+ }
72
+ function isServerSystemUser(user) {
73
+ if (!user) {
74
+ return false;
75
+ }
76
+ const systemUserId = UserCache.Instance.GetSystemUser()?.ID;
77
+ return Boolean((systemUserId && UUIDsEqual(user.ID, systemUserId)) ||
78
+ WellKnownUserSource.Instance.IsSystemUser(user));
79
+ }
80
+ function isMetadataProvider(provider) {
81
+ return Boolean(provider && ('Entities' in provider || 'ProviderType' in provider));
82
+ }
83
+ function resolveMetadataProvider(entityProvider, actor) {
84
+ if (isMetadataProvider(entityProvider)) {
85
+ return entityProvider;
86
+ }
87
+ return (actor?.OwningProvider ??
88
+ Metadata.Provider ?? // global-provider-ok: fallback when provider is not attached to entity
89
+ null);
90
+ }
91
+ function resolveTargetEntityName(params) {
92
+ if (typeof params.EntityName === 'string' && params.EntityName.trim().length > 0) {
93
+ return params.EntityName.trim();
94
+ }
95
+ const viewEntity = params.ViewEntity;
96
+ const viewEntityName = viewEntity?.Entity;
97
+ if (typeof viewEntityName === 'string' && viewEntityName.trim().length > 0) {
98
+ return viewEntityName.trim();
99
+ }
100
+ return '';
101
+ }
102
+ function readVersionArtifactId(row) {
103
+ if (!row || typeof row !== 'object') {
104
+ return null;
105
+ }
106
+ if (row instanceof MJArtifactVersionEntity) {
107
+ return row.ArtifactID || null;
108
+ }
109
+ const candidate = row.ArtifactID;
110
+ return typeof candidate === 'string' && candidate.trim().length > 0 ? candidate.trim() : null;
111
+ }
112
+ function readVersionRowId(row) {
113
+ if (!row || typeof row !== 'object') {
114
+ return null;
115
+ }
116
+ if (row instanceof MJArtifactVersionEntity) {
117
+ return row.ID || null;
118
+ }
119
+ const candidate = row.ID;
120
+ return typeof candidate === 'string' && candidate.trim().length > 0 ? candidate.trim() : null;
121
+ }
122
+ const SINGLE_ARTIFACT_EQ_FILTER_RE = /^\s*\[?ArtifactID\]?\s*=\s*N?'([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})'\s*$/i;
123
+ function extractSingleArtifactIdFromFilter(extraFilter) {
124
+ const raw = typeof extraFilter === 'string'
125
+ ? extraFilter
126
+ : extraFilter && typeof extraFilter === 'object'
127
+ ? extraFilter.default
128
+ : null;
129
+ if (typeof raw !== 'string') {
130
+ return null;
131
+ }
132
+ const match = SINGLE_ARTIFACT_EQ_FILTER_RE.exec(raw);
133
+ return match ? match[1] : null;
134
+ }
135
+ function hasFieldIgnoreCase(fields, targetField) {
136
+ const lower = targetField.toLowerCase();
137
+ return fields.some((f) => typeof f === 'string' && f.trim().toLowerCase() === lower);
138
+ }
139
+ async function fetchVersionArtifactIdsByIds(provider, contextUser, versionIds) {
140
+ const map = new Map();
141
+ const uniqueEscaped = Array.from(new Set(versionIds
142
+ .map((id) => id.trim())
143
+ .filter((id) => id.length > 0)
144
+ .map((id) => `'${EscapeSQLString(id)}'`)));
145
+ if (uniqueEscaped.length === 0) {
146
+ return map;
147
+ }
148
+ try {
149
+ const systemUser = (await WellKnownUserSource.Instance.GetSystemUser(provider)) ?? contextUser;
150
+ const rv = RunView.FromMetadataProvider(provider);
151
+ const lookupParams = {
152
+ EntityName: 'MJ: Artifact Versions',
153
+ ExtraFilter: `ID IN (${uniqueEscaped.join(',')})`,
154
+ Fields: ['ID', 'ArtifactID'],
155
+ MaxRows: uniqueEscaped.length,
156
+ SkipTotalRowCount: true,
157
+ ResultType: 'simple'
158
+ };
159
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(lookupParams);
160
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(lookupParams);
161
+ const res = await rv.RunView(lookupParams, systemUser);
162
+ if (!res?.Success) {
163
+ LogError(`ArtifactVersionPostRunViewHook failed hydrating ArtifactID for narrow Fields projection: ${res?.ErrorMessage || 'RunView returned Success=false'}`);
164
+ return map;
165
+ }
166
+ if (Array.isArray(res.Results)) {
167
+ for (const item of res.Results) {
168
+ if (item.ID && item.ArtifactID) {
169
+ map.set(NormalizeUUID(item.ID), item.ArtifactID);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ catch (error) {
175
+ LogError(`ArtifactVersionPostRunViewHook failed hydrating ArtifactID for narrow Fields projection: ${error instanceof Error ? error.message : String(error)}`);
176
+ }
177
+ return map;
178
+ }
179
+ function stripSyntheticArtifactId(row) {
180
+ if (!row || typeof row !== 'object' || row instanceof BaseEntity) {
181
+ return row;
182
+ }
183
+ if (!Object.prototype.hasOwnProperty.call(row, 'ArtifactID')) {
184
+ return row;
185
+ }
186
+ const copy = { ...row };
187
+ delete copy.ArtifactID;
188
+ return copy;
189
+ }
190
+ /**
191
+ * Server-side `PreRunView` data hook ensuring `ArtifactID` is included prior to column projection
192
+ * when a non-system caller queries `MJ: Artifact Versions` with a narrow `Fields` list (`B3`).
193
+ * Mutates `params` in place so `ProviderBase.RunView` (`TrustLocalCacheCompletely === true`) carries
194
+ * the widened `Fields` into `InternalRunView` and `PostRunView` without poisoning `LocalCacheManager`.
195
+ * Any synthetically added `ArtifactID` is stripped in {@link ArtifactVersionPostRunViewHook}
196
+ * before returning to the caller so the caller's projected shape is preserved.
197
+ */
198
+ export const ArtifactVersionPreRunViewHook = async (params, contextUser, hookProvider) => {
199
+ return PrepareScopedPreRunView(params, {
200
+ TargetEntityName: ARTIFACT_VERSION_ENTITY_NAME,
201
+ RequiredFields: ['ArtifactID'],
202
+ IdColumnName: 'ArtifactID',
203
+ InternalParams: getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS),
204
+ OriginalFieldsMap: getOriginalVersionFieldsMap(),
205
+ SqlScopedParams: getGlobalWeakSet(GLOBAL_KEY_SQL_SCOPED_VERSION_PARAMS),
206
+ BuildSqlPredicateAsync: async (prov, user, entityInfo, runViewParams, collectionCache) => BuildSqlArtifactReadablePredicateAsync(await QualifyOuterEntityColumnAsync(entityInfo, 'vwArtifactVersions', 'ArtifactID', prov, runViewParams, user), prov, user, { precomputedCollectionCache: collectionCache }),
207
+ CheckSingleIdReadable: async (prov, artifactId, user) => {
208
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(prov, artifactId, user);
209
+ return perms.CanRead;
210
+ }
211
+ }, contextUser, hookProvider);
212
+ };
213
+ /**
214
+ * Server-side `PostRunView` data hook enforcing `ArtifactPermissionEngine` `CanRead`
215
+ * authorization on `MJ: Artifact Versions` across `RunView` and `RunMJArtifactVersionDynamicView`.
216
+ */
217
+ export const ArtifactVersionPostRunViewHook = async (params, results, contextUser, hookProvider) => {
218
+ if (!results?.Success) {
219
+ return results;
220
+ }
221
+ const provider = resolveMetadataProvider(hookProvider, contextUser);
222
+ const sqlScopedSet = getGlobalWeakSet(GLOBAL_KEY_SQL_SCOPED_VERSION_PARAMS);
223
+ const { bypass, originalFields } = await ShouldBypassPostRunViewAsync(params, ARTIFACT_VERSION_ENTITY_NAME, getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS), getOriginalVersionFieldsMap(), contextUser, provider);
224
+ if (bypass) {
225
+ sqlScopedSet.delete(params);
226
+ if (originalFields && Array.isArray(results.Results)) {
227
+ return {
228
+ ...results,
229
+ Results: results.Results.map((r) => StripSyntheticFieldsFromRow(r, originalFields))
230
+ };
231
+ }
232
+ return results;
233
+ }
234
+ if (!contextUser || !provider || provider.ProviderType !== 'Database') {
235
+ sqlScopedSet.delete(params);
236
+ if (provider !== null && provider.ProviderType !== 'Database') {
237
+ if (originalFields && Array.isArray(results.Results)) {
238
+ return {
239
+ ...results,
240
+ Results: results.Results.map((r) => StripSyntheticFieldsFromRow(r, originalFields))
241
+ };
242
+ }
243
+ return results;
244
+ }
245
+ return EmptyPostRunViewResult(results);
246
+ }
247
+ const filterArtifactId = extractSingleArtifactIdFromFilter(params.ExtraFilter);
248
+ if (!Array.isArray(results.Results) || results.Results.length === 0) {
249
+ if (params.ResultType === 'count_only' && (results.TotalRowCount ?? 0) > 0) {
250
+ if (sqlScopedSet.has(params)) {
251
+ sqlScopedSet.delete(params);
252
+ return results;
253
+ }
254
+ if (filterArtifactId) {
255
+ try {
256
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, filterArtifactId, contextUser);
257
+ if (perms.CanRead) {
258
+ return results;
259
+ }
260
+ }
261
+ catch (error) {
262
+ LogError(`ArtifactVersionPostRunViewHook failed resolving count_only CanRead for artifact ${filterArtifactId}: ${error instanceof Error ? error.message : String(error)}`);
263
+ }
264
+ }
265
+ return EmptyPostRunViewResult(results);
266
+ }
267
+ return FinalizePostRunViewResult(params, results, [], 0, sqlScopedSet);
268
+ }
269
+ const rawRows = results.Results;
270
+ // If any rows lack `ArtifactID` (e.g. direct hook call or narrow projection without PreRunView)
271
+ // and `ExtraFilter` is not a single-artifact equality predicate, hydrate `ArtifactID` by `ID`.
272
+ const missingIds = [];
273
+ if (!filterArtifactId) {
274
+ for (const row of rawRows) {
275
+ if (!readVersionArtifactId(row)) {
276
+ const versionId = readVersionRowId(row);
277
+ if (versionId) {
278
+ missingIds.push(versionId);
279
+ }
280
+ }
281
+ }
282
+ }
283
+ const hydratedArtifactIds = missingIds.length > 0
284
+ ? await fetchVersionArtifactIdsByIds(provider, contextUser, missingIds)
285
+ : null;
286
+ const preResolved = ConsumePreResolvedIdsForParams(params);
287
+ const readAllowedByArtifact = new Map(preResolved);
288
+ const keptRows = [];
289
+ for (const row of rawRows) {
290
+ let artifactId = readVersionArtifactId(row) ?? filterArtifactId;
291
+ if (!artifactId && hydratedArtifactIds) {
292
+ const versionId = readVersionRowId(row);
293
+ if (versionId) {
294
+ artifactId = hydratedArtifactIds.get(NormalizeUUID(versionId)) ?? null;
295
+ }
296
+ }
297
+ if (!artifactId) {
298
+ // Fail CLOSED on unclassifiable rows (no ArtifactID, no single-artifact filter, and no resolvable ID).
299
+ continue;
300
+ }
301
+ const normId = NormalizeUUID(artifactId);
302
+ let allowed = readAllowedByArtifact.get(normId);
303
+ if (allowed === undefined) {
304
+ try {
305
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, artifactId, contextUser);
306
+ allowed = perms.CanRead;
307
+ }
308
+ catch (error) {
309
+ LogError(`ArtifactVersionPostRunViewHook failed resolving CanRead for artifact ${artifactId}: ${error instanceof Error ? error.message : String(error)}`);
310
+ allowed = false;
311
+ }
312
+ readAllowedByArtifact.set(normId, allowed);
313
+ }
314
+ if (allowed) {
315
+ keptRows.push(StripSyntheticFieldsFromRow(row, originalFields));
316
+ }
317
+ }
318
+ return FinalizePostRunViewResult(params, results, keptRows, rawRows.length, sqlScopedSet);
319
+ };
320
+ export function EnsureArtifactVersionReadHookRegistered() {
321
+ const existingPre = GetDataHooks('PreRunView');
322
+ if (!existingPre.includes(ArtifactVersionPreRunViewHook)) {
323
+ RegisterDataHook('PreRunView', ArtifactVersionPreRunViewHook);
324
+ }
325
+ const existingPost = GetDataHooks('PostRunView');
326
+ if (!existingPost.includes(ArtifactVersionPostRunViewHook)) {
327
+ RegisterDataHook('PostRunView', ArtifactVersionPostRunViewHook);
328
+ }
329
+ }
330
+ EnsureArtifactVersionReadHookRegistered();
11
331
  /**
12
332
  * Returns the UTF-8 byte length of `content`. Used by the Save hook to
13
333
  * populate `ContentSizeBytes` so clients can display file sizes without
@@ -23,29 +343,50 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
23
343
  this._loadedAttributes = null;
24
344
  }
25
345
  /**
26
- * Gets the attributes for this artifact version
27
- * Returns loaded attributes if available, empty array otherwise
28
- * Use InnerLoad() to automatically load attributes from database
29
- * After Save(), returns the newly created attributes from extraction
346
+ * Gets the attributes for this artifact version.
347
+ * Returns loaded attributes if available, empty array otherwise.
348
+ * Use InnerLoad() to automatically load attributes from database.
349
+ * After Save(), returns the newly created attributes from extraction.
30
350
  */
31
351
  get Attributes() {
32
352
  return this._loadedAttributes || [];
33
353
  }
34
354
  /**
35
- * Override InnerLoad to automatically load attributes after loading the version
355
+ * Overrides generated `MJArtifactVersionEntity.Load(ID)` (which calls `super.InnerLoad` directly)
356
+ * so single-record `entity.Load(ID)` routes through {@link InnerLoad} and enforces `CanRead`.
357
+ */
358
+ async Load(ID, EntityRelationshipsToLoad) {
359
+ const key = CompositeKey.FromID(ID); // first-pk-ok: 'MJ: Artifact Versions' has the single key ID
360
+ return this.InnerLoad(key, EntityRelationshipsToLoad);
361
+ }
362
+ /**
363
+ * Overrides InnerLoad to:
364
+ * 1) Enforce `ArtifactPermissionEngine` `CanRead` for non-system users (`Blocker 2`).
365
+ * 2) Automatically load `MJ: Artifact Version Attributes` after loading the version.
36
366
  */
37
367
  async InnerLoad(compositeKey, EntityRelationshipsToLoad) {
38
- // Load the base entity first
39
368
  const loaded = await super.InnerLoad(compositeKey, EntityRelationshipsToLoad);
40
369
  if (!loaded) {
41
370
  return false;
42
371
  }
43
- // Automatically load attributes for this version
372
+ const actor = this.ContextCurrentUser;
373
+ if (!isServerSystemUser(actor)) {
374
+ const provider = resolveMetadataProvider(this.ProviderToUse, actor);
375
+ if (!actor || !provider || !this.ArtifactID) {
376
+ this.NewRecord();
377
+ return false;
378
+ }
379
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, this.ArtifactID, actor);
380
+ if (!perms.CanRead) {
381
+ this.NewRecord();
382
+ return false;
383
+ }
384
+ }
44
385
  try {
45
386
  const rv = new RunView(this.RunViewProviderToUse);
46
387
  const result = await rv.RunView({
47
388
  EntityName: 'MJ: Artifact Version Attributes',
48
- ExtraFilter: `ArtifactVersionID='${this.ID}'`,
389
+ ExtraFilter: `ArtifactVersionID='${EscapeSQLString(this.ID)}'`,
49
390
  ResultType: 'entity_object'
50
391
  }, this.ContextCurrentUser);
51
392
  if (result.Success && result.Results) {
@@ -56,49 +397,569 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
56
397
  }
57
398
  }
58
399
  catch (error) {
59
- LogError(`Error loading attributes for artifact version ${this.ID}: ${error instanceof Error ? error.message : error}`);
400
+ LogError(`Error loading attributes for artifact version ${this.ID}: ${error instanceof Error ? error.message : String(error)}`);
60
401
  this._loadedAttributes = [];
61
402
  }
62
403
  return true;
63
404
  }
64
405
  /**
65
406
  * Overrides base save method to:
66
- * 1) Automatically calculate the ContentHash field whenever the Content field is changed
67
- * 2) Automatically extract attributes from the Content field using the ExtractRules from the ArtifactType
68
- * @param options
407
+ * 0) Enforce `ArtifactPermissionEngine` `CanEdit` on `this.ArtifactID` for non-system users (`Blocker 2`).
408
+ * 1) Automatically calculate the ContentHash field whenever the Content field is changed.
409
+ * 2) Automatically extract attributes from the Content field using the ExtractRules from the ArtifactType.
69
410
  */
70
411
  async Save(options) {
71
- const contentDirty = this.IsSaved === false || this.GetFieldByName("Content")?.Dirty;
72
- if (contentDirty && this.Content) {
73
- try {
74
- // 1. Calculate ContentHash using SHA-256
75
- this.ContentHash = this.CalculateContentHash(this.Content);
76
- // 2. Capture the UTF-8 byte length so the client can render file sizes
77
- // without reading the full Content blob.
78
- this.ContentSizeBytes = CalculateContentSizeBytes(this.Content);
79
- // 3. Extract attributes (sets Name/Description and stores pending attributes)
80
- await this.ExtractAndSaveAttributes();
412
+ const saveType = this.IsSaved ? 'update' : 'create';
413
+ const actor = this.ContextCurrentUser;
414
+ const trustedRestoreSet = getGlobalWeakSet(GLOBAL_KEY_TRUSTED_RESTORE);
415
+ const trustedDraftSet = getGlobalWeakSet(GLOBAL_KEY_TRUSTED_AGENT_DRAFT);
416
+ const trustedCompactionSet = getGlobalWeakSet(GLOBAL_KEY_TRUSTED_COMPACTION);
417
+ const isTrustedRestore = trustedRestoreSet.has(this);
418
+ const isTrustedAgentDraft = trustedDraftSet.has(this);
419
+ const isTrustedCompaction = trustedCompactionSet.has(this);
420
+ const provider = resolveMetadataProvider(this.ProviderToUse, actor);
421
+ const preParsedXlsxCache = new Map();
422
+ try {
423
+ if (!isServerSystemUser(actor)) {
424
+ if (provider?.ProviderType === 'Network') {
425
+ return await super.Save(options);
426
+ }
427
+ const artifactIdField = this.safeGetField('ArtifactID');
428
+ const oldArtifactId = typeof artifactIdField?.OldValue === 'string' &&
429
+ artifactIdField.OldValue.trim().length > 0
430
+ ? artifactIdField.OldValue.trim()
431
+ : null;
432
+ const currentArtifactId = this.ArtifactID ? this.ArtifactID.trim() : '';
433
+ if (this.IsSaved &&
434
+ oldArtifactId &&
435
+ (!currentArtifactId || !UUIDsEqual(oldArtifactId, currentArtifactId))) {
436
+ return this.recordPermissionFailure(saveType, 'Permission denied: ArtifactID cannot be reassigned on an existing artifact version.');
437
+ }
438
+ const authArtifactId = (this.IsSaved ? oldArtifactId : null) ?? currentArtifactId;
439
+ if (!actor || !provider || !authArtifactId) {
440
+ return this.recordPermissionFailure(saveType, 'Permission denied: authenticated user context and target ArtifactID are required to save an artifact version.');
441
+ }
442
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, authArtifactId, actor);
443
+ if (!perms.CanEdit) {
444
+ return this.recordPermissionFailure(saveType, `Permission denied: user '${actor.Email || actor.ID}' does not hold Edit permission on artifact '${authArtifactId}'.`);
445
+ }
446
+ const systemActor = (await WellKnownUserSource.Instance.GetSystemUser(provider)) ?? actor;
447
+ const canQueryDb = typeof provider.RunView === 'function';
448
+ let isArtifactOwner = perms.Source === 'Owner';
449
+ // Pre-parse any `.xlsx` `(content, config)` pair once per Save in the isolated worker (`R10-1`).
450
+ // Never cache or fall back by single string when `(content, config)` pairs can differ.
451
+ const hasXlsxPayload = (raw) => {
452
+ if (!raw || typeof raw !== 'string') {
453
+ return false;
454
+ }
455
+ const trimmed = raw.trim();
456
+ return trimmed.startsWith('data:') || trimmed.startsWith('UEsDB');
457
+ };
458
+ const preParseIfXlsx = async (rawContent, rawConfig) => {
459
+ if (!hasXlsxPayload(rawContent) && !hasXlsxPayload(rawConfig)) {
460
+ return null;
461
+ }
462
+ const cacheKey = MakePreParsedWorkbookCacheKey(rawContent, rawConfig);
463
+ if (preParsedXlsxCache.has(cacheKey)) {
464
+ return null;
465
+ }
466
+ try {
467
+ const parsed = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(rawContent ?? null, rawConfig ?? null, { SkipEvaluate: true });
468
+ preParsedXlsxCache.set(cacheKey, parsed);
469
+ return null;
470
+ }
471
+ catch (err) {
472
+ return err instanceof Error ? err.message : String(err);
473
+ }
474
+ };
475
+ if (canQueryDb && IsValidUUID(authArtifactId)) {
476
+ const artParams = {
477
+ EntityName: 'MJ: Artifacts',
478
+ ExtraFilter: `ID='${EscapeSQLString(authArtifactId)}'`,
479
+ Fields: ['ID', 'UserID'],
480
+ MaxRows: 1,
481
+ SkipTotalRowCount: true,
482
+ ResultType: 'simple'
483
+ };
484
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(artParams);
485
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(artParams);
486
+ const artRes = await RunView.FromMetadataProvider(provider).RunView(artParams, systemActor);
487
+ if (!artRes.Success && provider.ProviderType === 'Database') {
488
+ return this.recordPermissionFailure(saveType, 'Permission denied: unable to verify parent artifact ownership before saving version.');
489
+ }
490
+ const artRow = artRes.Results?.[0];
491
+ if (artRow?.UserID && UUIDsEqual(artRow.UserID, actor.ID)) {
492
+ isArtifactOwner = true;
493
+ }
494
+ }
495
+ if (!this.IsSaved) {
496
+ // Always stamp UserID from authenticated actor on version create (`B3`).
497
+ if (this.hasInitializedFields()) {
498
+ this.UserID = actor.ID;
499
+ }
500
+ if (canQueryDb && IsValidUUID(authArtifactId)) {
501
+ const priorParams = {
502
+ EntityName: ARTIFACT_VERSION_ENTITY_NAME,
503
+ ExtraFilter: `ArtifactID='${EscapeSQLString(authArtifactId)}'`,
504
+ OrderBy: 'VersionNumber DESC',
505
+ Fields: ['ID', 'VersionNumber', 'Content', 'Configuration', 'ContentMode', 'FileID'],
506
+ MaxRows: 1,
507
+ SkipTotalRowCount: true,
508
+ ResultType: 'simple'
509
+ };
510
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(priorParams);
511
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(priorParams);
512
+ const priorRes = await RunView.FromMetadataProvider(provider).RunView(priorParams, systemActor);
513
+ if (!priorRes.Success && provider.ProviderType === 'Database') {
514
+ return this.recordPermissionFailure(saveType, 'Permission denied: unable to verify prior artifact version locks before creating version.');
515
+ }
516
+ const nextContent = this.safeReadStringProp('Content') ?? '';
517
+ const nextConfig = this.safeReadStringProp('Configuration');
518
+ const rawFileId = this.safeReadStringProp('FileID');
519
+ const nextFileId = rawFileId ? rawFileId.trim() : null;
520
+ const nextContentMode = this.safeReadStringProp('ContentMode');
521
+ const priorRow = priorRes.Success ? priorRes.Results?.[0] : undefined;
522
+ if (priorRes.Success) {
523
+ if (priorRow) {
524
+ const priorVer = typeof priorRow.VersionNumber === 'number' && Number.isFinite(priorRow.VersionNumber)
525
+ ? priorRow.VersionNumber
526
+ : 0;
527
+ if (this.hasInitializedFields()) {
528
+ this.VersionNumber = priorVer + 1;
529
+ }
530
+ if (!isTrustedCompaction) {
531
+ const priorContent = typeof priorRow.Content === 'string' ? priorRow.Content : '';
532
+ const priorConfig = typeof priorRow.Configuration === 'string' ? priorRow.Configuration : null;
533
+ const priorXlsxErr = (await preParseIfXlsx(priorContent, priorConfig)) ??
534
+ (priorConfig !== null ? await preParseIfXlsx(priorContent, null) : null) ??
535
+ (await preParseIfXlsx(nextContent, nextConfig ?? null)) ??
536
+ (nextConfig != null ? await preParseIfXlsx(nextContent, null) : null);
537
+ if (priorXlsxErr) {
538
+ return this.recordPermissionFailure(saveType, priorXlsxErr);
539
+ }
540
+ const lockCheck = ValidateArtifactContentMutationAgainstLocks(priorContent, nextContent, actor.ID, isArtifactOwner, {
541
+ currentConfiguration: priorConfig,
542
+ nextConfiguration: nextConfig,
543
+ preParsedWorkbooks: preParsedXlsxCache
544
+ });
545
+ if (!lockCheck.Allowed) {
546
+ return this.recordPermissionFailure(saveType, lockCheck.Reason ?? 'Write rejected: new version content modifies a locked region.');
547
+ }
548
+ const priorFileId = typeof priorRow.FileID === 'string' ? priorRow.FileID.trim() : null;
549
+ const isFileModeSwap = (priorRow.ContentMode === 'File' || nextContentMode === 'File') &&
550
+ priorFileId !== nextFileId;
551
+ if (isFileModeSwap && !isArtifactOwner && !isTrustedAgentDraft && priorConfig) {
552
+ const wipeCheck = ValidateArtifactContentMutationAgainstLocks(priorContent, '', actor.ID, false, {
553
+ currentConfiguration: priorConfig,
554
+ nextConfiguration: '{}',
555
+ preParsedWorkbooks: preParsedXlsxCache
556
+ });
557
+ if (!wipeCheck.Allowed) {
558
+ return this.recordPermissionFailure(saveType, 'Write rejected: File-mode artifact with protected ranges cannot be overwritten directly via FileID replacement.');
559
+ }
560
+ }
561
+ }
562
+ }
563
+ else if (this.hasInitializedFields() &&
564
+ (typeof this.VersionNumber !== 'number' || this.VersionNumber < 1)) {
565
+ this.VersionNumber = 1;
566
+ }
567
+ }
568
+ if (!isTrustedCompaction && !isArtifactOwner) {
569
+ const wsParams = {
570
+ EntityName: 'MJ: Artifact Working States',
571
+ ExtraFilter: `ArtifactID='${EscapeSQLString(authArtifactId)}'`,
572
+ Fields: ['ID', 'ArtifactID', 'YjsState'],
573
+ IncludeBinaryFields: true,
574
+ MaxRows: 1,
575
+ SkipTotalRowCount: true,
576
+ ResultType: 'simple'
577
+ };
578
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(wsParams);
579
+ const wsRes = await RunView.FromMetadataProvider(provider).RunView(wsParams, systemActor);
580
+ if (!wsRes.Success && provider.ProviderType === 'Database') {
581
+ return this.recordPermissionFailure(saveType, 'Permission denied: unable to verify active artifact working state locks before saving version.');
582
+ }
583
+ const rawYjsState = wsRes.Success ? wsRes.Results?.[0]?.YjsState : null;
584
+ const hasWorkingStateBytes = (typeof rawYjsState === 'string' && rawYjsState.trim().length > 0) ||
585
+ (rawYjsState instanceof Uint8Array && rawYjsState.byteLength > 0);
586
+ if (hasWorkingStateBytes) {
587
+ const deserializer = GetWorkingStateContentDeserializer();
588
+ if (!deserializer) {
589
+ if (provider.ProviderType === 'Database') {
590
+ return this.recordPermissionFailure(saveType, 'Permission denied: unable to decode active working-state locks before saving version.');
591
+ }
592
+ }
593
+ else {
594
+ let wsContent = '';
595
+ try {
596
+ wsContent = deserializer(rawYjsState);
597
+ }
598
+ catch (err) {
599
+ LogError(`MJArtifactVersionEntityServer: failed to decode active working-state locks for artifact '${authArtifactId}': ${err instanceof Error ? err.message : String(err)}`);
600
+ return this.recordPermissionFailure(saveType, 'Permission denied: unable to decode active working-state locks before saving version.');
601
+ }
602
+ if (wsContent && wsContent !== (priorRow?.Content ?? '')) {
603
+ const wsConfig = priorRow?.Configuration ?? null;
604
+ const wsXlsxErr = (await preParseIfXlsx(wsContent, wsConfig)) ??
605
+ (wsConfig !== null ? await preParseIfXlsx(wsContent, null) : null) ??
606
+ (await preParseIfXlsx(nextContent, nextConfig ?? null)) ??
607
+ (nextConfig != null ? await preParseIfXlsx(nextContent, null) : null);
608
+ if (wsXlsxErr) {
609
+ return this.recordPermissionFailure(saveType, wsXlsxErr);
610
+ }
611
+ const wsLockCheck = ValidateArtifactContentMutationAgainstLocks(wsContent, nextContent, actor.ID, false, {
612
+ currentConfiguration: priorRow?.Configuration ?? null,
613
+ nextConfiguration: nextConfig,
614
+ preParsedWorkbooks: preParsedXlsxCache
615
+ });
616
+ if (!wsLockCheck.Allowed) {
617
+ return this.recordPermissionFailure(saveType, wsLockCheck.Reason ??
618
+ 'Write rejected: new version content conflicts with a locked region in the active working state.');
619
+ }
620
+ }
621
+ }
622
+ }
623
+ }
624
+ }
625
+ }
626
+ else {
627
+ const userIdField = this.safeGetField('UserID');
628
+ if (userIdField?.Dirty) {
629
+ const oldUserId = typeof userIdField.OldValue === 'string' ? userIdField.OldValue.trim() : '';
630
+ const rawUserId = this.safeReadStringProp('UserID');
631
+ const curUserId = rawUserId ? rawUserId.trim() : '';
632
+ if (!oldUserId || !UUIDsEqual(oldUserId, curUserId)) {
633
+ return this.recordPermissionFailure('update', 'Permission denied: UserID on a saved artifact version is immutable.');
634
+ }
635
+ }
636
+ const verNumField = this.safeGetField('VersionNumber');
637
+ const curVerNum = this.hasInitializedFields()
638
+ ? this.VersionNumber
639
+ : Object.getOwnPropertyDescriptor(this, 'VersionNumber')?.value;
640
+ if (verNumField?.Dirty && verNumField.OldValue !== undefined && verNumField.OldValue !== curVerNum) {
641
+ return this.recordPermissionFailure('update', 'Permission denied: VersionNumber on a saved artifact version is immutable.');
642
+ }
643
+ const contentField = this.safeGetField('Content');
644
+ const configurationField = this.safeGetField('Configuration');
645
+ const contentModeField = this.safeGetField('ContentMode');
646
+ const fileIdField = this.safeGetField('FileID');
647
+ const contentHashField = this.safeGetField('ContentHash');
648
+ const mutatesVersionContent = Boolean(contentField?.Dirty ||
649
+ configurationField?.Dirty ||
650
+ contentModeField?.Dirty ||
651
+ fileIdField?.Dirty ||
652
+ contentHashField?.Dirty);
653
+ if (mutatesVersionContent) {
654
+ if (!isTrustedAgentDraft && !isTrustedCompaction) {
655
+ return this.recordPermissionFailure('update', 'Permission denied: saved artifact versions are immutable; create a new version instead.');
656
+ }
657
+ const savedVersionId = this.safeReadId();
658
+ if (canQueryDb && savedVersionId && IsValidUUID(savedVersionId)) {
659
+ const linkCheckParams = {
660
+ EntityName: 'MJ: Artifact Guest Share Links',
661
+ ExtraFilter: `ArtifactVersionID='${EscapeSQLString(savedVersionId)}'`,
662
+ Fields: ['ID'],
663
+ MaxRows: 1,
664
+ SkipTotalRowCount: true,
665
+ ResultType: 'simple'
666
+ };
667
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(linkCheckParams);
668
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(linkCheckParams);
669
+ const linkRes = await RunView.FromMetadataProvider(provider).RunView(linkCheckParams, systemActor);
670
+ if (!linkRes.Success && provider.ProviderType === 'Database') {
671
+ return this.recordPermissionFailure('update', 'Permission denied: unable to verify whether version is pinned by guest share links.');
672
+ }
673
+ if ((linkRes.Results?.length ?? 0) > 0) {
674
+ return this.recordPermissionFailure('update', 'Permission denied: cannot mutate an artifact version referenced by guest share links.');
675
+ }
676
+ }
677
+ const oldContent = typeof contentField?.OldValue === 'string' ? contentField.OldValue : '';
678
+ const nextContent = this.safeReadStringProp('Content') ?? '';
679
+ const oldConfig = typeof configurationField?.OldValue === 'string' ? configurationField.OldValue : null;
680
+ const nextConfig = this.safeReadStringProp('Configuration');
681
+ if (!isTrustedCompaction && ((oldContent.length > 0 && oldContent !== nextContent) || (oldConfig && oldConfig !== nextConfig))) {
682
+ const draftXlsxErr = (await preParseIfXlsx(oldContent, oldConfig)) ??
683
+ (oldConfig !== null ? await preParseIfXlsx(oldContent, null) : null) ??
684
+ (await preParseIfXlsx(nextContent, nextConfig ?? null)) ??
685
+ (nextConfig != null ? await preParseIfXlsx(nextContent, null) : null);
686
+ if (draftXlsxErr) {
687
+ return this.recordPermissionFailure('update', draftXlsxErr);
688
+ }
689
+ const lockCheck = ValidateArtifactContentMutationAgainstLocks(oldContent, nextContent, actor.ID, isArtifactOwner, {
690
+ currentConfiguration: oldConfig,
691
+ nextConfiguration: nextConfig,
692
+ preParsedWorkbooks: preParsedXlsxCache
693
+ });
694
+ if (!lockCheck.Allowed) {
695
+ return this.recordPermissionFailure('update', lockCheck.Reason ?? 'Write rejected: draft update modifies a locked region.');
696
+ }
697
+ }
698
+ }
699
+ }
81
700
  }
82
- catch (error) {
83
- LogError(`Error in MJArtifactVersionEntityServer.Save pre-processing: ${error instanceof Error ? error.message : error}`);
701
+ const contentField = this.safeGetField('Content');
702
+ const configurationField = this.safeGetField('Configuration');
703
+ const previousContentValue = typeof contentField?.OldValue === 'string' ? contentField.OldValue : null;
704
+ const contentDirty = this.IsSaved === false || contentField?.Dirty;
705
+ const configDirty = this.IsSaved === false || configurationField?.Dirty;
706
+ const currentContentMode = this.hasInitializedFields() ? this.ContentMode : null;
707
+ if ((contentDirty || configDirty) && currentContentMode !== 'File') {
708
+ const effectiveContent = this.safeReadStringProp('Content') ?? '';
709
+ const effectiveConfig = this.safeReadStringProp('Configuration');
710
+ const looksLikeSpreadsheet = (raw) => {
711
+ if (!raw || typeof raw !== 'string')
712
+ return false;
713
+ const trimmed = raw.trim();
714
+ return ((trimmed.startsWith('{') && trimmed.includes('"Worksheets"')) ||
715
+ trimmed.startsWith('data:') ||
716
+ trimmed.startsWith('UEsDB'));
717
+ };
718
+ if (looksLikeSpreadsheet(effectiveContent) || looksLikeSpreadsheet(effectiveConfig)) {
719
+ const effectiveContentArg = looksLikeSpreadsheet(effectiveContent) ? effectiveContent : null;
720
+ const effectiveConfigArg = looksLikeSpreadsheet(effectiveConfig) ? effectiveConfig : null;
721
+ const effectivePairKey = MakePreParsedWorkbookCacheKey(effectiveContentArg, effectiveConfigArg);
722
+ if (!preParsedXlsxCache.has(effectivePairKey)) {
723
+ try {
724
+ await SpreadsheetEngine.Instance.ParseWorkbookIsolated(effectiveContentArg, effectiveConfigArg, { SkipEvaluate: true });
725
+ }
726
+ catch (err) {
727
+ const msg = err instanceof Error ? err.message : String(err);
728
+ return this.recordPermissionFailure(saveType, msg);
729
+ }
730
+ }
731
+ }
732
+ }
733
+ if (contentDirty && currentContentMode !== 'File') {
734
+ const effectiveContent = this.safeReadStringProp('Content') ?? '';
735
+ // 1. Always recompute server-side ContentHash & ContentSizeBytes when content changes (`B3`).
736
+ const currentHash = this.hasInitializedFields() ? this.ContentHash : Object.getOwnPropertyDescriptor(this, 'ContentHash')?.value;
737
+ if (effectiveContent.length > 0 || (typeof currentHash === 'string' && currentHash.length > 0)) {
738
+ const nextHash = effectiveContent.length > 0 ? this.CalculateContentHash(effectiveContent) : '';
739
+ const nextBytes = CalculateContentSizeBytes(effectiveContent);
740
+ if (this.hasInitializedFields()) {
741
+ this.ContentHash = nextHash;
742
+ this.ContentSizeBytes = nextBytes;
743
+ }
744
+ else {
745
+ this.safeWriteStubProp('ContentHash', nextHash);
746
+ this.safeWriteStubProp('ContentSizeBytes', nextBytes);
747
+ }
748
+ }
749
+ // 2. Extract attributes when content is non-empty
750
+ if (effectiveContent.length > 0) {
751
+ try {
752
+ await this.ExtractAndSaveAttributes();
753
+ }
754
+ catch (error) {
755
+ this._pendingAttributes = null;
756
+ LogError(`Error in MJArtifactVersionEntityServer.Save attribute extraction: ${error instanceof Error ? error.message : String(error)}`);
757
+ }
758
+ }
759
+ }
760
+ const saveResult = await super.Save(options);
761
+ // Notify ArtifactCollaborationServer when a version's content is saved so active Yjs rooms
762
+ // or persisted working states reconcile out-of-band version writes (REST save, Restore, Library edit).
763
+ if (saveResult && contentDirty && typeof this.Content === 'string' && this.ArtifactID) {
764
+ try {
765
+ const versionId = typeof this.ID === 'string' ? this.ID : '';
766
+ const versionNumber = typeof this.VersionNumber === 'number' ? this.VersionNumber : 0;
767
+ const descriptionValue = typeof this.Description === 'string' ? this.Description : null;
768
+ const commentsValue = typeof this.Comments === 'string' ? this.Comments : null;
769
+ const updatedByUserId = this.UserID || this.ContextCurrentUser?.ID;
770
+ const payload = {
771
+ ArtifactID: this.ArtifactID,
772
+ VersionID: versionId,
773
+ VersionNumber: versionNumber,
774
+ Content: this.Content,
775
+ PreviousContent: previousContentValue,
776
+ Description: descriptionValue,
777
+ Comments: commentsValue,
778
+ IsRestore: isTrustedRestore,
779
+ UpdatedByUserID: updatedByUserId
780
+ };
781
+ MJGlobal.Instance.RaiseEvent({
782
+ component: this,
783
+ event: MJEventType.ComponentEvent,
784
+ eventCode: ARTIFACT_VERSION_SAVED_EVENT_CODE,
785
+ args: payload
786
+ });
787
+ }
788
+ catch (error) {
789
+ LogError(`Error raising ${ARTIFACT_VERSION_SAVED_EVENT_CODE} in MJArtifactVersionEntityServer.Save: ${error instanceof Error ? error.message : String(error)}`);
790
+ }
791
+ }
792
+ // After successful save, create ArtifactVersionAttribute records
793
+ if (saveResult && this._pendingAttributes && this._pendingAttributes.length > 0) {
794
+ try {
795
+ const savedAttributes = await this.SaveAttributeRecords(this._pendingAttributes);
796
+ this._loadedAttributes = savedAttributes;
797
+ this._pendingAttributes = null;
798
+ }
799
+ catch (error) {
800
+ LogError(`Error saving ArtifactVersionAttribute records: ${error instanceof Error ? error.message : String(error)}`);
801
+ }
802
+ }
803
+ return saveResult;
804
+ }
805
+ finally {
806
+ trustedRestoreSet.delete(this);
807
+ trustedDraftSet.delete(this);
808
+ trustedCompactionSet.delete(this);
809
+ }
810
+ }
811
+ /**
812
+ * Enforces `ArtifactPermissionEngine` `CanDelete` on `this.ArtifactID` for non-system users (`Blocker 2`),
813
+ * and cleans up referencing `MJ: Artifact Guest Share Links` before deleting the version (`S8`).
814
+ */
815
+ async Delete(options) {
816
+ const actor = this.ContextCurrentUser;
817
+ const provider = resolveMetadataProvider(this.ProviderToUse, actor);
818
+ if (!isServerSystemUser(actor)) {
819
+ if (provider?.ProviderType === 'Network') {
820
+ return super.Delete(options);
821
+ }
822
+ const artifactIdField = this.safeGetField('ArtifactID');
823
+ const oldArtifactId = typeof artifactIdField?.OldValue === 'string' &&
824
+ artifactIdField.OldValue.trim().length > 0
825
+ ? artifactIdField.OldValue.trim()
826
+ : null;
827
+ const currentArtifactId = this.ArtifactID ? this.ArtifactID.trim() : '';
828
+ if (this.IsSaved &&
829
+ oldArtifactId &&
830
+ (!currentArtifactId || !UUIDsEqual(oldArtifactId, currentArtifactId))) {
831
+ return this.recordPermissionFailure('delete', 'Permission denied: ArtifactID cannot be reassigned before deleting an artifact version.');
832
+ }
833
+ const authArtifactId = (this.IsSaved ? oldArtifactId : null) ?? currentArtifactId;
834
+ if (!actor || !provider || !authArtifactId) {
835
+ return this.recordPermissionFailure('delete', 'Permission denied: authenticated user context and target ArtifactID are required to delete an artifact version.');
836
+ }
837
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, authArtifactId, actor);
838
+ if (!perms.CanDelete) {
839
+ return this.recordPermissionFailure('delete', `Permission denied: user '${actor.Email || actor.ID}' does not hold Delete permission on artifact '${authArtifactId}'.`);
840
+ }
841
+ const canQueryDb = typeof provider.RunView === 'function';
842
+ let isArtifactOwner = perms.Source === 'Owner';
843
+ const systemActor = (await WellKnownUserSource.Instance.GetSystemUser(provider)) ?? actor;
844
+ if (canQueryDb && IsValidUUID(authArtifactId)) {
845
+ const artParams = {
846
+ EntityName: 'MJ: Artifacts',
847
+ ExtraFilter: `ID='${EscapeSQLString(authArtifactId)}'`,
848
+ Fields: ['ID', 'UserID'],
849
+ MaxRows: 1,
850
+ SkipTotalRowCount: true,
851
+ ResultType: 'simple'
852
+ };
853
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(artParams);
854
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(artParams);
855
+ const artRes = await RunView.FromMetadataProvider(provider).RunView(artParams, systemActor);
856
+ if (!artRes.Success && provider.ProviderType === 'Database') {
857
+ return this.recordPermissionFailure('delete', 'Permission denied: unable to verify parent artifact ownership before deleting version.');
858
+ }
859
+ const artRow = artRes.Results?.[0];
860
+ if (artRow?.UserID && UUIDsEqual(artRow.UserID, actor.ID)) {
861
+ isArtifactOwner = true;
862
+ }
863
+ if (!isArtifactOwner) {
864
+ const versionsParams = {
865
+ EntityName: ARTIFACT_VERSION_ENTITY_NAME,
866
+ ExtraFilter: `ArtifactID='${EscapeSQLString(authArtifactId)}'`,
867
+ OrderBy: 'VersionNumber DESC',
868
+ Fields: ['ID', 'VersionNumber', 'Content', 'Configuration'],
869
+ IgnoreMaxRows: true,
870
+ SkipTotalRowCount: true,
871
+ ResultType: 'simple'
872
+ };
873
+ getGlobalWeakSet(GLOBAL_KEY_INTERNAL_VERSION_PARAMS).add(versionsParams);
874
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(versionsParams);
875
+ const verRes = await RunView.FromMetadataProvider(provider).RunView(versionsParams, systemActor);
876
+ if (!verRes.Success && provider.ProviderType === 'Database') {
877
+ return this.recordPermissionFailure('delete', 'Permission denied: unable to verify artifact version locks before deleting version.');
878
+ }
879
+ const versionRows = verRes.Results ?? [];
880
+ const deletingId = this.safeReadId();
881
+ const targetRow = deletingId
882
+ ? versionRows.find((r) => r.ID && UUIDsEqual(r.ID, deletingId))
883
+ : undefined;
884
+ const isLatestVersion = Boolean(targetRow && versionRows[0]?.ID && UUIDsEqual(targetRow.ID, versionRows[0].ID)) ||
885
+ versionRows.length === 0;
886
+ const deletedContent = typeof targetRow?.Content === 'string'
887
+ ? targetRow.Content
888
+ : this.safeReadStringProp('Content') ?? '';
889
+ const deletedConfig = typeof targetRow?.Configuration === 'string'
890
+ ? targetRow.Configuration
891
+ : this.safeReadStringProp('Configuration');
892
+ const remainingLatest = versionRows.find((r) => !deletingId || !r.ID || !UUIDsEqual(r.ID, deletingId));
893
+ if (isLatestVersion && (deletedContent.length > 0 || (deletedConfig && deletedConfig.length > 0))) {
894
+ const deleteLockCheck = ValidateArtifactContentMutationAgainstLocks(deletedContent, typeof remainingLatest?.Content === 'string' ? remainingLatest.Content : '', actor.ID, false, {
895
+ currentConfiguration: deletedConfig,
896
+ nextConfiguration: typeof remainingLatest?.Configuration === 'string'
897
+ ? remainingLatest.Configuration
898
+ : null
899
+ });
900
+ if (!deleteLockCheck.Allowed) {
901
+ return this.recordPermissionFailure('delete', deleteLockCheck.Reason ??
902
+ 'Permission denied: cannot delete a locked artifact version as a non-owner.');
903
+ }
904
+ }
905
+ }
906
+ }
907
+ }
908
+ const versionIdForCascade = this.safeReadId();
909
+ if (versionIdForCascade && IsValidUUID(versionIdForCascade)) {
910
+ const cascadeRes = await CascadeDeleteArtifactGuestShareLinks(provider, `ArtifactVersionID='${EscapeSQLString(versionIdForCascade)}'`, actor);
911
+ if (!cascadeRes.Success) {
912
+ return this.recordPermissionFailure('delete', cascadeRes.ErrorMessage ?? 'Failed to clean up guest share links before deleting artifact version.');
913
+ }
914
+ const attrCascadeRes = await CascadeDeleteArtifactVersionAttributes(provider, versionIdForCascade, actor);
915
+ if (!attrCascadeRes.Success) {
916
+ return this.recordPermissionFailure('delete', attrCascadeRes.ErrorMessage ?? 'Failed to clean up artifact version attributes before deleting artifact version.');
84
917
  }
85
918
  }
86
- // Save the main entity
87
- const saveResult = await super.Save(options);
88
- // After successful save, create ArtifactVersionAttribute records
89
- if (saveResult && this._pendingAttributes && this._pendingAttributes.length > 0) {
919
+ return super.Delete(options);
920
+ }
921
+ hasInitializedFields() {
922
+ return Boolean(this.EntityInfo && Array.isArray(this.Fields) && this.Fields.length > 0);
923
+ }
924
+ safeReadId() {
925
+ if (this.hasInitializedFields()) {
926
+ return this.ID ? this.ID.trim() : null;
927
+ }
928
+ const own = Object.getOwnPropertyDescriptor(this, 'ID')?.value;
929
+ return typeof own === 'string' && own.trim().length > 0 ? own.trim() : null;
930
+ }
931
+ safeReadStringProp(propName) {
932
+ const val = this.hasInitializedFields()
933
+ ? this[propName]
934
+ : Object.getOwnPropertyDescriptor(this, propName)?.value;
935
+ return typeof val === 'string' ? val : null;
936
+ }
937
+ safeWriteStubProp(propName, value) {
938
+ const desc = Object.getOwnPropertyDescriptor(this, propName);
939
+ if (desc) {
940
+ if (desc.writable) {
941
+ Reflect.set(this, propName, value);
942
+ }
943
+ return;
944
+ }
945
+ Object.defineProperty(this, propName, { value, writable: true, configurable: true });
946
+ }
947
+ safeGetField(fieldName) {
948
+ if (Array.isArray(this.Fields)) {
949
+ const found = this.Fields.find((f) => f.Name === fieldName);
950
+ if (found) {
951
+ return found;
952
+ }
953
+ }
954
+ if (typeof this.GetFieldByName === 'function') {
90
955
  try {
91
- const savedAttributes = await this.SaveAttributeRecords(this._pendingAttributes);
92
- // Populate loaded attributes with the newly created ones
93
- this._loadedAttributes = savedAttributes;
94
- this._pendingAttributes = null; // Clear pending attributes
956
+ return this.GetFieldByName(fieldName);
95
957
  }
96
- catch (error) {
97
- LogError(`Error saving ArtifactVersionAttribute records: ${error instanceof Error ? error.message : error}`);
98
- // Don't fail the save if attribute creation fails
958
+ catch {
959
+ return undefined;
99
960
  }
100
961
  }
101
- return saveResult;
962
+ return undefined;
102
963
  }
103
964
  /**
104
965
  * Calculates SHA-256 hash of content
@@ -116,9 +977,10 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
116
977
  if (!this.Content) {
117
978
  return; // Nothing to extract
118
979
  }
119
- // Load the parent Artifact to get TypeID
120
- // Use the entity's provider instead of creating new Metadata instance
121
- const md = this.ProviderToUse;
980
+ const md = resolveMetadataProvider(this.ProviderToUse, this.ContextCurrentUser);
981
+ if (!md) {
982
+ return;
983
+ }
122
984
  const artifact = await md.GetEntityObject('MJ: Artifacts', this.ContextCurrentUser);
123
985
  const loadedArtifact = await artifact.Load(this.ArtifactID);
124
986
  if (!loadedArtifact) {
@@ -151,9 +1013,6 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
151
1013
  if (descriptionValue !== null && typeof descriptionValue === 'string') {
152
1014
  this.Description = descriptionValue;
153
1015
  }
154
- // We need to save the ArtifactVersion first to get an ID before saving attributes
155
- // So we'll do this in a post-save hook. For now, store the extraction result
156
- // so we can save attributes after the main save completes
157
1016
  this._pendingAttributes = extractionResult.attributes;
158
1017
  }
159
1018
  /**
@@ -170,19 +1029,21 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
170
1029
  if (!attributes || attributes.length === 0) {
171
1030
  return [];
172
1031
  }
173
- // Use the entity's provider instead of creating new Metadata instance
174
- const md = this.ProviderToUse;
1032
+ const md = resolveMetadataProvider(this.ProviderToUse, this.ContextCurrentUser);
1033
+ if (!md) {
1034
+ return [];
1035
+ }
175
1036
  const operations = [];
176
1037
  const savedAttributes = [];
177
1038
  // Load existing attributes for this version
178
1039
  const rv = new RunView(this.RunViewProviderToUse);
179
1040
  const existingAttrsResult = await rv.RunView({
180
1041
  EntityName: 'MJ: Artifact Version Attributes',
181
- ExtraFilter: `ArtifactVersionID='${this.ID}'`,
1042
+ ExtraFilter: `ArtifactVersionID='${EscapeSQLString(this.ID)}'`,
182
1043
  ResultType: 'entity_object'
183
1044
  }, this.ContextCurrentUser);
184
- const existingAttrs = existingAttrsResult?.Success ? (existingAttrsResult.Results || []) : [];
185
- const existingAttrMap = new Map(existingAttrs.map(attr => [attr.Name, attr]));
1045
+ const existingAttrs = existingAttrsResult?.Success ? existingAttrsResult.Results || [] : [];
1046
+ const existingAttrMap = new Map(existingAttrs.map((attr) => [attr.Name, attr]));
186
1047
  // Serialize attributes for storage
187
1048
  const serialized = ArtifactExtractor.SerializeForStorage(attributes);
188
1049
  // Track which attributes we've processed
@@ -198,11 +1059,17 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
198
1059
  }
199
1060
  continue;
200
1061
  }
1062
+ const stdProp = attrData.standardProperty === 'name' ||
1063
+ attrData.standardProperty === 'description' ||
1064
+ attrData.standardProperty === 'displayMarkdown' ||
1065
+ attrData.standardProperty === 'displayHtml'
1066
+ ? attrData.standardProperty
1067
+ : null;
201
1068
  // Update existing attribute
202
1069
  if (existingAttr) {
203
1070
  existingAttr.Type = attrData.type;
204
1071
  existingAttr.Value = attrData.value;
205
- existingAttr.StandardProperty = attrData.standardProperty || null;
1072
+ existingAttr.StandardProperty = stdProp;
206
1073
  operations.push(existingAttr.Save());
207
1074
  savedAttributes.push(existingAttr);
208
1075
  }
@@ -214,7 +1081,7 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
214
1081
  newAttr.Name = attrData.name;
215
1082
  newAttr.Type = attrData.type;
216
1083
  newAttr.Value = attrData.value;
217
- newAttr.StandardProperty = attrData.standardProperty || null;
1084
+ newAttr.StandardProperty = stdProp;
218
1085
  operations.push(newAttr.Save());
219
1086
  savedAttributes.push(newAttr);
220
1087
  }
@@ -237,8 +1104,10 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
237
1104
  */
238
1105
  async LoadArtifactTypeHierarchy(typeId) {
239
1106
  const hierarchy = [];
240
- // Use the entity's provider instead of creating new Metadata instance
241
- const md = this.ProviderToUse;
1107
+ const md = resolveMetadataProvider(this.ProviderToUse, this.ContextCurrentUser);
1108
+ if (!md) {
1109
+ return hierarchy;
1110
+ }
242
1111
  let currentTypeId = typeId;
243
1112
  // Walk up the hierarchy (max 10 levels to prevent infinite loops)
244
1113
  let maxDepth = 10;
@@ -254,9 +1123,19 @@ let MJArtifactVersionEntityServer = class MJArtifactVersionEntityServer extends
254
1123
  }
255
1124
  return hierarchy;
256
1125
  }
1126
+ recordPermissionFailure(type, message) {
1127
+ const res = new BaseEntityResult();
1128
+ res.Success = false;
1129
+ res.Type = type;
1130
+ res.StartedAt = new Date();
1131
+ res.EndedAt = new Date();
1132
+ res.Message = message;
1133
+ this.ResultHistory.push(res);
1134
+ return false;
1135
+ }
257
1136
  };
258
1137
  MJArtifactVersionEntityServer = __decorate([
259
- RegisterClass(BaseEntity, "MJ: Artifact Versions")
1138
+ RegisterClass(BaseEntity, 'MJ: Artifact Versions')
260
1139
  ], MJArtifactVersionEntityServer);
261
1140
  export { MJArtifactVersionEntityServer };
262
1141
  //# sourceMappingURL=MJArtifactVersionEntityServer.server.js.map