@memberjunction/core 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 (104) hide show
  1. package/dist/generic/QueryCache.d.ts +2 -2
  2. package/dist/generic/QueryCache.d.ts.map +1 -1
  3. package/dist/generic/QueryCache.js +12 -7
  4. package/dist/generic/QueryCache.js.map +1 -1
  5. package/dist/generic/baseEngine.d.ts +9 -0
  6. package/dist/generic/baseEngine.d.ts.map +1 -1
  7. package/dist/generic/baseEngine.js +23 -1
  8. package/dist/generic/baseEngine.js.map +1 -1
  9. package/dist/generic/baseEngineRegistry.d.ts +8 -0
  10. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  11. package/dist/generic/baseEngineRegistry.js +28 -10
  12. package/dist/generic/baseEngineRegistry.js.map +1 -1
  13. package/dist/generic/baseEntity.d.ts +69 -3
  14. package/dist/generic/baseEntity.d.ts.map +1 -1
  15. package/dist/generic/baseEntity.js +141 -53
  16. package/dist/generic/baseEntity.js.map +1 -1
  17. package/dist/generic/baseRemotableOperation.d.ts +17 -0
  18. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  19. package/dist/generic/baseRemotableOperation.js +18 -0
  20. package/dist/generic/baseRemotableOperation.js.map +1 -1
  21. package/dist/generic/constraintErrorRedaction.d.ts +26 -0
  22. package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
  23. package/dist/generic/constraintErrorRedaction.js +166 -0
  24. package/dist/generic/constraintErrorRedaction.js.map +1 -0
  25. package/dist/generic/dataHooks.d.ts +27 -3
  26. package/dist/generic/dataHooks.d.ts.map +1 -1
  27. package/dist/generic/dataHooks.js +82 -0
  28. package/dist/generic/dataHooks.js.map +1 -1
  29. package/dist/generic/databaseProviderBase.d.ts +69 -7
  30. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  31. package/dist/generic/databaseProviderBase.js +230 -38
  32. package/dist/generic/databaseProviderBase.js.map +1 -1
  33. package/dist/generic/entityInfo.d.ts +56 -6
  34. package/dist/generic/entityInfo.d.ts.map +1 -1
  35. package/dist/generic/entityInfo.js +200 -50
  36. package/dist/generic/entityInfo.js.map +1 -1
  37. package/dist/generic/entitySavePlan.d.ts +6 -0
  38. package/dist/generic/entitySavePlan.d.ts.map +1 -1
  39. package/dist/generic/entitySavePlan.js +145 -1
  40. package/dist/generic/entitySavePlan.js.map +1 -1
  41. package/dist/generic/entityValueFieldSecurity.d.ts.map +1 -1
  42. package/dist/generic/entityValueFieldSecurity.js +1 -0
  43. package/dist/generic/entityValueFieldSecurity.js.map +1 -1
  44. package/dist/generic/interfaces.d.ts +69 -18
  45. package/dist/generic/interfaces.d.ts.map +1 -1
  46. package/dist/generic/interfaces.js +9 -9
  47. package/dist/generic/interfaces.js.map +1 -1
  48. package/dist/generic/limitsConfig.d.ts +577 -0
  49. package/dist/generic/limitsConfig.d.ts.map +1 -0
  50. package/dist/generic/limitsConfig.js +1126 -0
  51. package/dist/generic/limitsConfig.js.map +1 -0
  52. package/dist/generic/localCacheManager.d.ts +10 -13
  53. package/dist/generic/localCacheManager.d.ts.map +1 -1
  54. package/dist/generic/localCacheManager.js +189 -67
  55. package/dist/generic/localCacheManager.js.map +1 -1
  56. package/dist/generic/metadata.d.ts +4 -4
  57. package/dist/generic/metadata.d.ts.map +1 -1
  58. package/dist/generic/metadata.js +4 -4
  59. package/dist/generic/metadata.js.map +1 -1
  60. package/dist/generic/providerBase.d.ts +242 -12
  61. package/dist/generic/providerBase.d.ts.map +1 -1
  62. package/dist/generic/providerBase.js +744 -101
  63. package/dist/generic/providerBase.js.map +1 -1
  64. package/dist/generic/queryResultEnricher.d.ts +4 -1
  65. package/dist/generic/queryResultEnricher.d.ts.map +1 -1
  66. package/dist/generic/queryResultEnricher.js.map +1 -1
  67. package/dist/generic/queryTemplateContext.d.ts.map +1 -1
  68. package/dist/generic/queryTemplateContext.js +38 -3
  69. package/dist/generic/queryTemplateContext.js.map +1 -1
  70. package/dist/generic/relatedRecordCollection.d.ts +20 -0
  71. package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
  72. package/dist/generic/relatedRecordCollection.js +257 -22
  73. package/dist/generic/relatedRecordCollection.js.map +1 -1
  74. package/dist/generic/securityInfo.d.ts +56 -2
  75. package/dist/generic/securityInfo.d.ts.map +1 -1
  76. package/dist/generic/securityInfo.js +141 -12
  77. package/dist/generic/securityInfo.js.map +1 -1
  78. package/dist/generic/telemetryManager.d.ts +40 -4
  79. package/dist/generic/telemetryManager.d.ts.map +1 -1
  80. package/dist/generic/telemetryManager.js +68 -15
  81. package/dist/generic/telemetryManager.js.map +1 -1
  82. package/dist/generic/transactionGroup.d.ts +41 -23
  83. package/dist/generic/transactionGroup.d.ts.map +1 -1
  84. package/dist/generic/transactionGroup.js +133 -70
  85. package/dist/generic/transactionGroup.js.map +1 -1
  86. package/dist/index.d.ts +3 -1
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +3 -1
  89. package/dist/index.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -0
  91. package/dist/views/decisionReadGuard.d.ts +143 -0
  92. package/dist/views/decisionReadGuard.d.ts.map +1 -0
  93. package/dist/views/decisionReadGuard.js +220 -0
  94. package/dist/views/decisionReadGuard.js.map +1 -0
  95. package/dist/views/runView.d.ts +8 -0
  96. package/dist/views/runView.d.ts.map +1 -1
  97. package/dist/views/runView.js +20 -3
  98. package/dist/views/runView.js.map +1 -1
  99. package/package.json +3 -3
  100. package/readme.md +6 -5
  101. package/dist/generic/typedQuery.d.ts +0 -151
  102. package/dist/generic/typedQuery.d.ts.map +0 -1
  103. package/dist/generic/typedQuery.js +0 -286
  104. package/dist/generic/typedQuery.js.map +0 -1
@@ -1,14 +1,15 @@
1
1
  import { ProviderBase } from "./providerBase.js";
2
2
  import { UserInfo } from "./securityInfo.js";
3
3
  import { EntityFieldTSType, EntityPermissionType } from "./entityInfo.js";
4
- import { BaseEntityResult, SerializeCloneChangeContext } from "./baseEntity.js";
4
+ import { BaseEntityResult, SerializeCloneChangeContext, SerializeSyncChangeContext } from "./baseEntity.js";
5
5
  import { EntitySaveOptions, EntityDeleteOptions } from "./interfaces.js";
6
6
  import { DispatchRemoteOperationInProcess } from "./remoteOperationDispatch.js";
7
7
  import { TransactionItem } from "./transactionGroup.js";
8
8
  import { CompositeKey } from "./compositeKey.js";
9
- import { LogError, LogWarning } from "./logging.js";
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
14
  import { FormatBinaryChangeValue, ScanSQLForScreening, SQLExpressionValidator, uuidv4, ValidationResult, EscapeSQLString } from "@memberjunction/global";
14
15
  import { GetDialect } from "@memberjunction/sql-dialect";
@@ -32,6 +33,8 @@ export class DatabaseProviderBase extends ProviderBase {
32
33
  super(...arguments);
33
34
  this._providerInstanceId = DatabaseProviderBase._nextProviderInstanceId++;
34
35
  this._transactionEpoch = 0;
36
+ this._detachedCoalescedTasks = new Map();
37
+ this._detachedCoalesceScheduled = false;
35
38
  this._dialect = null;
36
39
  /**************************************************************************/
37
40
  // END ---- Record Duplicates & Merge
@@ -219,6 +222,44 @@ export class DatabaseProviderBase extends ProviderBase {
219
222
  CapturePostCommitToken() {
220
223
  return undefined;
221
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
+ }
222
263
  /**
223
264
  * Await one post-commit task, logging (never rethrowing) its failure. Shared by the immediate
224
265
  * path of {@link RunAfterCommit} and by subclasses that drain a queue after commit.
@@ -1139,6 +1180,21 @@ export class DatabaseProviderBase extends ProviderBase {
1139
1180
  async CheckUpdateConcurrency(_entity, _user, _options, _entityResult) {
1140
1181
  return true;
1141
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
+ }
1142
1198
  /**
1143
1199
  * Awaited immediately after the save SQL succeeds (inside direct `Save()`'s
1144
1200
  * {@link EntityTransactionScope} before commit, or inside a `TransactionGroup` item's completion
@@ -1227,7 +1283,11 @@ export class DatabaseProviderBase extends ProviderBase {
1227
1283
  if (overlappingChangeData &&
1228
1284
  entity.EntityInfo.AllowMultipleSubtypes &&
1229
1285
  entity.EntityInfo.TrackRecordChanges) {
1230
- await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? '', options.ISAActiveChildEntityName, undefined, entity.CloneContext ? 'Clone' : 'Internal', entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : null);
1286
+ await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? '', options.ISAActiveChildEntityName, undefined, entity.CloneContext ? 'Clone' : entity.SyncContext ? 'Sync' : 'Internal', entity.CloneContext
1287
+ ? SerializeCloneChangeContext(entity.CloneContext)
1288
+ : entity.SyncContext
1289
+ ? SerializeSyncChangeContext(entity.SyncContext)
1290
+ : null, entity.SyncContext?.IntegrationID ?? null);
1231
1291
  }
1232
1292
  return null;
1233
1293
  }
@@ -1771,6 +1831,12 @@ export class DatabaseProviderBase extends ProviderBase {
1771
1831
  }
1772
1832
  }
1773
1833
  }
1834
+ // Snapshot field values before Step 3 (before-save hooks / cross-entity policy / auto-numbering).
1835
+ // If no hook mutates any field value on a new record, the 2nd CheckCreateRLS check at step 3b
1836
+ // is redundant with step 2b and can be safely skipped.
1837
+ const preHookFieldSnapshot = (!bReplay && bNewRecord)
1838
+ ? this.CaptureEntityFieldSnapshot(entity)
1839
+ : null;
1774
1840
  // Step 3: Before-save hook (entity actions, AI actions)
1775
1841
  if (!bReplay) {
1776
1842
  await this.OnBeforeSaveExecute(entity, user, options, saveContext);
@@ -1806,22 +1872,19 @@ export class DatabaseProviderBase extends ProviderBase {
1806
1872
  // escalation, not just a leak). This runs AFTER the before-save hooks by design:
1807
1873
  // hooks can mutate field values, including filter-referenced ones, and the
1808
1874
  // authorization boundary must cover the values that actually get written.
1809
- // Nothing existing moves — step 2b and step 3 keep their order; this is a new,
1810
- // additive step. Applies to BOTH creates and updates: a before-save hook can
1811
- // move a brand-new record's values outside the Create filter just as easily as
1812
- // it can move an existing row outside the Update filter, so CheckCreateRLS is
1813
- // called a second time here (idempotent, side-effect-free) rather than only
1814
- // gating updates. Post-image failure gets a specific message (unlike step 2b's
1815
- // deliberately generic one on the update path): the caller demonstrably had
1816
- // access to the pre-hook state, so the diagnostic leaks nothing new.
1875
+ // When before-save hooks leave field values and dirty flags completely unchanged,
1876
+ // the second CheckCreateRLS evaluation is redundant with step 2b and safely skipped.
1817
1877
  if (!bReplay) {
1818
1878
  if (bNewRecord) {
1819
- const postHookCreatePass = await this.CheckCreateRLS(entity, user);
1820
- if (!postHookCreatePass) {
1821
- entityResult.Success = false;
1822
- entityResult.EndedAt = new Date();
1823
- entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
1824
- throw new Error(entityResult.Message);
1879
+ const fieldsMutated = preHookFieldSnapshot === null || this.HasEntityFieldStateMutated(entity, preHookFieldSnapshot);
1880
+ if (fieldsMutated) {
1881
+ const postHookCreatePass = await this.CheckCreateRLS(entity, user);
1882
+ if (!postHookCreatePass) {
1883
+ entityResult.Success = false;
1884
+ entityResult.EndedAt = new Date();
1885
+ entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
1886
+ throw new Error(entityResult.Message);
1887
+ }
1825
1888
  }
1826
1889
  }
1827
1890
  else {
@@ -1857,11 +1920,11 @@ export class DatabaseProviderBase extends ProviderBase {
1857
1920
  };
1858
1921
  if (entity.TransactionGroup && !bReplay) {
1859
1922
  // ---- Transaction Group path ----
1860
- if (!bNewRecord &&
1861
- !bReplay &&
1862
- (options?.ConcurrencyBaseline !== undefined || options?.ConcurrencyCheck === 'enforce')) {
1863
- LogWarning(`DatabaseProviderBase.Save: entity "${entity.EntityInfo.Name}" is queued in a TransactionGroup; per-save concurrency checking (ConcurrencyBaseline / ConcurrencyCheck: 'enforce') is bypassed for TransactionGroup items.`);
1864
- }
1923
+ // Captured before GenerateSaveSQL, matching the direct path, which checks
1924
+ // before it generates the update.
1925
+ const concurrencyCheck = bNewRecord
1926
+ ? null
1927
+ : this.PrepareQueuedUpdateConcurrencyCheck(entity, user, options, entityResult);
1865
1928
  let sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
1866
1929
  const preSaveValues = capturePreSaveValues();
1867
1930
  entity.RaiseReadyForTransaction();
@@ -1920,8 +1983,12 @@ export class DatabaseProviderBase extends ProviderBase {
1920
1983
  else {
1921
1984
  entityResult.Success = false;
1922
1985
  if (!entityResult.Message) {
1986
+ // The group's failure carries the database message of whichever
1987
+ // item failed, so it gets the same redaction as a direct save.
1923
1988
  entityResult.Message =
1924
- transactionResult instanceof Error ? transactionResult.message : 'Transaction Failed';
1989
+ transactionResult instanceof Error
1990
+ ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user)
1991
+ : 'Transaction Failed';
1925
1992
  }
1926
1993
  }
1927
1994
  });
@@ -1945,6 +2012,9 @@ export class DatabaseProviderBase extends ProviderBase {
1945
2012
  }
1946
2013
  };
1947
2014
  }
2015
+ if (concurrencyCheck) {
2016
+ txItem.CheckBeforeSubmit = concurrencyCheck;
2017
+ }
1948
2018
  entity.TransactionGroup.AddTransaction(txItem);
1949
2019
  return true;
1950
2020
  }
@@ -2072,7 +2142,10 @@ export class DatabaseProviderBase extends ProviderBase {
2072
2142
  }
2073
2143
  resumeRefresh();
2074
2144
  entityResult.EndedAt = new Date();
2075
- entityResult.Message = e.message;
2145
+ // A constraint error can echo column values, including the stored value of a column
2146
+ // this user may not read (a unique index spanning it). The caller gets the message
2147
+ // without them; the server log keeps the original.
2148
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
2076
2149
  LogError(e);
2077
2150
  throw e;
2078
2151
  }
@@ -2187,7 +2260,9 @@ export class DatabaseProviderBase extends ProviderBase {
2187
2260
  entityResult.Success = false;
2188
2261
  if (!entityResult.Message) {
2189
2262
  entityResult.Message =
2190
- transactionResult instanceof Error ? transactionResult.message : 'Transaction failed to commit';
2263
+ transactionResult instanceof Error
2264
+ ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user)
2265
+ : 'Transaction failed to commit';
2191
2266
  }
2192
2267
  }
2193
2268
  }));
@@ -2223,7 +2298,9 @@ export class DatabaseProviderBase extends ProviderBase {
2223
2298
  }
2224
2299
  catch (e) {
2225
2300
  LogError(e);
2226
- entityResult.Message = e.message;
2301
+ // A delete's SQL writes the full record to the audit trail, and a constraint error can
2302
+ // echo stored values, so the caller gets the same redaction as a failed save.
2303
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
2227
2304
  entityResult.Success = false;
2228
2305
  entityResult.EndedAt = new Date();
2229
2306
  return false;
@@ -2234,6 +2311,101 @@ export class DatabaseProviderBase extends ProviderBase {
2234
2311
  }
2235
2312
  }
2236
2313
  }
2314
+ /**
2315
+ * Captures an immutable snapshot of an entity's fields (name, value, dirty status)
2316
+ * so we can detect whether before-save hooks mutated any field (including in-place
2317
+ * Date, Uint8Array, or JSON object mutations and case-sensitive string changes).
2318
+ */
2319
+ CaptureEntityFieldSnapshot(entity) {
2320
+ return entity.Fields.map((f) => this.snapshotSingleFieldState(f.Name, f.Value, f.Dirty));
2321
+ }
2322
+ snapshotSingleFieldState(name, val, dirty) {
2323
+ if (val === null) {
2324
+ return { Name: name, Kind: 'primitive', PrimitiveValue: null, Dirty: dirty };
2325
+ }
2326
+ if (val === undefined) {
2327
+ return { Name: name, Kind: 'primitive', PrimitiveValue: undefined, Dirty: dirty };
2328
+ }
2329
+ if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
2330
+ return { Name: name, Kind: 'primitive', PrimitiveValue: val, Dirty: dirty };
2331
+ }
2332
+ if (val instanceof Date) {
2333
+ return { Name: name, Kind: 'date', DateMs: val.getTime(), Dirty: dirty };
2334
+ }
2335
+ if (val instanceof Uint8Array) {
2336
+ return { Name: name, Kind: 'bytes', BytesCopy: val.slice(), Dirty: dirty };
2337
+ }
2338
+ if (typeof val === 'object') {
2339
+ try {
2340
+ return { Name: name, Kind: 'json', SerializedJson: JSON.stringify(val), Dirty: dirty };
2341
+ }
2342
+ catch {
2343
+ return { Name: name, Kind: 'uncomparable', Dirty: dirty };
2344
+ }
2345
+ }
2346
+ return { Name: name, Kind: 'uncomparable', Dirty: dirty };
2347
+ }
2348
+ /**
2349
+ * Checks whether an entity's field values or dirty flags have mutated compared to a previous snapshot.
2350
+ */
2351
+ HasEntityFieldStateMutated(entity, snapshot) {
2352
+ const currentFields = entity.Fields;
2353
+ if (snapshot.length !== currentFields.length) {
2354
+ return true;
2355
+ }
2356
+ for (let i = 0; i < snapshot.length; i++) {
2357
+ const prev = snapshot[i];
2358
+ const curr = currentFields[i];
2359
+ if (prev.Name !== curr.Name || prev.Dirty !== curr.Dirty) {
2360
+ return true;
2361
+ }
2362
+ if (!this.matchesFieldSnapshot(prev, curr.Value)) {
2363
+ return true;
2364
+ }
2365
+ }
2366
+ return false;
2367
+ }
2368
+ matchesFieldSnapshot(prev, curr) {
2369
+ if (prev.Kind === 'uncomparable') {
2370
+ return false;
2371
+ }
2372
+ if (prev.Kind === 'primitive') {
2373
+ if (typeof prev.PrimitiveValue === 'number' && typeof curr === 'number' && Number.isNaN(prev.PrimitiveValue) && Number.isNaN(curr)) {
2374
+ return true;
2375
+ }
2376
+ return prev.PrimitiveValue === curr;
2377
+ }
2378
+ if (prev.Kind === 'date') {
2379
+ if (!(curr instanceof Date)) {
2380
+ return false;
2381
+ }
2382
+ const currMs = curr.getTime();
2383
+ return (Number.isNaN(prev.DateMs) && Number.isNaN(currMs)) || prev.DateMs === currMs;
2384
+ }
2385
+ if (prev.Kind === 'bytes') {
2386
+ if (!(curr instanceof Uint8Array) || !prev.BytesCopy || prev.BytesCopy.length !== curr.length) {
2387
+ return false;
2388
+ }
2389
+ for (let i = 0; i < curr.length; i++) {
2390
+ if (prev.BytesCopy[i] !== curr[i]) {
2391
+ return false;
2392
+ }
2393
+ }
2394
+ return true;
2395
+ }
2396
+ if (prev.Kind === 'json') {
2397
+ if (curr === null || typeof curr !== 'object' || curr instanceof Date || curr instanceof Uint8Array) {
2398
+ return false;
2399
+ }
2400
+ try {
2401
+ return prev.SerializedJson === JSON.stringify(curr);
2402
+ }
2403
+ catch {
2404
+ return false;
2405
+ }
2406
+ }
2407
+ return false;
2408
+ }
2237
2409
  /**************************************************************************/
2238
2410
  // END ---- Save/Delete Orchestration
2239
2411
  /**************************************************************************/
@@ -2380,8 +2552,8 @@ export class DatabaseProviderBase extends ProviderBase {
2380
2552
  * @param type The change type
2381
2553
  * @param user The acting user
2382
2554
  */
2383
- async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext) {
2384
- const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext);
2555
+ async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext) {
2556
+ const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext);
2385
2557
  if (sqlResult) {
2386
2558
  return await this.ExecuteSQL(sqlResult.sql, sqlResult.parameters ?? undefined, undefined, user);
2387
2559
  }
@@ -2401,7 +2573,7 @@ export class DatabaseProviderBase extends ProviderBase {
2401
2573
  }
2402
2574
  /**
2403
2575
  * Builds the dialect-agnostic payload for a RecordChange row from the
2404
- * entity's old/new data and an optional restore or clone context. Concrete
2576
+ * entity's old/new data and an optional restore, clone, or sync context. Concrete
2405
2577
  * providers consume the returned payload to render their dialect-specific
2406
2578
  * SQL (SQL Server EXEC, PostgreSQL INSERT, etc.).
2407
2579
  *
@@ -2427,24 +2599,43 @@ export class DatabaseProviderBase extends ProviderBase {
2427
2599
  * `DiffObjects`. Defaults to single quote.
2428
2600
  * @param cloneContext When non-null, populates `source='Clone'` and the
2429
2601
  * structured `changeContext` JSON payload.
2602
+ * @param skipFullRecordJSON When true (because the dialect builds `FullRecordJSON` in SQL
2603
+ * from the returned row), skips `EscapeQuotesInProperties` and `JSON.stringify` for
2604
+ * `fullRecordJSON`, returning `''`.
2605
+ * @param syncContext When non-null, populates `source='Sync'`, `integrationID`,
2606
+ * and the structured `changeContext` JSON payload.
2430
2607
  */
2431
- BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext) {
2432
- if (restoreContext && cloneContext) {
2433
- throw new Error('BuildRecordChangePayload: both restoreContext and cloneContext were provided; an operation cannot be both a restore and a clone');
2608
+ BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false, syncContext) {
2609
+ const activeContexts = [restoreContext, cloneContext, syncContext].filter(Boolean).length;
2610
+ if (activeContexts > 1) {
2611
+ throw new Error('BuildRecordChangePayload: restoreContext, cloneContext, and syncContext are mutually exclusive; at most one may be provided');
2434
2612
  }
2435
2613
  const isCreateOrDelete = oldData === null || newData === null;
2436
2614
  const changes = this.DiffObjects(oldData, newData, entityInfo, quoteToEscape);
2437
2615
  const changesKeys = changes ? Object.keys(changes) : [];
2438
2616
  if (changesKeys.length === 0 && !isCreateOrDelete)
2439
2617
  return null;
2440
- const dataForFullJSON = newData ?? oldData;
2441
- const fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
2618
+ let fullRecordJSON = '';
2619
+ if (!skipFullRecordJSON) {
2620
+ const dataForFullJSON = newData ?? oldData;
2621
+ fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
2622
+ }
2442
2623
  const changesJSON = changes !== null ? JSON.stringify(changes) : '';
2443
2624
  const changesDescription = (oldData && newData)
2444
2625
  ? this.CreateUserDescriptionOfChanges(changes)
2445
2626
  : (!oldData ? 'Record Created' : 'Record Deleted');
2446
- const source = restoreContext ? 'Restore' : cloneContext ? 'Clone' : 'Internal';
2447
- const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : null;
2627
+ const source = restoreContext
2628
+ ? 'Restore'
2629
+ : cloneContext
2630
+ ? 'Clone'
2631
+ : syncContext
2632
+ ? 'Sync'
2633
+ : 'Internal';
2634
+ const changeContext = cloneContext
2635
+ ? SerializeCloneChangeContext(cloneContext)
2636
+ : syncContext
2637
+ ? SerializeSyncChangeContext(syncContext)
2638
+ : null;
2448
2639
  return {
2449
2640
  entityID: entityInfo.ID,
2450
2641
  recordID,
@@ -2457,6 +2648,7 @@ export class DatabaseProviderBase extends ProviderBase {
2457
2648
  restoredFromID: restoreContext?.SourceChangeID ?? null,
2458
2649
  restoreReason: restoreContext?.Reason ?? null,
2459
2650
  changeContext,
2651
+ integrationID: syncContext?.IntegrationID ?? null,
2460
2652
  };
2461
2653
  }
2462
2654
  /**
@@ -2473,7 +2665,7 @@ export class DatabaseProviderBase extends ProviderBase {
2473
2665
  * @param source The source discriminator for the record change row ('Internal' or 'Clone')
2474
2666
  * @param changeContext Optional serialized JSON provenance for clone operations
2475
2667
  */
2476
- async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = 'Internal', changeContext = null) {
2668
+ async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = 'Internal', changeContext = null, integrationID = null) {
2477
2669
  const sqlParts = [];
2478
2670
  const safePKValue = pkValue.replace(/'/g, "''");
2479
2671
  const safeUserId = userId.replace(/'/g, "''");
@@ -2491,7 +2683,7 @@ export class DatabaseProviderBase extends ProviderBase {
2491
2683
  if (!entityInTree.TrackRecordChanges)
2492
2684
  continue;
2493
2685
  const varName = `@_rc_prop_${varIndex++}`;
2494
- sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext));
2686
+ sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext, integrationID));
2495
2687
  }
2496
2688
  }
2497
2689
  // Execute as single batch