@memberjunction/core 6.2.2 → 6.3.0-edge.1

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 (152) hide show
  1. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  2. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  3. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  4. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  5. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  6. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  7. package/dist/generic/appCapabilityRegistry.js +212 -0
  8. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  9. package/dist/generic/baseEngine.d.ts +108 -3
  10. package/dist/generic/baseEngine.d.ts.map +1 -1
  11. package/dist/generic/baseEngine.js +891 -122
  12. package/dist/generic/baseEngine.js.map +1 -1
  13. package/dist/generic/baseEngineRegistry.d.ts +8 -0
  14. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  15. package/dist/generic/baseEngineRegistry.js +36 -11
  16. package/dist/generic/baseEngineRegistry.js.map +1 -1
  17. package/dist/generic/baseEntity.d.ts +155 -3
  18. package/dist/generic/baseEntity.d.ts.map +1 -1
  19. package/dist/generic/baseEntity.js +1146 -74
  20. package/dist/generic/baseEntity.js.map +1 -1
  21. package/dist/generic/baseRemotableOperation.d.ts +32 -0
  22. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  23. package/dist/generic/baseRemotableOperation.js +29 -0
  24. package/dist/generic/baseRemotableOperation.js.map +1 -1
  25. package/dist/generic/compositeKey.d.ts.map +1 -1
  26. package/dist/generic/compositeKey.js +3 -1
  27. package/dist/generic/compositeKey.js.map +1 -1
  28. package/dist/generic/constraintErrorRedaction.d.ts +26 -0
  29. package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
  30. package/dist/generic/constraintErrorRedaction.js +166 -0
  31. package/dist/generic/constraintErrorRedaction.js.map +1 -0
  32. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  33. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  34. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  35. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  36. package/dist/generic/dataHooks.d.ts +41 -4
  37. package/dist/generic/dataHooks.d.ts.map +1 -1
  38. package/dist/generic/dataHooks.js +82 -0
  39. package/dist/generic/dataHooks.js.map +1 -1
  40. package/dist/generic/databaseProviderBase.d.ts +96 -1
  41. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  42. package/dist/generic/databaseProviderBase.js +414 -44
  43. package/dist/generic/databaseProviderBase.js.map +1 -1
  44. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  45. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  46. package/dist/generic/documentNumberingEngine.js +739 -0
  47. package/dist/generic/documentNumberingEngine.js.map +1 -0
  48. package/dist/generic/entityInfo.d.ts +152 -8
  49. package/dist/generic/entityInfo.d.ts.map +1 -1
  50. package/dist/generic/entityInfo.js +507 -71
  51. package/dist/generic/entityInfo.js.map +1 -1
  52. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  53. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  54. package/dist/generic/entityLifecyclePolicy.js +708 -0
  55. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  56. package/dist/generic/entitySavePlan.d.ts +6 -0
  57. package/dist/generic/entitySavePlan.d.ts.map +1 -1
  58. package/dist/generic/entitySavePlan.js +145 -1
  59. package/dist/generic/entitySavePlan.js.map +1 -1
  60. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  61. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  62. package/dist/generic/entitySubtypeDriver.js +26 -0
  63. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  64. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  65. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  66. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  67. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  68. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  69. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  70. package/dist/generic/filters/compositeFilter.js +127 -12
  71. package/dist/generic/filters/compositeFilter.js.map +1 -1
  72. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  73. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  74. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  75. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  76. package/dist/generic/filters/filter.types.d.ts +5 -2
  77. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  78. package/dist/generic/filters/filter.types.js +4 -1
  79. package/dist/generic/filters/filter.types.js.map +1 -1
  80. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  81. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  82. package/dist/generic/filters/filterBuilder.js +104 -0
  83. package/dist/generic/filters/filterBuilder.js.map +1 -0
  84. package/dist/generic/filters/index.d.ts +2 -0
  85. package/dist/generic/filters/index.d.ts.map +1 -1
  86. package/dist/generic/filters/index.js +2 -0
  87. package/dist/generic/filters/index.js.map +1 -1
  88. package/dist/generic/interfaces.d.ts +125 -19
  89. package/dist/generic/interfaces.d.ts.map +1 -1
  90. package/dist/generic/interfaces.js +9 -10
  91. package/dist/generic/interfaces.js.map +1 -1
  92. package/dist/generic/localCacheManager.d.ts +54 -14
  93. package/dist/generic/localCacheManager.d.ts.map +1 -1
  94. package/dist/generic/localCacheManager.js +450 -106
  95. package/dist/generic/localCacheManager.js.map +1 -1
  96. package/dist/generic/metadata.d.ts +7 -5
  97. package/dist/generic/metadata.d.ts.map +1 -1
  98. package/dist/generic/metadata.js +29 -10
  99. package/dist/generic/metadata.js.map +1 -1
  100. package/dist/generic/providerBase.d.ts +405 -45
  101. package/dist/generic/providerBase.d.ts.map +1 -1
  102. package/dist/generic/providerBase.js +1107 -200
  103. package/dist/generic/providerBase.js.map +1 -1
  104. package/dist/generic/queryInfo.d.ts +5 -0
  105. package/dist/generic/queryInfo.d.ts.map +1 -1
  106. package/dist/generic/queryInfo.js +5 -0
  107. package/dist/generic/queryInfo.js.map +1 -1
  108. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  109. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  110. package/dist/generic/queryResultEnricher.d.ts +4 -1
  111. package/dist/generic/queryResultEnricher.d.ts.map +1 -1
  112. package/dist/generic/queryResultEnricher.js.map +1 -1
  113. package/dist/generic/queryTemplateContext.d.ts.map +1 -1
  114. package/dist/generic/queryTemplateContext.js +38 -3
  115. package/dist/generic/queryTemplateContext.js.map +1 -1
  116. package/dist/generic/relatedRecordCollection.d.ts +20 -0
  117. package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
  118. package/dist/generic/relatedRecordCollection.js +257 -22
  119. package/dist/generic/relatedRecordCollection.js.map +1 -1
  120. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  121. package/dist/generic/remoteOperationDispatch.js +13 -1
  122. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  123. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  124. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  125. package/dist/generic/saveEntityGraphOperation.js +8 -0
  126. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  127. package/dist/generic/securityInfo.d.ts +49 -2
  128. package/dist/generic/securityInfo.d.ts.map +1 -1
  129. package/dist/generic/securityInfo.js +139 -12
  130. package/dist/generic/securityInfo.js.map +1 -1
  131. package/dist/generic/telemetryManager.d.ts +40 -4
  132. package/dist/generic/telemetryManager.d.ts.map +1 -1
  133. package/dist/generic/telemetryManager.js +68 -15
  134. package/dist/generic/telemetryManager.js.map +1 -1
  135. package/dist/generic/transactionGroup.d.ts +66 -23
  136. package/dist/generic/transactionGroup.d.ts.map +1 -1
  137. package/dist/generic/transactionGroup.js +225 -57
  138. package/dist/generic/transactionGroup.js.map +1 -1
  139. package/dist/generic/util.d.ts.map +1 -1
  140. package/dist/generic/util.js +9 -3
  141. package/dist/generic/util.js.map +1 -1
  142. package/dist/index.d.ts +6 -0
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.js +6 -0
  145. package/dist/index.js.map +1 -1
  146. package/dist/tsconfig.tsbuildinfo +1 -0
  147. package/dist/views/runView.d.ts +61 -0
  148. package/dist/views/runView.d.ts.map +1 -1
  149. package/dist/views/runView.js +154 -3
  150. package/dist/views/runView.js.map +1 -1
  151. package/package.json +3 -3
  152. package/readme.md +6 -5
@@ -9,9 +9,13 @@ import { CompositeKey } from "./compositeKey.js";
9
9
  import { LogError } from "./logging.js";
10
10
  import { LocalCacheManager } from "./localCacheManager.js";
11
11
  import { AssertClientInputWritableForUser } from "./entityValueFieldSecurity.js";
12
+ import { SaveErrorMessageForUser } from "./constraintErrorRedaction.js";
12
13
  import { CanonicalPrimaryKeyValue } from "./util.js";
13
- import { FormatBinaryChangeValue, ScanSQLForScreening, SQLExpressionValidator, uuidv4, EscapeSQLString } from "@memberjunction/global";
14
+ import { FormatBinaryChangeValue, ScanSQLForScreening, SQLExpressionValidator, uuidv4, ValidationResult, EscapeSQLString } from "@memberjunction/global";
14
15
  import { GetDialect } from "@memberjunction/sql-dialect";
16
+ import { EntityLifecyclePolicyEngine } from "./entityLifecyclePolicy.js";
17
+ import { DocumentNumberingEngine } from "./documentNumberingEngine.js";
18
+ import { CrossEntityPolicyEngine } from "./crossEntityPolicyEngine.js";
15
19
  // Re-export PlatformSQL types from their canonical location for backward compatibility
16
20
  export { IsPlatformSQL } from "./platformSQL.js";
17
21
  /**
@@ -27,11 +31,44 @@ export { IsPlatformSQL } from "./platformSQL.js";
27
31
  export class DatabaseProviderBase extends ProviderBase {
28
32
  constructor() {
29
33
  super(...arguments);
34
+ this._providerInstanceId = DatabaseProviderBase._nextProviderInstanceId++;
35
+ this._transactionEpoch = 0;
36
+ this._detachedCoalescedTasks = new Map();
37
+ this._detachedCoalesceScheduled = false;
30
38
  this._dialect = null;
31
39
  /**************************************************************************/
32
40
  // END ---- Record Duplicates & Merge
33
41
  /**************************************************************************/
34
42
  }
43
+ static { this._nextProviderInstanceId = 1; }
44
+ /**
45
+ * Whether the calling async scope is part of this provider's ambient transaction.
46
+ * Subclasses with async-context transaction affinity (`GenericDatabaseProvider`) override this
47
+ * so concurrent callers on a shared provider do not share transaction-scoped caches.
48
+ */
49
+ IsCallerInAmbientTransaction() {
50
+ return this.IsInTransaction || this.CurrentTransactionDepth > 0;
51
+ }
52
+ /**
53
+ * Unique cache key identifying this provider's current active transaction epoch, or `null` when
54
+ * no entity/physical transaction is open for the calling async scope. Used by
55
+ * {@link CrossEntityPolicyEngine} to memoize parent-record lookups across batch/graph saves and
56
+ * evict them cleanly on commit or rollback.
57
+ */
58
+ get TransactionScopeCacheKey() {
59
+ if (this.IsCallerInAmbientTransaction() && (this.IsInTransaction || this.CurrentTransactionDepth > 0)) {
60
+ return `tx:${this._providerInstanceId}:${this._transactionEpoch}`;
61
+ }
62
+ return null;
63
+ }
64
+ /**
65
+ * Advances this provider's transaction epoch and evicts any transaction-scoped
66
+ * {@link CrossEntityPolicyEngine} caches bound to it.
67
+ */
68
+ BumpTransactionEpoch() {
69
+ this._transactionEpoch++;
70
+ CrossEntityPolicyEngine.Instance.ClearProviderScope(this);
71
+ }
35
72
  /**
36
73
  * Server-side providers trust the local cache completely because it is
37
74
  * kept in perfect sync via BaseEntity save/delete events and cross-server
@@ -185,6 +222,44 @@ export class DatabaseProviderBase extends ProviderBase {
185
222
  CapturePostCommitToken() {
186
223
  return undefined;
187
224
  }
225
+ /**
226
+ * Enqueues post-commit work coalesced by `coalesceKey`.
227
+ *
228
+ * Outside an open transaction (on transactional providers) or on non-transactional providers,
229
+ * registrations sharing a `coalesceKey` within the same microtask turn collapse per `mode`
230
+ * (`'last-wins'` by default) before flushing once on a microtask. Inside a transaction,
231
+ * transactional providers bind each registration to the caller's ambient frame (or `token`)
232
+ * so rolled-back savepoints drop their entries cleanly while surviving entries coalesce at commit.
233
+ */
234
+ ScheduleAfterCommit(coalesceKey, task, description = 'post-commit task', token, mode = 'last-wins') {
235
+ if (!coalesceKey) {
236
+ this.RunAfterCommit(task, description, token);
237
+ return;
238
+ }
239
+ this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode);
240
+ }
241
+ /** Runs a detached post-commit task safely; transactional subclasses detach transaction affinity here. */
242
+ ExecuteDetachedPostCommitTask(task, description) {
243
+ void this.RunPostCommitTaskSafely(task, description);
244
+ }
245
+ /** Coalesces detached post-commit registrations onto a single microtask flush per turn. */
246
+ EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode) {
247
+ if (mode !== 'first-wins' || !this._detachedCoalescedTasks.has(coalesceKey)) {
248
+ this._detachedCoalescedTasks.set(coalesceKey, { Task: task, Description: description });
249
+ }
250
+ if (this._detachedCoalesceScheduled) {
251
+ return;
252
+ }
253
+ this._detachedCoalesceScheduled = true;
254
+ queueMicrotask(() => {
255
+ const entries = [...this._detachedCoalescedTasks.values()];
256
+ this._detachedCoalescedTasks.clear();
257
+ this._detachedCoalesceScheduled = false;
258
+ for (const entry of entries) {
259
+ this.ExecuteDetachedPostCommitTask(entry.Task, entry.Description);
260
+ }
261
+ });
262
+ }
188
263
  /**
189
264
  * Await one post-commit task, logging (never rethrowing) its failure. Shared by the immediate
190
265
  * path of {@link RunAfterCommit} and by subclasses that drain a queue after commit.
@@ -277,6 +352,14 @@ export class DatabaseProviderBase extends ProviderBase {
277
352
  }
278
353
  }
279
354
  finally {
355
+ if (!isNested || !settledAsCommit) {
356
+ if (typeof this.BumpTransactionEpoch === 'function') {
357
+ this.BumpTransactionEpoch();
358
+ }
359
+ else {
360
+ CrossEntityPolicyEngine.Instance.ClearProviderScope(this);
361
+ }
362
+ }
280
363
  await LocalCacheManager.Instance.EndEntityEventBatch(this, settledAsCommit);
281
364
  }
282
365
  };
@@ -1077,6 +1160,41 @@ export class DatabaseProviderBase extends ProviderBase {
1077
1160
  async ShouldEnlistSaveInTransaction(_entity, _user, _options, _isNewRecord) {
1078
1161
  return false;
1079
1162
  }
1163
+ /**
1164
+ * Returns true when an UPDATE on the direct `Save()` path should run {@link CheckUpdateConcurrency}
1165
+ * inside an {@link EntityTransactionScope} before executing the update SQL.
1166
+ *
1167
+ * Default: `false`. Overridden by `GenericDatabaseProvider` when `ConcurrencyCheck` is `'log'` or `'enforce'`.
1168
+ */
1169
+ ShouldCheckUpdateConcurrency(_entity, _options) {
1170
+ return false;
1171
+ }
1172
+ /**
1173
+ * Performs a locked row read and field-level concurrency check inside the save transaction scope
1174
+ * before the UPDATE statement runs.
1175
+ *
1176
+ * Returns `true` when the save should proceed, or `false` when the save is rejected (in `'enforce'`
1177
+ * mode, after populating `entityResult.Message`, `entityResult.ConcurrencyConflict`, and
1178
+ * `entityResult.Success = false`).
1179
+ */
1180
+ async CheckUpdateConcurrency(_entity, _user, _options, _entityResult) {
1181
+ return true;
1182
+ }
1183
+ /**
1184
+ * The `TransactionGroup` counterpart of {@link CheckUpdateConcurrency}, called when an UPDATE is
1185
+ * queued into a group. The values the check compares (each changed field's baseline and new
1186
+ * value) are captured now, when the save's SQL is generated; the returned function performs the
1187
+ * locked row read and comparison later, inside the group's transaction before any of the
1188
+ * group's statements run.
1189
+ *
1190
+ * The returned function resolves `true` when the save may proceed, or `false` when it is
1191
+ * rejected (after populating `entityResult` the same way {@link CheckUpdateConcurrency} does).
1192
+ *
1193
+ * Default: `null`, meaning no check (and no extra work at submit).
1194
+ */
1195
+ PrepareQueuedUpdateConcurrencyCheck(_entity, _user, _options, _entityResult) {
1196
+ return null;
1197
+ }
1080
1198
  /**
1081
1199
  * Awaited immediately after the save SQL succeeds (inside direct `Save()`'s
1082
1200
  * {@link EntityTransactionScope} before commit, or inside a `TransactionGroup` item's completion
@@ -1600,6 +1718,9 @@ export class DatabaseProviderBase extends ProviderBase {
1600
1718
  */
1601
1719
  async Save(entity, user, options) {
1602
1720
  const entityResult = new BaseEntityResult();
1721
+ let autoNumberTxScope = null;
1722
+ let autoNumberTxCommitted = false;
1723
+ let assignedAutoNumberFields = [];
1603
1724
  // Each suspend is matched by exactly one resume, whichever path (success, transaction
1604
1725
  // callback, or catch) gets there first: providers count suspensions, so a stray resume
1605
1726
  // would re-enable refresh while another save is still running.
@@ -1654,8 +1775,27 @@ export class DatabaseProviderBase extends ProviderBase {
1654
1775
  // EntityField.Value does not assert active status, so no suppression is needed.
1655
1776
  entityResult.OriginalValues = entity.Fields.map((f) => ({ FieldName: f.Name, Value: f.Value }));
1656
1777
  entity.RegisterResultHistoryEntry(entityResult);
1657
- // Step 2: Validation hook
1778
+ // Step 2: Validation hook (lifecycle gates, state machine, auto-number, cross-entity policies, & provider hook)
1658
1779
  if (!bReplay) {
1780
+ const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(entity, bNewRecord ? 'Create' : 'Update', user, true);
1781
+ if (gateError) {
1782
+ entityResult.Success = false;
1783
+ entityResult.EndedAt = new Date();
1784
+ entityResult.Message = gateError;
1785
+ return false;
1786
+ }
1787
+ const lifecycleValidation = new ValidationResult();
1788
+ lifecycleValidation.Success = true;
1789
+ EntityLifecyclePolicyEngine.Instance.ValidateLifecycleOnEntity(entity, user, lifecycleValidation);
1790
+ DocumentNumberingEngine.Instance.ValidateAutoNumberFields(entity, lifecycleValidation);
1791
+ if (!lifecycleValidation.Success) {
1792
+ entityResult.Success = false;
1793
+ entityResult.EndedAt = new Date();
1794
+ entityResult.Errors.push(...lifecycleValidation.Errors);
1795
+ entityResult.Message = lifecycleValidation.Errors.map((e) => e.Message).join('; ');
1796
+ entityResult.MessageIncludesErrors = true;
1797
+ return false;
1798
+ }
1659
1799
  const validationMessage = await this.OnValidateBeforeSave(entity, user, saveContext);
1660
1800
  if (validationMessage) {
1661
1801
  entityResult.Success = false;
@@ -1687,10 +1827,40 @@ export class DatabaseProviderBase extends ProviderBase {
1687
1827
  }
1688
1828
  }
1689
1829
  }
1830
+ // Snapshot field values before Step 3 (before-save hooks / cross-entity policy / auto-numbering).
1831
+ // If no hook mutates any field value on a new record, the 2nd CheckCreateRLS check at step 3b
1832
+ // is redundant with step 2b and can be safely skipped.
1833
+ const preHookFieldSnapshot = (!bReplay && bNewRecord)
1834
+ ? this.CaptureEntityFieldSnapshot(entity)
1835
+ : null;
1690
1836
  // Step 3: Before-save hook (entity actions, AI actions)
1691
1837
  if (!bReplay) {
1692
1838
  await this.OnBeforeSaveExecute(entity, user, options, saveContext);
1693
1839
  }
1840
+ // Step 3a: Cross-entity policy evaluation (after RLS pre-check and before-save hooks;
1841
+ // TransactionGroup items defer batch evaluation to TransactionGroupBase.Submit())
1842
+ if (!bReplay && !entity.TransactionGroup) {
1843
+ const crossPolicyError = await CrossEntityPolicyEngine.Instance.EnforceBeforeSave(entity, user, this, saveContext);
1844
+ if (crossPolicyError) {
1845
+ entityResult.Success = false;
1846
+ entityResult.EndedAt = new Date();
1847
+ entityResult.Message = crossPolicyError;
1848
+ return false;
1849
+ }
1850
+ }
1851
+ // Step 3a-ii: Scoped document auto-numbering allocation (transactional & gap-free).
1852
+ // For TransactionGroup saves, allocation is deferred to TransactionItem.PrepareBeforeSubmit
1853
+ // inside BeginGroupTransaction() so sequence locks and rollback match the group transaction.
1854
+ const deferAutoNumberToGroup = !bReplay &&
1855
+ bNewRecord &&
1856
+ Boolean(entity.TransactionGroup) &&
1857
+ DocumentNumberingEngine.Instance.NeedsAllocation(entity);
1858
+ if (!bReplay && bNewRecord && !entity.TransactionGroup && DocumentNumberingEngine.Instance.NeedsAllocation(entity)) {
1859
+ if (DocumentNumberingEngine.Instance.RequiresTransactionalSave(entity.EntityInfo)) {
1860
+ autoNumberTxScope = await this.BeginEntityTransaction();
1861
+ }
1862
+ assignedAutoNumberFields = await DocumentNumberingEngine.Instance.AllocateAndAssignForEntity(entity, this, user);
1863
+ }
1694
1864
  // Step 3b: Post-image RLS check. The pre-image/pre-hook check at step 2b
1695
1865
  // validates values as they exist BEFORE the before-save hooks run, which cannot
1696
1866
  // catch a hook that mutates a filter-referenced field afterward (e.g. reassigning
@@ -1698,22 +1868,19 @@ export class DatabaseProviderBase extends ProviderBase {
1698
1868
  // escalation, not just a leak). This runs AFTER the before-save hooks by design:
1699
1869
  // hooks can mutate field values, including filter-referenced ones, and the
1700
1870
  // authorization boundary must cover the values that actually get written.
1701
- // Nothing existing moves — step 2b and step 3 keep their order; this is a new,
1702
- // additive step. Applies to BOTH creates and updates: a before-save hook can
1703
- // move a brand-new record's values outside the Create filter just as easily as
1704
- // it can move an existing row outside the Update filter, so CheckCreateRLS is
1705
- // called a second time here (idempotent, side-effect-free) rather than only
1706
- // gating updates. Post-image failure gets a specific message (unlike step 2b's
1707
- // deliberately generic one on the update path): the caller demonstrably had
1708
- // access to the pre-hook state, so the diagnostic leaks nothing new.
1871
+ // When before-save hooks leave field values and dirty flags completely unchanged,
1872
+ // the second CheckCreateRLS evaluation is redundant with step 2b and safely skipped.
1709
1873
  if (!bReplay) {
1710
1874
  if (bNewRecord) {
1711
- const postHookCreatePass = await this.CheckCreateRLS(entity, user);
1712
- if (!postHookCreatePass) {
1713
- entityResult.Success = false;
1714
- entityResult.EndedAt = new Date();
1715
- entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
1716
- throw new Error(entityResult.Message);
1875
+ const fieldsMutated = preHookFieldSnapshot === null || this.HasEntityFieldStateMutated(entity, preHookFieldSnapshot);
1876
+ if (fieldsMutated) {
1877
+ const postHookCreatePass = await this.CheckCreateRLS(entity, user);
1878
+ if (!postHookCreatePass) {
1879
+ entityResult.Success = false;
1880
+ entityResult.EndedAt = new Date();
1881
+ entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
1882
+ throw new Error(entityResult.Message);
1883
+ }
1717
1884
  }
1718
1885
  }
1719
1886
  else {
@@ -1726,28 +1893,36 @@ export class DatabaseProviderBase extends ProviderBase {
1726
1893
  }
1727
1894
  }
1728
1895
  }
1729
- // Step 4: Generate provider-specific SQL
1730
- const sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
1731
- const effectiveReturnMode = options?.SaveReturnMode ?? entity.EntityInfo.SaveReturnMode;
1732
- // Snapshot the entity's in-memory field values at the exact point SQL parameters were bound
1733
- // (before awaiting ExecuteSQL). If the caller mutates the entity in memory while an async
1734
- // save is in flight (e.g. BaseEntitySaveQueue pipelining an INSERT + UPDATE), merging
1735
- // post-await entity.GetAll() would falsely mark those in-flight mutations as clean/saved.
1736
- const preSaveValues = effectiveReturnMode === 'datestamps_only'
1737
- ? entity.GetAll()
1738
- : undefined;
1739
- if (preSaveValues && bNewRecord) {
1740
- // On a new record saved with 'datestamps_only', the SP does not query BaseView,
1741
- // so virtual non-PK fields (e.g. joined name columns) that were never set stay
1742
- // null. Omit them from preSaveValues so finalizeSave marks them NotLoaded=true.
1743
- for (const f of entity.EntityInfo.Fields) {
1744
- if (f.IsVirtual && !f.IsPrimaryKey && (preSaveValues[f.Name] === null || preSaveValues[f.Name] === undefined)) {
1745
- delete preSaveValues[f.Name];
1896
+ const capturePreSaveValues = () => {
1897
+ const effectiveReturnMode = options?.SaveReturnMode ?? entity.EntityInfo.SaveReturnMode;
1898
+ // Snapshot the entity's in-memory field values at the exact point SQL parameters were bound
1899
+ // (before awaiting ExecuteSQL). If the caller mutates the entity in memory while an async
1900
+ // save is in flight (e.g. BaseEntitySaveQueue pipelining an INSERT + UPDATE), merging
1901
+ // post-await entity.GetAll() would falsely mark those in-flight mutations as clean/saved.
1902
+ const snapshot = effectiveReturnMode === 'datestamps_only'
1903
+ ? entity.GetAll()
1904
+ : undefined;
1905
+ if (snapshot && bNewRecord) {
1906
+ // On a new record saved with 'datestamps_only', the SP does not query BaseView,
1907
+ // so virtual non-PK fields (e.g. joined name columns) that were never set stay
1908
+ // null. Omit them from preSaveValues so finalizeSave marks them NotLoaded=true.
1909
+ for (const f of entity.EntityInfo.Fields) {
1910
+ if (f.IsVirtual && !f.IsPrimaryKey && (snapshot[f.Name] === null || snapshot[f.Name] === undefined)) {
1911
+ delete snapshot[f.Name];
1912
+ }
1746
1913
  }
1747
1914
  }
1748
- }
1915
+ return snapshot;
1916
+ };
1749
1917
  if (entity.TransactionGroup && !bReplay) {
1750
1918
  // ---- Transaction Group path ----
1919
+ // Captured before GenerateSaveSQL, matching the direct path, which checks
1920
+ // before it generates the update.
1921
+ const concurrencyCheck = bNewRecord
1922
+ ? null
1923
+ : this.PrepareQueuedUpdateConcurrencyCheck(entity, user, options, entityResult);
1924
+ let sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
1925
+ const preSaveValues = capturePreSaveValues();
1751
1926
  entity.RaiseReadyForTransaction();
1752
1927
  transactionReadyRaised = true;
1753
1928
  suspendRefresh();
@@ -1758,7 +1933,7 @@ export class DatabaseProviderBase extends ProviderBase {
1758
1933
  configurable: true,
1759
1934
  });
1760
1935
  extraData.entityName = entity.EntityInfo.Name;
1761
- entity.TransactionGroup.AddTransaction(new TransactionItem(entity, entityResult.Type === 'create' ? 'Create' : 'Update', sqlDetails.literalSQL ?? sqlDetails.fullSQL, sqlDetails.literalSQL ? null : (sqlDetails.parameters ?? null), extraData, async (transactionResult, success) => {
1936
+ const txItem = new TransactionItem(entity, entityResult.Type === 'create' ? 'Create' : 'Update', sqlDetails.literalSQL ?? sqlDetails.fullSQL, sqlDetails.literalSQL ? null : (sqlDetails.parameters ?? null), extraData, async (transactionResult, success) => {
1762
1937
  resumeRefresh();
1763
1938
  entityResult.EndedAt = new Date();
1764
1939
  if (success && transactionResult) {
@@ -1796,6 +1971,7 @@ export class DatabaseProviderBase extends ProviderBase {
1796
1971
  if (patches) {
1797
1972
  Object.assign(transactionResult, patches);
1798
1973
  }
1974
+ CrossEntityPolicyEngine.Instance.NotifyEntityMutated(this, entity, bNewRecord ? 'Create' : 'Update');
1799
1975
  this.OnAfterSaveExecute(entity, user, options, saveContext);
1800
1976
  entityResult.Success = true;
1801
1977
  entityResult.NewValues = this.MapTransactionResultToNewValues(transactionResult);
@@ -1803,21 +1979,69 @@ export class DatabaseProviderBase extends ProviderBase {
1803
1979
  else {
1804
1980
  entityResult.Success = false;
1805
1981
  if (!entityResult.Message) {
1982
+ // The group's failure carries the database message of whichever
1983
+ // item failed, so it gets the same redaction as a direct save.
1806
1984
  entityResult.Message =
1807
- transactionResult instanceof Error ? transactionResult.message : 'Transaction Failed';
1985
+ transactionResult instanceof Error
1986
+ ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user)
1987
+ : 'Transaction Failed';
1808
1988
  }
1809
1989
  }
1810
- }));
1990
+ });
1991
+ if (deferAutoNumberToGroup) {
1992
+ let groupAssignedFields = [];
1993
+ txItem.PrepareBeforeSubmit = async () => {
1994
+ groupAssignedFields = await DocumentNumberingEngine.Instance.AllocateAndAssignForEntity(entity, this, user);
1995
+ sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
1996
+ txItem.Instruction = sqlDetails.literalSQL ?? sqlDetails.fullSQL;
1997
+ txItem.Vars = sqlDetails.literalSQL ? null : (sqlDetails.parameters ?? null);
1998
+ if (preSaveValues) {
1999
+ for (const fName of groupAssignedFields) {
2000
+ preSaveValues[fName] = entity.Get(fName);
2001
+ }
2002
+ }
2003
+ };
2004
+ txItem.RevertAfterRollback = () => {
2005
+ if (groupAssignedFields.length > 0) {
2006
+ DocumentNumberingEngine.Instance.RevertAssignedNumbers(entity, groupAssignedFields);
2007
+ groupAssignedFields = [];
2008
+ }
2009
+ };
2010
+ }
2011
+ if (concurrencyCheck) {
2012
+ txItem.CheckBeforeSubmit = concurrencyCheck;
2013
+ }
2014
+ entity.TransactionGroup.AddTransaction(txItem);
1811
2015
  return true;
1812
2016
  }
1813
2017
  else {
1814
2018
  // ---- Direct execution path ----
1815
2019
  const enlistInTx = !bReplay && await this.ShouldEnlistSaveInTransaction(entity, user, options, bNewRecord);
1816
- const saveTxScope = enlistInTx ? await this.BeginEntityTransaction() : null;
2020
+ const checkConcurrencyInTx = !bReplay && !bNewRecord && this.ShouldCheckUpdateConcurrency(entity, options);
2021
+ const saveTxScope = (enlistInTx || checkConcurrencyInTx) && !autoNumberTxScope ? await this.BeginEntityTransaction() : null;
1817
2022
  let saveTxCommitted = false;
1818
2023
  suspendRefresh();
1819
2024
  let result;
2025
+ let sqlDetails;
2026
+ let preSaveValues;
1820
2027
  try {
2028
+ if (checkConcurrencyInTx) {
2029
+ const concurrencyPassed = await this.CheckUpdateConcurrency(entity, user, options, entityResult);
2030
+ if (!concurrencyPassed) {
2031
+ resumeRefresh();
2032
+ if (saveTxScope && !saveTxCommitted) {
2033
+ await saveTxScope.Rollback();
2034
+ saveTxCommitted = true;
2035
+ }
2036
+ if (autoNumberTxScope && !autoNumberTxCommitted) {
2037
+ await autoNumberTxScope.Rollback();
2038
+ autoNumberTxCommitted = true;
2039
+ }
2040
+ return false;
2041
+ }
2042
+ }
2043
+ sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
2044
+ preSaveValues = capturePreSaveValues();
1821
2045
  if (bReplay) {
1822
2046
  result = [entity.GetAll()];
1823
2047
  }
@@ -1849,6 +2073,10 @@ export class DatabaseProviderBase extends ProviderBase {
1849
2073
  await saveTxScope.Commit();
1850
2074
  saveTxCommitted = true;
1851
2075
  }
2076
+ if (autoNumberTxScope) {
2077
+ await autoNumberTxScope.Commit();
2078
+ autoNumberTxCommitted = true;
2079
+ }
1852
2080
  }
1853
2081
  else {
1854
2082
  if (bNewRecord)
@@ -1863,6 +2091,7 @@ export class DatabaseProviderBase extends ProviderBase {
1863
2091
  }
1864
2092
  throw innerErr;
1865
2093
  }
2094
+ CrossEntityPolicyEngine.Instance.NotifyEntityMutated(this, entity, bNewRecord ? 'Create' : 'Update');
1866
2095
  this.OnAfterSaveExecute(entity, user, options, saveContext);
1867
2096
  entityResult.Success = true;
1868
2097
  // In 'datestamps_only' mode, the SP/query returned only the PK and
@@ -1896,9 +2125,23 @@ export class DatabaseProviderBase extends ProviderBase {
1896
2125
  }
1897
2126
  }
1898
2127
  catch (e) {
2128
+ if (autoNumberTxScope && !autoNumberTxCommitted) {
2129
+ try {
2130
+ await autoNumberTxScope.Rollback();
2131
+ }
2132
+ catch (rbErr) {
2133
+ LogError(rbErr);
2134
+ }
2135
+ }
2136
+ if (assignedAutoNumberFields.length > 0 && !autoNumberTxCommitted) {
2137
+ DocumentNumberingEngine.Instance.RevertAssignedNumbers(entity, assignedAutoNumberFields);
2138
+ }
1899
2139
  resumeRefresh();
1900
2140
  entityResult.EndedAt = new Date();
1901
- entityResult.Message = e.message;
2141
+ // A constraint error can echo column values, including the stored value of a column
2142
+ // this user may not read (a unique index spanning it). The caller gets the message
2143
+ // without them; the server log keeps the original.
2144
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
1902
2145
  LogError(e);
1903
2146
  throw e;
1904
2147
  }
@@ -1945,6 +2188,15 @@ export class DatabaseProviderBase extends ProviderBase {
1945
2188
  Value: f.Value,
1946
2189
  }));
1947
2190
  entity.RegisterResultHistoryEntry(entityResult);
2191
+ if (!bReplay) {
2192
+ const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(entity, 'Delete', user, true);
2193
+ if (gateError) {
2194
+ entityResult.Success = false;
2195
+ entityResult.EndedAt = new Date();
2196
+ entityResult.Message = gateError;
2197
+ return false;
2198
+ }
2199
+ }
1948
2200
  // Generate provider-specific delete SQL
1949
2201
  const sqlDetails = this.GenerateDeleteSQL(entity, user, options);
1950
2202
  // Before-delete hooks
@@ -1961,6 +2213,17 @@ export class DatabaseProviderBase extends ProviderBase {
1961
2213
  throw new Error(entityResult.Message);
1962
2214
  }
1963
2215
  }
2216
+ // Cross-entity policy evaluation for Delete (after RLS and before-delete hooks;
2217
+ // TransactionGroup items defer batch evaluation to TransactionGroupBase.Submit())
2218
+ if (!bReplay && !entity.TransactionGroup) {
2219
+ const crossPolicyError = await CrossEntityPolicyEngine.Instance.EnforceBeforeDelete(entity, user, this);
2220
+ if (crossPolicyError) {
2221
+ entityResult.Success = false;
2222
+ entityResult.EndedAt = new Date();
2223
+ entityResult.Message = crossPolicyError;
2224
+ return false;
2225
+ }
2226
+ }
1964
2227
  if (entity.TransactionGroup && !bReplay) {
1965
2228
  // ---- Transaction Group path ----
1966
2229
  entity.RaiseReadyForTransaction();
@@ -1984,6 +2247,7 @@ export class DatabaseProviderBase extends ProviderBase {
1984
2247
  throw new Error(entityResult.Message ||
1985
2248
  `Failed to delete ${entity.EntityInfo.Name}: record not found or primary key mismatch`);
1986
2249
  }
2250
+ CrossEntityPolicyEngine.Instance.NotifyEntityMutated(this, entity, 'Delete');
1987
2251
  this.OnAfterDeleteExecute(entity, user, options);
1988
2252
  entityResult.NewValues = this.MapTransactionResultToNewValues(transactionResult);
1989
2253
  entityResult.Success = true;
@@ -1992,7 +2256,9 @@ export class DatabaseProviderBase extends ProviderBase {
1992
2256
  entityResult.Success = false;
1993
2257
  if (!entityResult.Message) {
1994
2258
  entityResult.Message =
1995
- transactionResult instanceof Error ? transactionResult.message : 'Transaction failed to commit';
2259
+ transactionResult instanceof Error
2260
+ ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user)
2261
+ : 'Transaction failed to commit';
1996
2262
  }
1997
2263
  }
1998
2264
  }));
@@ -2014,6 +2280,7 @@ export class DatabaseProviderBase extends ProviderBase {
2014
2280
  entityResult.Success = false;
2015
2281
  return false;
2016
2282
  }
2283
+ CrossEntityPolicyEngine.Instance.NotifyEntityMutated(this, entity, 'Delete');
2017
2284
  this.OnAfterDeleteExecute(entity, user, options);
2018
2285
  entityResult.EndedAt = new Date();
2019
2286
  return true;
@@ -2027,7 +2294,9 @@ export class DatabaseProviderBase extends ProviderBase {
2027
2294
  }
2028
2295
  catch (e) {
2029
2296
  LogError(e);
2030
- entityResult.Message = e.message;
2297
+ // A delete's SQL writes the full record to the audit trail, and a constraint error can
2298
+ // echo stored values, so the caller gets the same redaction as a failed save.
2299
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
2031
2300
  entityResult.Success = false;
2032
2301
  entityResult.EndedAt = new Date();
2033
2302
  return false;
@@ -2038,6 +2307,101 @@ export class DatabaseProviderBase extends ProviderBase {
2038
2307
  }
2039
2308
  }
2040
2309
  }
2310
+ /**
2311
+ * Captures an immutable snapshot of an entity's fields (name, value, dirty status)
2312
+ * so we can detect whether before-save hooks mutated any field (including in-place
2313
+ * Date, Uint8Array, or JSON object mutations and case-sensitive string changes).
2314
+ */
2315
+ CaptureEntityFieldSnapshot(entity) {
2316
+ return entity.Fields.map((f) => this.snapshotSingleFieldState(f.Name, f.Value, f.Dirty));
2317
+ }
2318
+ snapshotSingleFieldState(name, val, dirty) {
2319
+ if (val === null) {
2320
+ return { Name: name, Kind: 'primitive', PrimitiveValue: null, Dirty: dirty };
2321
+ }
2322
+ if (val === undefined) {
2323
+ return { Name: name, Kind: 'primitive', PrimitiveValue: undefined, Dirty: dirty };
2324
+ }
2325
+ if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
2326
+ return { Name: name, Kind: 'primitive', PrimitiveValue: val, Dirty: dirty };
2327
+ }
2328
+ if (val instanceof Date) {
2329
+ return { Name: name, Kind: 'date', DateMs: val.getTime(), Dirty: dirty };
2330
+ }
2331
+ if (val instanceof Uint8Array) {
2332
+ return { Name: name, Kind: 'bytes', BytesCopy: val.slice(), Dirty: dirty };
2333
+ }
2334
+ if (typeof val === 'object') {
2335
+ try {
2336
+ return { Name: name, Kind: 'json', SerializedJson: JSON.stringify(val), Dirty: dirty };
2337
+ }
2338
+ catch {
2339
+ return { Name: name, Kind: 'uncomparable', Dirty: dirty };
2340
+ }
2341
+ }
2342
+ return { Name: name, Kind: 'uncomparable', Dirty: dirty };
2343
+ }
2344
+ /**
2345
+ * Checks whether an entity's field values or dirty flags have mutated compared to a previous snapshot.
2346
+ */
2347
+ HasEntityFieldStateMutated(entity, snapshot) {
2348
+ const currentFields = entity.Fields;
2349
+ if (snapshot.length !== currentFields.length) {
2350
+ return true;
2351
+ }
2352
+ for (let i = 0; i < snapshot.length; i++) {
2353
+ const prev = snapshot[i];
2354
+ const curr = currentFields[i];
2355
+ if (prev.Name !== curr.Name || prev.Dirty !== curr.Dirty) {
2356
+ return true;
2357
+ }
2358
+ if (!this.matchesFieldSnapshot(prev, curr.Value)) {
2359
+ return true;
2360
+ }
2361
+ }
2362
+ return false;
2363
+ }
2364
+ matchesFieldSnapshot(prev, curr) {
2365
+ if (prev.Kind === 'uncomparable') {
2366
+ return false;
2367
+ }
2368
+ if (prev.Kind === 'primitive') {
2369
+ if (typeof prev.PrimitiveValue === 'number' && typeof curr === 'number' && Number.isNaN(prev.PrimitiveValue) && Number.isNaN(curr)) {
2370
+ return true;
2371
+ }
2372
+ return prev.PrimitiveValue === curr;
2373
+ }
2374
+ if (prev.Kind === 'date') {
2375
+ if (!(curr instanceof Date)) {
2376
+ return false;
2377
+ }
2378
+ const currMs = curr.getTime();
2379
+ return (Number.isNaN(prev.DateMs) && Number.isNaN(currMs)) || prev.DateMs === currMs;
2380
+ }
2381
+ if (prev.Kind === 'bytes') {
2382
+ if (!(curr instanceof Uint8Array) || !prev.BytesCopy || prev.BytesCopy.length !== curr.length) {
2383
+ return false;
2384
+ }
2385
+ for (let i = 0; i < curr.length; i++) {
2386
+ if (prev.BytesCopy[i] !== curr[i]) {
2387
+ return false;
2388
+ }
2389
+ }
2390
+ return true;
2391
+ }
2392
+ if (prev.Kind === 'json') {
2393
+ if (curr === null || typeof curr !== 'object' || curr instanceof Date || curr instanceof Uint8Array) {
2394
+ return false;
2395
+ }
2396
+ try {
2397
+ return prev.SerializedJson === JSON.stringify(curr);
2398
+ }
2399
+ catch {
2400
+ return false;
2401
+ }
2402
+ }
2403
+ return false;
2404
+ }
2041
2405
  /**************************************************************************/
2042
2406
  // END ---- Save/Delete Orchestration
2043
2407
  /**************************************************************************/
@@ -2231,8 +2595,11 @@ export class DatabaseProviderBase extends ProviderBase {
2231
2595
  * `DiffObjects`. Defaults to single quote.
2232
2596
  * @param cloneContext When non-null, populates `source='Clone'` and the
2233
2597
  * structured `changeContext` JSON payload.
2598
+ * @param skipFullRecordJSON When true (because the dialect builds `FullRecordJSON` in SQL
2599
+ * from the returned row), skips `EscapeQuotesInProperties` and `JSON.stringify` for
2600
+ * `fullRecordJSON`, returning `''`.
2234
2601
  */
2235
- BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext) {
2602
+ BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false) {
2236
2603
  if (restoreContext && cloneContext) {
2237
2604
  throw new Error('BuildRecordChangePayload: both restoreContext and cloneContext were provided; an operation cannot be both a restore and a clone');
2238
2605
  }
@@ -2241,8 +2608,11 @@ export class DatabaseProviderBase extends ProviderBase {
2241
2608
  const changesKeys = changes ? Object.keys(changes) : [];
2242
2609
  if (changesKeys.length === 0 && !isCreateOrDelete)
2243
2610
  return null;
2244
- const dataForFullJSON = newData ?? oldData;
2245
- const fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
2611
+ let fullRecordJSON = '';
2612
+ if (!skipFullRecordJSON) {
2613
+ const dataForFullJSON = newData ?? oldData;
2614
+ fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
2615
+ }
2246
2616
  const changesJSON = changes !== null ? JSON.stringify(changes) : '';
2247
2617
  const changesDescription = (oldData && newData)
2248
2618
  ? this.CreateUserDescriptionOfChanges(changes)