@memberjunction/core 6.2.0 → 6.3.0-edge.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/generic/BaseEntitySaveQueue.d.ts +11 -0
  2. package/dist/generic/BaseEntitySaveQueue.d.ts.map +1 -1
  3. package/dist/generic/BaseEntitySaveQueue.js +17 -1
  4. package/dist/generic/BaseEntitySaveQueue.js.map +1 -1
  5. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  6. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  7. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  8. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  9. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  10. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  11. package/dist/generic/appCapabilityRegistry.js +212 -0
  12. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  13. package/dist/generic/baseEngine.d.ts +108 -3
  14. package/dist/generic/baseEngine.d.ts.map +1 -1
  15. package/dist/generic/baseEngine.js +891 -122
  16. package/dist/generic/baseEngine.js.map +1 -1
  17. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  18. package/dist/generic/baseEngineRegistry.js +8 -1
  19. package/dist/generic/baseEngineRegistry.js.map +1 -1
  20. package/dist/generic/baseEntity.d.ts +147 -3
  21. package/dist/generic/baseEntity.d.ts.map +1 -1
  22. package/dist/generic/baseEntity.js +1063 -25
  23. package/dist/generic/baseEntity.js.map +1 -1
  24. package/dist/generic/baseRemotableOperation.d.ts +15 -0
  25. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  26. package/dist/generic/baseRemotableOperation.js +11 -0
  27. package/dist/generic/baseRemotableOperation.js.map +1 -1
  28. package/dist/generic/compositeKey.d.ts.map +1 -1
  29. package/dist/generic/compositeKey.js +3 -1
  30. package/dist/generic/compositeKey.js.map +1 -1
  31. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  32. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  33. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  34. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  35. package/dist/generic/dataHooks.d.ts +14 -1
  36. package/dist/generic/dataHooks.d.ts.map +1 -1
  37. package/dist/generic/dataHooks.js.map +1 -1
  38. package/dist/generic/databaseProviderBase.d.ts +37 -0
  39. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  40. package/dist/generic/databaseProviderBase.js +220 -24
  41. package/dist/generic/databaseProviderBase.js.map +1 -1
  42. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  43. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  44. package/dist/generic/documentNumberingEngine.js +739 -0
  45. package/dist/generic/documentNumberingEngine.js.map +1 -0
  46. package/dist/generic/entityInfo.d.ts +104 -3
  47. package/dist/generic/entityInfo.d.ts.map +1 -1
  48. package/dist/generic/entityInfo.js +326 -22
  49. package/dist/generic/entityInfo.js.map +1 -1
  50. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  51. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  52. package/dist/generic/entityLifecyclePolicy.js +708 -0
  53. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  54. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  55. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  56. package/dist/generic/entitySubtypeDriver.js +26 -0
  57. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  58. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  59. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  60. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  61. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  62. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  63. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  64. package/dist/generic/filters/compositeFilter.js +127 -12
  65. package/dist/generic/filters/compositeFilter.js.map +1 -1
  66. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  67. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  68. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  69. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  70. package/dist/generic/filters/filter.types.d.ts +5 -2
  71. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  72. package/dist/generic/filters/filter.types.js +4 -1
  73. package/dist/generic/filters/filter.types.js.map +1 -1
  74. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  75. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  76. package/dist/generic/filters/filterBuilder.js +104 -0
  77. package/dist/generic/filters/filterBuilder.js.map +1 -0
  78. package/dist/generic/filters/index.d.ts +2 -0
  79. package/dist/generic/filters/index.d.ts.map +1 -1
  80. package/dist/generic/filters/index.js +2 -0
  81. package/dist/generic/filters/index.js.map +1 -1
  82. package/dist/generic/interfaces.d.ts +74 -1
  83. package/dist/generic/interfaces.d.ts.map +1 -1
  84. package/dist/generic/interfaces.js +0 -1
  85. package/dist/generic/interfaces.js.map +1 -1
  86. package/dist/generic/localCacheManager.d.ts +46 -3
  87. package/dist/generic/localCacheManager.d.ts.map +1 -1
  88. package/dist/generic/localCacheManager.js +267 -45
  89. package/dist/generic/localCacheManager.js.map +1 -1
  90. package/dist/generic/metadata.d.ts +3 -1
  91. package/dist/generic/metadata.d.ts.map +1 -1
  92. package/dist/generic/metadata.js +25 -6
  93. package/dist/generic/metadata.js.map +1 -1
  94. package/dist/generic/providerBase.d.ts +212 -33
  95. package/dist/generic/providerBase.d.ts.map +1 -1
  96. package/dist/generic/providerBase.js +543 -117
  97. package/dist/generic/providerBase.js.map +1 -1
  98. package/dist/generic/queryInfo.d.ts +5 -0
  99. package/dist/generic/queryInfo.d.ts.map +1 -1
  100. package/dist/generic/queryInfo.js +5 -0
  101. package/dist/generic/queryInfo.js.map +1 -1
  102. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  103. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  104. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  105. package/dist/generic/remoteOperationDispatch.js +13 -1
  106. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  107. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  108. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  109. package/dist/generic/saveEntityGraphOperation.js +8 -0
  110. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  111. package/dist/generic/transactionGroup.d.ts +25 -0
  112. package/dist/generic/transactionGroup.d.ts.map +1 -1
  113. package/dist/generic/transactionGroup.js +105 -0
  114. package/dist/generic/transactionGroup.js.map +1 -1
  115. package/dist/generic/typedQuery.d.ts +151 -0
  116. package/dist/generic/typedQuery.d.ts.map +1 -0
  117. package/dist/generic/typedQuery.js +286 -0
  118. package/dist/generic/typedQuery.js.map +1 -0
  119. package/dist/generic/util.d.ts.map +1 -1
  120. package/dist/generic/util.js +9 -3
  121. package/dist/generic/util.js.map +1 -1
  122. package/dist/index.d.ts +6 -0
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +6 -0
  125. package/dist/index.js.map +1 -1
  126. package/dist/views/runView.d.ts +53 -0
  127. package/dist/views/runView.d.ts.map +1 -1
  128. package/dist/views/runView.js +134 -0
  129. package/dist/views/runView.js.map +1 -1
  130. package/package.json +3 -3
@@ -16,6 +16,209 @@ import { ProviderBase } from "./providerBase.js";
16
16
  import { DatabaseProviderBase } from "./databaseProviderBase.js";
17
17
  import { TransformSimpleObjectToEntityObject, CanonicalPrimaryKeyValue } from "./util.js";
18
18
  import { WellKnownUserSource } from "./wellKnownUserSource.js";
19
+ import { CompositeFilter } from "./filters/compositeFilter.js";
20
+ /** Key indexes by cached array. The index of a replaced array is collected with it. */
21
+ const primaryKeyIndexes = new WeakMap();
22
+ const deltaHeldRowIndexes = new WeakMap();
23
+ /**
24
+ * Reads a field value from an entity, falling back to `entity.Get(fieldName)` when no generated
25
+ * property getter exists on the instance (e.g. generic `BaseEntity` fallback instances).
26
+ */
27
+ function readEntityFieldValue(entity, fieldName) {
28
+ const direct = Reflect.get(entity, fieldName);
29
+ if (direct !== undefined) {
30
+ return direct;
31
+ }
32
+ return typeof entity.Get === 'function' ? entity.Get(fieldName) : undefined;
33
+ }
34
+ /**
35
+ * One key column as a string with the same equality as {@link BaseEngine.findEntityIndexByPrimaryKeys}:
36
+ * `UUIDsEqual` for UUID columns, `===` otherwise. Returns undefined for a value it cannot represent.
37
+ */
38
+ function primaryKeyPart(value, isUuid) {
39
+ if (isUuid) {
40
+ if (value == null)
41
+ return 'n';
42
+ return typeof value === 'string' ? 'u' + value.trim().toLowerCase() : undefined;
43
+ }
44
+ switch (typeof value) {
45
+ case 'string': return 's' + value;
46
+ case 'number': return Number.isNaN(value) ? undefined : 'd' + value;
47
+ case 'boolean': return 'b' + value;
48
+ case 'bigint': return 'g' + value;
49
+ case 'undefined': return 'U';
50
+ default: return value === null ? 'N' : undefined;
51
+ }
52
+ }
53
+ /** The index key of a row: its key columns in order, or undefined when a column cannot be represented. */
54
+ function primaryKeyOfRow(row, pks) {
55
+ if (row == null)
56
+ return undefined;
57
+ if (pks.length === 1)
58
+ return primaryKeyPart(readEntityFieldValue(row, pks[0].Name), pks[0].IsUniqueIdentifier);
59
+ let key = '';
60
+ for (const pk of pks) {
61
+ const part = primaryKeyPart(readEntityFieldValue(row, pk.Name), pk.IsUniqueIdentifier);
62
+ if (part === undefined)
63
+ return undefined;
64
+ key += part.length + ':' + part;
65
+ }
66
+ return key;
67
+ }
68
+ /** The index key of a plain field snapshot (such as `OldValues` on a delete event). */
69
+ function primaryKeyOfRecord(record, pks) {
70
+ if (pks.length === 1)
71
+ return primaryKeyPart(record[pks[0].Name], pks[0].IsUniqueIdentifier);
72
+ let key = '';
73
+ for (const pk of pks) {
74
+ const part = primaryKeyPart(record[pk.Name], pk.IsUniqueIdentifier);
75
+ if (part === undefined)
76
+ return undefined;
77
+ key += part.length + ':' + part;
78
+ }
79
+ return key;
80
+ }
81
+ /** A string naming the key columns and their comparison, so an index is reused only for the same key. */
82
+ function primaryKeySignature(pks) {
83
+ return pks.map(pk => (pk.IsUniqueIdentifier ? 'u:' : 's:') + pk.Name).join('|');
84
+ }
85
+ /** Builds and stores the key index of an array. Returns null when the rows cannot be read. */
86
+ function buildPrimaryKeyIndex(dataArray, pks, signature) {
87
+ try {
88
+ let map = new Map();
89
+ const refs = new WeakSet();
90
+ let duplicates = false;
91
+ for (let i = 0; i < dataArray.length; i++) {
92
+ const row = dataArray[i];
93
+ if (row != null && typeof row === 'object') {
94
+ refs.add(row);
95
+ }
96
+ if (map) {
97
+ const key = primaryKeyOfRow(row, pks);
98
+ if (key === undefined) {
99
+ map = null;
100
+ }
101
+ else if (map.has(key)) {
102
+ duplicates = true;
103
+ }
104
+ else {
105
+ map.set(key, i);
106
+ }
107
+ }
108
+ }
109
+ const index = { map, refs, pks, signature, duplicates, length: dataArray.length, last: dataArray[dataArray.length - 1] };
110
+ primaryKeyIndexes.set(dataArray, index);
111
+ return index;
112
+ }
113
+ catch {
114
+ primaryKeyIndexes.delete(dataArray);
115
+ return null;
116
+ }
117
+ }
118
+ /** True when the row at `pos` has the index key `key`. */
119
+ function rowHasPrimaryKey(dataArray, pos, pks, key) {
120
+ try {
121
+ return pos < dataArray.length && primaryKeyOfRow(dataArray[pos], pks) === key;
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
127
+ /** Adds a row just appended to `dataArray` to its key index, when the index was current before the append; drops the index otherwise. */
128
+ function primaryKeyIndexAppended(dataArray, row) {
129
+ const index = primaryKeyIndexes.get(dataArray);
130
+ if (!index)
131
+ return;
132
+ try {
133
+ const n = dataArray.length;
134
+ if (index.length !== n - 1 || index.last !== dataArray[n - 2] || dataArray[n - 1] !== row) {
135
+ primaryKeyIndexes.delete(dataArray);
136
+ return;
137
+ }
138
+ if (index.map) {
139
+ const key = primaryKeyOfRow(row, index.pks);
140
+ if (key === undefined) {
141
+ primaryKeyIndexes.delete(dataArray);
142
+ return;
143
+ }
144
+ if (index.map.has(key))
145
+ index.duplicates = true;
146
+ else
147
+ index.map.set(key, n - 1);
148
+ }
149
+ if (row != null && typeof row === 'object') {
150
+ index.refs.add(row);
151
+ }
152
+ index.length = n;
153
+ index.last = row;
154
+ }
155
+ catch {
156
+ primaryKeyIndexes.delete(dataArray);
157
+ }
158
+ }
159
+ /** Keeps the key index of `dataArray` after a row was written in place at `pos`; drops it when the row's key is not indexed at `pos`. */
160
+ function primaryKeyIndexReplaced(dataArray, pos, row, previousRow) {
161
+ const index = primaryKeyIndexes.get(dataArray);
162
+ if (!index)
163
+ return;
164
+ try {
165
+ const n = dataArray.length;
166
+ const current = index.length === n && (pos === n - 1 || index.last === dataArray[n - 1]);
167
+ if (!current || (index.map && index.map.get(primaryKeyOfRow(row, index.pks) ?? '') !== pos)) {
168
+ primaryKeyIndexes.delete(dataArray);
169
+ return;
170
+ }
171
+ if (previousRow && previousRow !== row && !index.duplicates) {
172
+ index.refs.delete(previousRow);
173
+ }
174
+ if (row != null && typeof row === 'object') {
175
+ index.refs.add(row);
176
+ }
177
+ if (pos === n - 1)
178
+ index.last = row;
179
+ }
180
+ catch {
181
+ primaryKeyIndexes.delete(dataArray);
182
+ }
183
+ }
184
+ /**
185
+ * Updates the key index of `dataArray` after `removed` was spliced out at `pos`: removes its key and
186
+ * moves later positions down by one. Drops the index when it was not current before the splice,
187
+ * holds duplicate keys, or does not have `removed` at `pos`.
188
+ */
189
+ function primaryKeyIndexRemoved(dataArray, pos, removed) {
190
+ const index = primaryKeyIndexes.get(dataArray);
191
+ if (!index)
192
+ return;
193
+ try {
194
+ const n = dataArray.length;
195
+ const lastBefore = pos === n ? removed : dataArray[n - 1];
196
+ if (!index.map || index.duplicates || index.length !== n + 1 || index.last !== lastBefore) {
197
+ primaryKeyIndexes.delete(dataArray);
198
+ return;
199
+ }
200
+ const key = primaryKeyOfRow(removed, index.pks);
201
+ if (key === undefined || index.map.get(key) !== pos) {
202
+ primaryKeyIndexes.delete(dataArray);
203
+ return;
204
+ }
205
+ index.map.delete(key);
206
+ index.refs.delete(removed);
207
+ for (const [k, p] of index.map) {
208
+ if (p > pos)
209
+ index.map.set(k, p - 1);
210
+ }
211
+ index.length = n;
212
+ index.last = dataArray[n - 1];
213
+ }
214
+ catch {
215
+ primaryKeyIndexes.delete(dataArray);
216
+ }
217
+ }
218
+ /** Drops the key index of an array; the next lookup rebuilds it. */
219
+ function primaryKeyIndexDropped(dataArray) {
220
+ primaryKeyIndexes.delete(dataArray);
221
+ }
19
222
  /**
20
223
  * Property configuration for the BaseEngine class to automatically load/set properties on the class.
21
224
  */
@@ -142,6 +345,12 @@ export class BaseEngine extends BaseSingleton {
142
345
  * 0 restores back-to-back reloads.
143
346
  */
144
347
  static { this.ExternalChangeFollowUpDelayMs = 1000; }
348
+ /**
349
+ * Most rows one keyed re-fetch reads. A no-row-data invalidation round that names more rows
350
+ * than this reloads the whole config instead. One `IN` list of this size stays well under the
351
+ * parameter and statement limits of every supported database.
352
+ */
353
+ static { this.KeyedRefetchMaxKeys = 200; }
145
354
  /**
146
355
  * Returns an Observable for a specific engine array property. Subscribers receive the
147
356
  * current array immediately (BehaviorSubject semantics), then re-receive the same array
@@ -859,9 +1068,11 @@ export class BaseEngine extends BaseSingleton {
859
1068
  }
860
1069
  // Fall through to server fetch if direct delete failed
861
1070
  }
862
- // Fallback: re-fetch from the server (no row, or it could not be applied).
1071
+ // Fallback: re-fetch from the server (no row, or it could not be applied). When the event
1072
+ // names its row, only that row is re-read (see runOneExternalChangeReload).
1073
+ const key = this.parseRemoteInvalidateKey(payload?.primaryKeyValues);
863
1074
  for (const config of matchingConfigs) {
864
- await this.reloadAfterRemoteInvalidate(config);
1075
+ await this.reloadAfterRemoteInvalidate(config, key);
865
1076
  }
866
1077
  return true;
867
1078
  }
@@ -880,10 +1091,10 @@ export class BaseEngine extends BaseSingleton {
880
1091
  * stale, and reading back through the cache would restore the pre-write snapshot. A transient
881
1092
  * failure gets the bounded retry, since the event that asked for this reload is consumed.
882
1093
  */
883
- async reloadAfterRemoteInvalidate(config) {
1094
+ async reloadAfterRemoteInvalidate(config, key = null) {
884
1095
  let succeeded;
885
1096
  try {
886
- await this.reloadAfterExternalChange(config, /*bypassCache*/ true);
1097
+ await this.reloadAfterExternalChange(config, /*bypassCache*/ true, key);
887
1098
  succeeded = this.configLoadedSuccessfully(config.PropertyName);
888
1099
  }
889
1100
  catch (e) {
@@ -894,6 +1105,28 @@ export class BaseEngine extends BaseSingleton {
894
1105
  this.scheduleEventRefreshRetry(config, 1);
895
1106
  }
896
1107
  }
1108
+ /**
1109
+ * The primary key a remote-invalidate event names, or null when it names none (or it cannot be
1110
+ * read). The payload carries it as a JSON array of `{ FieldName, Value }`.
1111
+ */
1112
+ parseRemoteInvalidateKey(primaryKeyValuesJSON) {
1113
+ if (!primaryKeyValuesJSON) {
1114
+ return null;
1115
+ }
1116
+ try {
1117
+ const pairs = JSON.parse(primaryKeyValuesJSON);
1118
+ if (!Array.isArray(pairs) || pairs.length === 0) {
1119
+ return null;
1120
+ }
1121
+ if (pairs.some(kv => !kv || typeof kv.FieldName !== 'string' || kv.Value === null || kv.Value === undefined)) {
1122
+ return null;
1123
+ }
1124
+ return CompositeKey.FromKeyValuePairs(pairs.map(kv => new KeyValuePair(kv.FieldName, kv.Value)));
1125
+ }
1126
+ catch {
1127
+ return null;
1128
+ }
1129
+ }
897
1130
  /**
898
1131
  * The entity configs that refresh automatically when a record of `entityName` changes.
899
1132
  * Matching ignores case and surrounding whitespace.
@@ -911,29 +1144,47 @@ export class BaseEngine extends BaseSingleton {
911
1144
  */
912
1145
  async applyRemoteRecordData(matchingConfigs, entityName, recordDataJSON) {
913
1146
  try {
1147
+ // Pre-check all matching configs before mutating any in-memory array so we never
1148
+ // leave earlier configs half-mutated when a later config requires a full refresh.
1149
+ if (!matchingConfigs.every(config => this.canUseImmediateMutation(config, /*skipAdditionalLoadingCheck*/ true))) {
1150
+ return false;
1151
+ }
914
1152
  const recordData = JSON.parse(recordDataJSON);
915
1153
  // Use this engine's bound provider (ProviderToUse) instead of `new Metadata()` so
916
1154
  // multi-provider client setups instantiate entities against the correct server.
917
1155
  const md = this.ProviderToUse;
918
1156
  const originalEntityName = matchingConfigs[0].EntityName;
919
- const entity = await md.GetEntityObject(originalEntityName, this._contextUser);
1157
+ const entity = await this.instantiateEntityForHydration(md, originalEntityName, this._contextUser);
920
1158
  await entity.LoadFromData(recordData);
921
1159
  for (const config of matchingConfigs) {
922
- // Skip the AdditionalLoading check because we call it ourselves after all mutations
923
- if (!this.canUseImmediateMutation(config, /*skipAdditionalLoadingCheck*/ true)) {
924
- return false;
925
- }
926
1160
  const currentData = this[config.PropertyName];
927
1161
  if (!currentData)
928
1162
  continue;
929
1163
  const index = this.findEntityIndexByPrimaryKeys(currentData, entity);
1164
+ if (this.isStructuredFilter(config.Filter)) {
1165
+ const matches = this.evaluateStructuredConfigFilter(config.Filter, entity);
1166
+ if (!matches) {
1167
+ if (index >= 0) {
1168
+ const removed = currentData[index];
1169
+ currentData.splice(index, 1);
1170
+ primaryKeyIndexRemoved(currentData, index, removed);
1171
+ this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1172
+ this.NotifyDataChange(config, currentData, 'delete', entity);
1173
+ this.emitPropertyChange(config.PropertyName);
1174
+ }
1175
+ continue;
1176
+ }
1177
+ }
930
1178
  if (index >= 0) {
1179
+ const prev = currentData[index];
931
1180
  currentData[index] = entity;
1181
+ primaryKeyIndexReplaced(currentData, index, entity, prev);
932
1182
  this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
933
1183
  this.NotifyDataChange(config, currentData, 'update', entity);
934
1184
  }
935
1185
  else {
936
1186
  currentData.push(entity);
1187
+ primaryKeyIndexAppended(currentData, entity);
937
1188
  this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
938
1189
  this.NotifyDataChange(config, currentData, 'add', entity);
939
1190
  }
@@ -969,6 +1220,7 @@ export class BaseEngine extends BaseSingleton {
969
1220
  if (index >= 0) {
970
1221
  const removed = currentData[index];
971
1222
  currentData.splice(index, 1);
1223
+ primaryKeyIndexRemoved(currentData, index, removed);
972
1224
  this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
973
1225
  this.NotifyDataChange(config, currentData, 'delete', removed);
974
1226
  this.emitPropertyChange(config.PropertyName);
@@ -1202,6 +1454,35 @@ export class BaseEngine extends BaseSingleton {
1202
1454
  }
1203
1455
  return this.indexOfEntityByRefOrKey(currentData, entity, preDeleteValues) >= 0;
1204
1456
  }
1457
+ /**
1458
+ * Fast `O(1)` reference membership check backed by {@link PrimaryKeyIndex.refs}, falling back
1459
+ * to `Array.prototype.indexOf` only when `entity` is recorded in `refs` or the array cannot
1460
+ * be indexed.
1461
+ */
1462
+ indexOfEntityByRefFast(currentData, entity) {
1463
+ const pks = entity?.EntityInfo?.PrimaryKeys;
1464
+ if (!pks || pks.length === 0 || !Array.isArray(currentData)) {
1465
+ return currentData.indexOf(entity);
1466
+ }
1467
+ const signature = primaryKeySignature(pks);
1468
+ let index = primaryKeyIndexes.get(currentData);
1469
+ if (!index || index.signature !== signature || index.length !== currentData.length || index.last !== currentData[currentData.length - 1]) {
1470
+ index = buildPrimaryKeyIndex(currentData, pks, signature);
1471
+ }
1472
+ if (index && !index.refs.has(entity)) {
1473
+ return -1;
1474
+ }
1475
+ if (index?.map) {
1476
+ const key = primaryKeyOfRow(entity, pks);
1477
+ if (key !== undefined) {
1478
+ const pos = index.map.get(key);
1479
+ if (pos !== undefined && currentData[pos] === entity) {
1480
+ return pos;
1481
+ }
1482
+ }
1483
+ }
1484
+ return currentData.indexOf(entity);
1485
+ }
1205
1486
  /**
1206
1487
  * Index of `entity` in `currentData` by reference, else by primary key. When `preDeleteValues`
1207
1488
  * carries a complete key it is the ONLY key used: after a delete the live entity's key has
@@ -1209,20 +1490,63 @@ export class BaseEngine extends BaseSingleton {
1209
1490
  * {@link isEntityInArrayByRefOrKey}).
1210
1491
  */
1211
1492
  indexOfEntityByRefOrKey(currentData, entity, preDeleteValues) {
1212
- const byRef = currentData.indexOf(entity);
1493
+ const byRef = this.indexOfEntityByRefFast(currentData, entity);
1213
1494
  if (byRef >= 0) {
1214
1495
  return byRef;
1215
1496
  }
1216
1497
  if (preDeleteValues) {
1217
- const key = new CompositeKey();
1218
- key.LoadFromEntityInfoAndRecord(entity.EntityInfo, preDeleteValues);
1219
- if (key.KeyValuePairs.length > 0 && !key.KeyValuePairs.some(kv => kv.Value == null)) {
1220
- return currentData.findIndex(e => e.PrimaryKey.Equals(key));
1498
+ const bySnapshot = this.findEntityIndexByRecordPrimaryKeys(currentData, entity?.EntityInfo, preDeleteValues);
1499
+ if (bySnapshot !== undefined) {
1500
+ return bySnapshot;
1221
1501
  }
1222
1502
  }
1223
1503
  // Fallback: the entity's current primary key
1224
1504
  return this.findEntityIndexByPrimaryKeys(currentData, entity);
1225
1505
  }
1506
+ /**
1507
+ * Looks up a plain pre-delete field snapshot (`OldValues`) in `currentData` via `PrimaryKeyIndex`
1508
+ * in `O(1)` when all primary key fields are present; returns `undefined` when the snapshot does
1509
+ * not carry a complete key so the caller can fall back to `entity`'s current key.
1510
+ */
1511
+ findEntityIndexByRecordPrimaryKeys(dataArray, entityInfo, record) {
1512
+ const pks = entityInfo?.PrimaryKeys;
1513
+ if (pks && pks.length > 0 && Array.isArray(dataArray)) {
1514
+ const hasCompleteKey = !pks.some(pk => record[pk.Name] == null);
1515
+ if (!hasCompleteKey) {
1516
+ return undefined;
1517
+ }
1518
+ const key = primaryKeyOfRecord(record, pks);
1519
+ if (key !== undefined) {
1520
+ const signature = primaryKeySignature(pks);
1521
+ let index = primaryKeyIndexes.get(dataArray);
1522
+ if (!index || index.signature !== signature || index.length !== dataArray.length || index.last !== dataArray[dataArray.length - 1]) {
1523
+ index = buildPrimaryKeyIndex(dataArray, pks, signature);
1524
+ }
1525
+ for (let attempt = 0; attempt < 2; attempt++) {
1526
+ if (!index || !index.map) {
1527
+ break;
1528
+ }
1529
+ const pos = index.map.get(key);
1530
+ if (pos === undefined) {
1531
+ return -1;
1532
+ }
1533
+ if (rowHasPrimaryKey(dataArray, pos, pks, key)) {
1534
+ return pos;
1535
+ }
1536
+ index = attempt === 0 ? buildPrimaryKeyIndex(dataArray, pks, signature) : null;
1537
+ }
1538
+ }
1539
+ }
1540
+ if (!entityInfo) {
1541
+ return undefined;
1542
+ }
1543
+ const compositeKey = new CompositeKey();
1544
+ compositeKey.LoadFromEntityInfoAndRecord(entityInfo, record);
1545
+ if (compositeKey.KeyValuePairs.length > 0 && !compositeKey.KeyValuePairs.some(kv => kv.Value == null)) {
1546
+ return dataArray.findIndex(e => e.PrimaryKey.Equals(compositeKey));
1547
+ }
1548
+ return undefined;
1549
+ }
1226
1550
  /**
1227
1551
  * Emits change notifications for a config whose backing array ALREADY reflects the
1228
1552
  * entity event — e.g., engine code saved the array's own cached instance in place,
@@ -1252,6 +1576,9 @@ export class BaseEngine extends BaseSingleton {
1252
1576
  if (!currentData) {
1253
1577
  return;
1254
1578
  }
1579
+ if (changeType !== 'update') {
1580
+ primaryKeyIndexDropped(currentData);
1581
+ }
1255
1582
  this.NotifyDataChange(config, currentData, changeType, entity);
1256
1583
  this.emitPropertyChange(config.PropertyName);
1257
1584
  }
@@ -1329,11 +1656,41 @@ export class BaseEngine extends BaseSingleton {
1329
1656
  * (e.g., applyRemoteRecordData applies all config mutations then calls AdditionalLoading).
1330
1657
  * @returns true if immediate mutation is safe, false if a full view refresh is needed
1331
1658
  */
1659
+ isStructuredFilter(filter) {
1660
+ return filter != null && typeof filter === 'object';
1661
+ }
1662
+ evaluateStructuredConfigFilter(filter, entity) {
1663
+ const compiled = filter instanceof CompositeFilter ? filter : CompositeFilter.FromDescriptor(filter);
1664
+ return compiled.Evaluate({ '': entity.GetAll() });
1665
+ }
1666
+ /**
1667
+ * Filters the in-memory array stored at `propertyName` using a structured
1668
+ * {@link CompositeFilterDescriptor}, {@link CompositeFilter}, or single {@link FilterDescriptor}.
1669
+ *
1670
+ * Works with both `BaseEntity` instances (reading fields via `GetAll()`) and plain `'simple'`
1671
+ * record objects.
1672
+ */
1673
+ Where(propertyName, filter) {
1674
+ const items = this[propertyName];
1675
+ if (!Array.isArray(items) || items.length === 0) {
1676
+ return [];
1677
+ }
1678
+ const compiled = filter instanceof CompositeFilter ? filter : CompositeFilter.FromDescriptor(filter);
1679
+ return items.filter((item) => {
1680
+ if (item == null || typeof item !== 'object')
1681
+ return false;
1682
+ const maybeEntity = item;
1683
+ const row = typeof maybeEntity.GetAll === 'function'
1684
+ ? maybeEntity.GetAll()
1685
+ : item;
1686
+ return compiled.Evaluate({ '': row });
1687
+ });
1688
+ }
1332
1689
  canUseImmediateMutation(config, skipAdditionalLoadingCheck = false) {
1333
- // If there's a filter, we can't safely do immediate mutations because:
1334
- // - For creates: the new entity might not match the filter
1335
- // - For updates: the entity might now match or no longer match the filter
1336
- if (config.Filter) {
1690
+ // If there's a string SQL filter, we can't safely do immediate mutations in memory because
1691
+ // SQL predicates cannot be evaluated client-side. Structured CompositeFilter configs CAN be
1692
+ // evaluated in memory via CompositeFilter.Evaluate().
1693
+ if (typeof config.Filter === 'string' && config.Filter.trim().length > 0) {
1337
1694
  return false;
1338
1695
  }
1339
1696
  // An AlternateBaseView applies a canonical SQL WHERE/JOIN in the database view;
@@ -1414,65 +1771,68 @@ export class BaseEngine extends BaseSingleton {
1414
1771
  }
1415
1772
  const entity = event.baseEntity;
1416
1773
  if (event.type === 'save') {
1417
- // Clone the entity so the cache holds an instance owned by THIS engine's provider,
1418
- // not the saving provider. Falling back to the original entity here would reintroduce
1419
- // the leak, so on clone failure we bail and let the next full refresh fix the cache.
1420
- const cached = await this.cloneEntityForCache(entity, config);
1421
- if (!cached) {
1422
- LogError(`BaseEngine.applyImmediateMutation: failed to clone entity for ${config.EntityName}; skipping immediate mutation`);
1423
- return;
1424
- }
1425
- if (event.saveSubType === 'create') {
1426
- // For create, first check if the exact object is already in the array
1427
- const existsByRef = currentData.indexOf(entity) >= 0;
1428
- if (!existsByRef) {
1429
- // Check by composite primary key in case it was added with a different object reference
1430
- const indexByKey = this.findEntityIndexByPrimaryKeys(currentData, entity);
1431
- if (indexByKey >= 0) {
1432
- // Already exists by key, treat as update
1433
- currentData[indexByKey] = cached;
1774
+ if (this.isStructuredFilter(config.Filter)) {
1775
+ const matches = this.evaluateStructuredConfigFilter(config.Filter, entity);
1776
+ if (!matches) {
1777
+ const existingIndex = this.indexOfEntityByRefOrKey(currentData, entity);
1778
+ if (existingIndex >= 0) {
1779
+ const removed = currentData[existingIndex];
1780
+ currentData.splice(existingIndex, 1);
1781
+ primaryKeyIndexRemoved(currentData, existingIndex, removed);
1434
1782
  this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1435
- this.NotifyDataChange(config, currentData, 'update', cached);
1436
- }
1437
- else {
1438
- // Add the new entity to the array
1439
- currentData.push(cached);
1440
- this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1441
- this.NotifyDataChange(config, currentData, 'add', cached);
1783
+ this.NotifyDataChange(config, currentData, 'delete', entity);
1784
+ this.emitPropertyChange(config.PropertyName);
1785
+ if (config.CacheLocal) {
1786
+ this.syncLocalCacheForConfig(config, event).catch(e => {
1787
+ LogWarning(`BaseEngine: Failed to sync local cache for ${config.EntityName}: ${e}`, 'Cache');
1788
+ });
1789
+ }
1442
1790
  }
1791
+ return;
1443
1792
  }
1444
- else {
1793
+ }
1794
+ // Check reference membership in O(1) BEFORE cloning: when an engine mutates and saves
1795
+ // its own cached instance in place (or pushes a new entity before Save settles), we
1796
+ // skip constructing + hydrating a throwaway clone altogether.
1797
+ const existsByRef = this.indexOfEntityByRefFast(currentData, entity) >= 0;
1798
+ if (existsByRef) {
1799
+ if (event.saveSubType === 'create') {
1445
1800
  // Already in the array by reference (engine code pushed it manually after
1446
1801
  // Save) — the array is current, but DataChange$ subscribers still need to
1447
- // hear about the change. Pass the in-array instance, not the clone.
1802
+ // hear about the change. Pass the in-array instance, not a clone.
1803
+ primaryKeyIndexDropped(currentData);
1448
1804
  this.NotifyDataChange(config, currentData, 'add', entity);
1449
1805
  }
1450
- }
1451
- else {
1452
- // Update: first check if the exact object is already in the array
1453
- const existsByRef = currentData.indexOf(entity) >= 0;
1454
- if (!existsByRef) {
1455
- // Find by composite primary key and replace
1456
- const index = this.findEntityIndexByPrimaryKeys(currentData, entity);
1457
- if (index >= 0) {
1458
- currentData[index] = cached;
1459
- this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1460
- this.NotifyDataChange(config, currentData, 'update', cached);
1461
- }
1462
- else {
1463
- // Entity not found in array - this shouldn't happen normally,
1464
- // but if it does, add it (might have been created before we started listening)
1465
- currentData.push(cached);
1466
- this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1467
- this.NotifyDataChange(config, currentData, 'add', cached);
1468
- }
1469
- }
1470
1806
  else {
1471
1807
  // In-place save of the array's own cached instance — the array is already
1472
1808
  // current, but DataChange$ subscribers still need to hear about the change.
1473
1809
  this.NotifyDataChange(config, currentData, 'update', entity);
1474
1810
  }
1475
1811
  }
1812
+ else {
1813
+ // Clone the entity so the cache holds an instance owned by THIS engine's provider,
1814
+ // not the saving provider. Falling back to the original entity here would reintroduce
1815
+ // the leak, so on clone failure we bail and let the next full refresh fix the cache.
1816
+ const cached = await this.cloneEntityForCache(entity, config);
1817
+ if (!cached) {
1818
+ LogError(`BaseEngine.applyImmediateMutation: failed to clone entity for ${config.EntityName}; skipping immediate mutation`);
1819
+ return;
1820
+ }
1821
+ const indexByKey = this.findEntityIndexByPrimaryKeys(currentData, entity);
1822
+ if (indexByKey >= 0) {
1823
+ const prev = currentData[indexByKey];
1824
+ currentData[indexByKey] = cached;
1825
+ primaryKeyIndexReplaced(currentData, indexByKey, cached, prev);
1826
+ this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1827
+ this.NotifyDataChange(config, currentData, 'update', cached);
1828
+ }
1829
+ else {
1830
+ currentData.push(cached);
1831
+ primaryKeyIndexAppended(currentData, cached);
1832
+ this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1833
+ this.NotifyDataChange(config, currentData, 'add', cached);
1834
+ }
1835
+ }
1476
1836
  }
1477
1837
  else if (event.type === 'delete') {
1478
1838
  // Match on the pre-delete snapshot: when this runs deferred (after the enclosing
@@ -1480,7 +1840,9 @@ export class BaseEngine extends BaseSingleton {
1480
1840
  const oldValues = event.payload?.OldValues;
1481
1841
  const index = this.indexOfEntityByRefOrKey(currentData, entity, oldValues);
1482
1842
  if (index >= 0) {
1843
+ const removed = currentData[index];
1483
1844
  currentData.splice(index, 1);
1845
+ primaryKeyIndexRemoved(currentData, index, removed);
1484
1846
  this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: currentData, loadedSuccessfully: true });
1485
1847
  this.NotifyDataChange(config, currentData, 'delete', entity);
1486
1848
  }
@@ -1496,6 +1858,12 @@ export class BaseEngine extends BaseSingleton {
1496
1858
  });
1497
1859
  }
1498
1860
  }
1861
+ instantiateEntityForHydration(provider, entityName, contextUser) {
1862
+ if (provider.GetEntityObjectWithOptions) {
1863
+ return provider.GetEntityObjectWithOptions(entityName, { SkipNewRecord: true }, contextUser);
1864
+ }
1865
+ return provider.GetEntityObject(entityName, contextUser);
1866
+ }
1499
1867
  /**
1500
1868
  * Creates a fresh BaseEntity owned by this engine's provider and populates it from the
1501
1869
  * given source entity's field values. Used by applyImmediateMutation to avoid pinning
@@ -1507,7 +1875,7 @@ export class BaseEngine extends BaseSingleton {
1507
1875
  if (!provider) {
1508
1876
  return null;
1509
1877
  }
1510
- const fresh = await provider.GetEntityObject(config.EntityName, this._contextUser);
1878
+ const fresh = await this.instantiateEntityForHydration(provider, config.EntityName, this._contextUser);
1511
1879
  if (!fresh) {
1512
1880
  return null;
1513
1881
  }
@@ -1567,7 +1935,7 @@ export class BaseEngine extends BaseSingleton {
1567
1935
  const updatedAt = rawUpdatedAt
1568
1936
  ? new Date(rawUpdatedAt).toISOString()
1569
1937
  : new Date().toISOString();
1570
- if (event.type === 'delete') {
1938
+ if (event.type === 'delete' || (this.isStructuredFilter(config.Filter) && !this.evaluateStructuredConfigFilter(config.Filter, entity))) {
1571
1939
  await LocalCacheManager.Instance.RemoveSingleEntity(fingerprint, key, updatedAt);
1572
1940
  }
1573
1941
  else {
@@ -1585,11 +1953,49 @@ export class BaseEngine extends BaseSingleton {
1585
1953
  * Finds an entity in the array by matching all primary key columns.
1586
1954
  * Supports composite primary keys by comparing all PrimaryKey fields from EntityInfo.
1587
1955
  *
1956
+ * Uses a key index per array, built on first use. A hit is checked against the row at the
1957
+ * indexed position, and the index is rebuilt when that check fails or when the array's length
1958
+ * or last row differ from what the index was built for. A miss on a current index reads no row.
1959
+ *
1588
1960
  * @param dataArray - The array of entities to search
1589
1961
  * @param targetEntity - The entity to find (using its primary key values)
1590
1962
  * @returns The index of the matching entity, or -1 if not found
1591
1963
  */
1592
1964
  findEntityIndexByPrimaryKeys(dataArray, targetEntity) {
1965
+ const pks = targetEntity?.EntityInfo?.PrimaryKeys;
1966
+ if (!pks || pks.length === 0 || !Array.isArray(dataArray)) {
1967
+ return this.scanForPrimaryKeys(dataArray, targetEntity);
1968
+ }
1969
+ const key = primaryKeyOfRow(targetEntity, pks);
1970
+ if (key === undefined) {
1971
+ return this.scanForPrimaryKeys(dataArray, targetEntity);
1972
+ }
1973
+ const signature = primaryKeySignature(pks);
1974
+ let index = primaryKeyIndexes.get(dataArray);
1975
+ if (!index || index.signature !== signature || index.length !== dataArray.length || index.last !== dataArray[dataArray.length - 1]) {
1976
+ index = buildPrimaryKeyIndex(dataArray, pks, signature);
1977
+ }
1978
+ for (let attempt = 0; attempt < 2; attempt++) {
1979
+ if (!index || !index.map) {
1980
+ return this.scanForPrimaryKeys(dataArray, targetEntity);
1981
+ }
1982
+ const pos = index.map.get(key);
1983
+ if (pos === undefined) {
1984
+ return -1;
1985
+ }
1986
+ if (rowHasPrimaryKey(dataArray, pos, pks, key)) {
1987
+ return pos;
1988
+ }
1989
+ index = attempt === 0 ? buildPrimaryKeyIndex(dataArray, pks, signature) : null;
1990
+ }
1991
+ return this.scanForPrimaryKeys(dataArray, targetEntity);
1992
+ }
1993
+ /**
1994
+ * Finds an entity by comparing primary key values row by row. Used for entities without
1995
+ * PrimaryKeys metadata, when the key index cannot represent a key value, and when a hit fails
1996
+ * its check again after a rebuild.
1997
+ */
1998
+ scanForPrimaryKeys(dataArray, targetEntity) {
1593
1999
  const primaryKeys = targetEntity.EntityInfo.PrimaryKeys;
1594
2000
  if (!primaryKeys || primaryKeys.length === 0) {
1595
2001
  // Fallback to single PrimaryKey property if no PrimaryKeys defined
@@ -1597,11 +2003,11 @@ export class BaseEngine extends BaseSingleton {
1597
2003
  return dataArray.findIndex(e => e.PrimaryKey.ToString() === pkValue);
1598
2004
  }
1599
2005
  // Get target entity's primary key values
1600
- const targetKeyValues = primaryKeys.map(pk => targetEntity[pk.Name]);
2006
+ const targetKeyValues = primaryKeys.map(pk => readEntityFieldValue(targetEntity, pk.Name));
1601
2007
  return dataArray.findIndex(e => {
1602
2008
  // Compare all primary key values
1603
2009
  return primaryKeys.every((pk, idx) => {
1604
- const entityValue = e[pk.Name];
2010
+ const entityValue = readEntityFieldValue(e, pk.Name);
1605
2011
  const targetValue = targetKeyValues[idx];
1606
2012
  // UUID columns must compare case-insensitively: the SAME id can arrive with
1607
2013
  // different casing depending on its source (a client-minted lowercase UUID from
@@ -1646,8 +2052,14 @@ export class BaseEngine extends BaseSingleton {
1646
2052
  const configsToLoad = this.CheckPermissionsOrSkipAll(this._metadataConfigs, contextUser);
1647
2053
  const entityConfigsToLoad = configsToLoad.filter(c => c.Type === 'entity');
1648
2054
  const datasetConfigsToLoad = configsToLoad.filter(c => c.Type === 'dataset');
1649
- await Promise.all([...datasetConfigsToLoad.map(c => this.LoadSingleDatasetConfig(c, contextUser, bypassCache)),
1650
- this.LoadMultipleEntityConfigs(entityConfigsToLoad, contextUser, bypassCache)]);
2055
+ try {
2056
+ await Promise.all([...datasetConfigsToLoad.map(c => this.LoadSingleDatasetConfig(c, contextUser, bypassCache)),
2057
+ this.LoadMultipleEntityConfigs(entityConfigsToLoad, contextUser, bypassCache)]);
2058
+ }
2059
+ finally {
2060
+ // Runs even when a read threw, so a failed load still starts (or stops) the timed refresh.
2061
+ this.reconcileExpirationTimers();
2062
+ }
1651
2063
  // Register cross-server cache change callbacks for entity configs
1652
2064
  this.RegisterCacheChangeCallbacks(entityConfigs);
1653
2065
  }
@@ -1890,10 +2302,12 @@ export class BaseEngine extends BaseSingleton {
1890
2302
  * and field-security segments; see {@link configFingerprint}.
1891
2303
  */
1892
2304
  BuildRunViewParamsForConfig(config, bypassCache = false) {
2305
+ const isStructured = this.isStructuredFilter(config.Filter);
1893
2306
  return {
1894
2307
  EntityName: config.EntityName,
1895
2308
  ResultType: config.ResultType || this.EngineDefaultResultType,
1896
- ExtraFilter: config.Filter,
2309
+ ExtraFilter: typeof config.Filter === 'string' ? config.Filter : undefined,
2310
+ ...(isStructured ? { Filter: config.Filter } : {}),
1897
2311
  OrderBy: config.OrderBy,
1898
2312
  ...(config.AlternateBaseView ? { AlternateBaseView: config.AlternateBaseView } : {}),
1899
2313
  IgnoreMaxRows: true, // Engines always need ALL data — bypass entity-level UserViewMaxRows caps
@@ -2137,18 +2551,21 @@ export class BaseEngine extends BaseSingleton {
2137
2551
  const provider = this.ProviderToUse;
2138
2552
  if (!provider)
2139
2553
  continue;
2140
- const cached = await provider.GetEntityObject(mapping.entityName, this._contextUser);
2141
- if (!cached)
2142
- continue;
2143
- await cached.LoadFromData(entity.GetAll());
2144
- const existsByRef = currentData.indexOf(entity) >= 0;
2554
+ const existsByRef = this.indexOfEntityByRefFast(currentData, entity) >= 0;
2145
2555
  if (!existsByRef) {
2556
+ const cached = await this.instantiateEntityForHydration(provider, mapping.entityName, this._contextUser);
2557
+ if (!cached)
2558
+ continue;
2559
+ await cached.LoadFromData(entity.GetAll());
2146
2560
  const index = this.findEntityIndexByPrimaryKeys(currentData, entity);
2147
2561
  if (index >= 0) {
2562
+ const prev = currentData[index];
2148
2563
  currentData[index] = cached;
2564
+ primaryKeyIndexReplaced(currentData, index, cached, prev);
2149
2565
  }
2150
2566
  else {
2151
2567
  currentData.push(cached);
2568
+ primaryKeyIndexAppended(currentData, cached);
2152
2569
  }
2153
2570
  }
2154
2571
  mutated = true;
@@ -2158,7 +2575,9 @@ export class BaseEngine extends BaseSingleton {
2158
2575
  const oldValues = event.payload?.OldValues;
2159
2576
  const index = this.indexOfEntityByRefOrKey(currentData, entity, oldValues);
2160
2577
  if (index >= 0) {
2578
+ const removed = currentData[index];
2161
2579
  currentData.splice(index, 1);
2580
+ primaryKeyIndexRemoved(currentData, index, removed);
2162
2581
  mutated = true;
2163
2582
  notifiedProperties.add(mapping.config.PropertyName);
2164
2583
  }
@@ -2237,7 +2656,7 @@ export class BaseEngine extends BaseSingleton {
2237
2656
  const singleObject = {};
2238
2657
  await Promise.all(result.Results.map(async (item) => {
2239
2658
  const entities = await Promise.all(item.Results.map(async (entityData) => {
2240
- const entity = await p.GetEntityObject(item.EntityName, contextUser);
2659
+ const entity = await this.instantiateEntityForHydration(p, item.EntityName, contextUser);
2241
2660
  await entity.LoadFromData(entityData);
2242
2661
  return entity;
2243
2662
  }));
@@ -2487,19 +2906,30 @@ export class BaseEngine extends BaseSingleton {
2487
2906
  const entityInfo = config.EntityName ? this.ProviderToUse?.EntityByName?.(config.EntityName) : undefined;
2488
2907
  const pkFields = delta.primaryKeyFields;
2489
2908
  const isUuidPk = pkFields.map(fieldName => Boolean(entityInfo?.FieldByName(fieldName)?.IsUniqueIdentifier));
2490
- const heldIndexByKey = this.indexHeldRowsForDelta(heldRows, pkFields, isUuidPk);
2491
- if (!heldIndexByKey) {
2909
+ const deltaSignature = pkFields
2910
+ .map((fieldName, idx) => `${isUuidPk[idx] ? 'u:' : 's:'}${fieldName}`)
2911
+ .join('\u001f');
2912
+ let heldDeltaIndex = this.getOrBuildHeldRowsDeltaIndex(heldRows, pkFields, isUuidPk, deltaSignature);
2913
+ if (!heldDeltaIndex) {
2492
2914
  return 'reload';
2493
2915
  }
2494
- const keyPlan = this.planRowDeltaKeys(delta, heldRows.length, heldIndexByKey, pkFields, isUuidPk);
2495
- if (!keyPlan) {
2916
+ let keyPlan = this.planRowDeltaKeys(delta, heldRows, heldDeltaIndex.map, pkFields, isUuidPk);
2917
+ if (keyPlan === 'stale_index') {
2918
+ deltaHeldRowIndexes.delete(heldRows);
2919
+ heldDeltaIndex = this.getOrBuildHeldRowsDeltaIndex(heldRows, pkFields, isUuidPk, deltaSignature);
2920
+ if (!heldDeltaIndex) {
2921
+ return 'reload';
2922
+ }
2923
+ keyPlan = this.planRowDeltaKeys(delta, heldRows, heldDeltaIndex.map, pkFields, isUuidPk);
2924
+ }
2925
+ if (!keyPlan || keyPlan === 'stale_index') {
2496
2926
  return 'reload';
2497
2927
  }
2498
2928
  // Echo / duplicate delta suppression: when no rows are added or removed and every
2499
2929
  // upserted row's __mj_UpdatedAt matches the held row, skip materialization & emit churn.
2500
2930
  if (keyPlan.matchedDeleteKeys.size === 0 &&
2501
2931
  keyPlan.netNewInserts === 0 &&
2502
- this.upsertsMatchHeldTimestamps(heldRows, heldIndexByKey, delta.upsertedRows, keyPlan.upsertKeys, entityInfo)) {
2932
+ this.upsertsMatchHeldTimestamps(heldRows, heldDeltaIndex.map, delta.upsertedRows, keyPlan.upsertKeys, entityInfo)) {
2503
2933
  LogStatusEx({ message: `BaseEngine.OnExternalCacheChange: '${config.PropertyName}' already holds row_delta versions — skipped`, verboseOnly: true });
2504
2934
  return 'applied';
2505
2935
  }
@@ -2514,7 +2944,15 @@ export class BaseEngine extends BaseSingleton {
2514
2944
  (this._inFlightFullRefreshCount.get(config.PropertyName) ?? 0) > 0) {
2515
2945
  return 'superseded';
2516
2946
  }
2517
- const nextRows = this.mergeMaterializedDeltaRows(heldRows, pkFields, isUuidPk, keyPlan.matchedDeleteKeys, keyPlan.upsertKeys, materializedUpserts);
2947
+ // Re-verify heldRows did not change while materializeCacheEventRows awaited.
2948
+ const currentHeldRows = this.getHeldRowsForDelta(config);
2949
+ if (currentHeldRows !== heldRows ||
2950
+ heldDeltaIndex.length !== heldRows.length ||
2951
+ heldDeltaIndex.first !== heldRows[0] ||
2952
+ heldDeltaIndex.last !== heldRows[heldRows.length - 1]) {
2953
+ return 'reload';
2954
+ }
2955
+ const nextRows = this.mergeMaterializedDeltaRows(heldRows, heldDeltaIndex, deltaSignature, keyPlan.matchedDeleteKeys, keyPlan.upsertKeys, materializedUpserts);
2518
2956
  this.HandleSingleViewResult(config, {
2519
2957
  Success: true,
2520
2958
  Results: nextRows,
@@ -2528,25 +2966,48 @@ export class BaseEngine extends BaseSingleton {
2528
2966
  this.emitPropertyChange(config.PropertyName);
2529
2967
  return 'applied';
2530
2968
  }
2531
- indexHeldRowsForDelta(heldRows, pkFields, isUuidPk) {
2532
- const heldIndexByKey = new Map();
2969
+ getOrBuildHeldRowsDeltaIndex(heldRows, pkFields, isUuidPk, signature) {
2970
+ const cached = deltaHeldRowIndexes.get(heldRows);
2971
+ if (cached &&
2972
+ cached.signature === signature &&
2973
+ cached.length === heldRows.length &&
2974
+ cached.first === heldRows[0] &&
2975
+ cached.last === heldRows[heldRows.length - 1]) {
2976
+ return cached;
2977
+ }
2978
+ const map = new Map();
2979
+ const keys = new Array(heldRows.length);
2533
2980
  for (let i = 0; i < heldRows.length; i++) {
2534
2981
  const key = this.canonicalHeldRowPkKey(heldRows[i], pkFields, isUuidPk);
2535
- if (key === null) {
2982
+ if (key === null || map.has(key)) {
2536
2983
  return null;
2537
2984
  }
2538
- heldIndexByKey.set(key, i);
2985
+ map.set(key, i);
2986
+ keys[i] = key;
2539
2987
  }
2540
- return heldIndexByKey.size === heldRows.length ? heldIndexByKey : null;
2988
+ const built = {
2989
+ signature,
2990
+ length: heldRows.length,
2991
+ first: heldRows[0],
2992
+ last: heldRows[heldRows.length - 1],
2993
+ map,
2994
+ keys,
2995
+ };
2996
+ deltaHeldRowIndexes.set(heldRows, built);
2997
+ return built;
2541
2998
  }
2542
- planRowDeltaKeys(delta, heldRowCount, heldIndexByKey, pkFields, isUuidPk) {
2999
+ planRowDeltaKeys(delta, heldRows, heldIndexByKey, pkFields, isUuidPk) {
2543
3000
  const matchedDeleteKeys = new Set();
2544
3001
  for (const delPk of delta.deletedPrimaryKeys) {
2545
3002
  const key = this.canonicalPlainRecordPkKey(delPk, pkFields, isUuidPk);
2546
3003
  if (key === null) {
2547
3004
  return null;
2548
3005
  }
2549
- if (heldIndexByKey.has(key)) {
3006
+ const pos = heldIndexByKey.get(key);
3007
+ if (pos !== undefined) {
3008
+ if (pos >= heldRows.length || this.canonicalHeldRowPkKey(heldRows[pos], pkFields, isUuidPk) !== key) {
3009
+ return 'stale_index';
3010
+ }
2550
3011
  matchedDeleteKeys.add(key);
2551
3012
  }
2552
3013
  }
@@ -2560,42 +3021,119 @@ export class BaseEngine extends BaseSingleton {
2560
3021
  }
2561
3022
  seenUpsertKeys.add(key);
2562
3023
  upsertKeys.push(key);
2563
- if (!heldIndexByKey.has(key) || matchedDeleteKeys.has(key)) {
3024
+ const pos = heldIndexByKey.get(key);
3025
+ if (pos !== undefined) {
3026
+ if (pos >= heldRows.length || this.canonicalHeldRowPkKey(heldRows[pos], pkFields, isUuidPk) !== key) {
3027
+ return 'stale_index';
3028
+ }
3029
+ }
3030
+ if (pos === undefined || matchedDeleteKeys.has(key)) {
2564
3031
  netNewInserts++;
2565
3032
  }
2566
3033
  }
2567
3034
  // Strict cardinality verification: detects uninitialized state, missed pub/sub messages,
2568
3035
  // or filtered-slot membership divergence and falls back to reading the warm cache slot.
2569
- const expectedNextLength = heldRowCount - matchedDeleteKeys.size + netNewInserts;
3036
+ const expectedNextLength = heldRows.length - matchedDeleteKeys.size + netNewInserts;
2570
3037
  if (expectedNextLength !== delta.rowCount) {
2571
3038
  return null;
2572
3039
  }
2573
3040
  return { matchedDeleteKeys, upsertKeys, netNewInserts };
2574
3041
  }
2575
- mergeMaterializedDeltaRows(heldRows, pkFields, isUuidPk, matchedDeleteKeys, upsertKeys, materializedUpserts) {
2576
- const upsertByKey = new Map();
2577
- for (let i = 0; i < upsertKeys.length; i++) {
2578
- upsertByKey.set(upsertKeys[i], materializedUpserts[i]);
2579
- }
2580
- const consumedUpsertKeys = new Set();
2581
- const nextRows = [];
2582
- for (let i = 0; i < heldRows.length; i++) {
2583
- const existingRow = heldRows[i];
2584
- const key = this.canonicalHeldRowPkKey(existingRow, pkFields, isUuidPk);
2585
- if (upsertByKey.has(key)) {
2586
- nextRows.push(upsertByKey.get(key));
2587
- consumedUpsertKeys.add(key);
2588
- }
2589
- else if (!matchedDeleteKeys.has(key)) {
2590
- nextRows.push(existingRow);
3042
+ mergeMaterializedDeltaRows(heldRows, heldDeltaIndex, signature, matchedDeleteKeys, upsertKeys, materializedUpserts) {
3043
+ // Fast O(Δ) path when no rows are deleted (updates and/or net-new appends):
3044
+ // native `slice()` shallow-copies the backing array in C++ without reading any fields on
3045
+ // untouched rows, updates changed slots in place, appends net-new rows, and carries the
3046
+ // updated key index forward to `nextRows`.
3047
+ if (matchedDeleteKeys.size === 0) {
3048
+ const nextRows = heldRows.slice();
3049
+ deltaHeldRowIndexes.delete(heldRows);
3050
+ const nextMap = heldDeltaIndex.map;
3051
+ const nextKeys = heldDeltaIndex.keys;
3052
+ for (let i = 0; i < upsertKeys.length; i++) {
3053
+ const key = upsertKeys[i];
3054
+ const existingIdx = nextMap.get(key);
3055
+ if (existingIdx !== undefined) {
3056
+ nextRows[existingIdx] = materializedUpserts[i];
3057
+ }
3058
+ else {
3059
+ const appendedIdx = nextRows.length;
3060
+ nextRows.push(materializedUpserts[i]);
3061
+ nextKeys.push(key);
3062
+ nextMap.set(key, appendedIdx);
3063
+ }
2591
3064
  }
2592
- }
3065
+ deltaHeldRowIndexes.set(nextRows, {
3066
+ signature,
3067
+ length: nextRows.length,
3068
+ first: nextRows[0],
3069
+ last: nextRows[nextRows.length - 1],
3070
+ map: nextMap,
3071
+ keys: nextKeys,
3072
+ });
3073
+ return nextRows;
3074
+ }
3075
+ // Delete + optional upsert path: update surviving upserts via O(1) index lookup,
3076
+ // compact out deleted indices using `heldDeltaIndex.keys` without re-extracting PKs
3077
+ // from untouched rows, and carry the compacted index forward to `nextRows`.
3078
+ deltaHeldRowIndexes.delete(heldRows);
3079
+ const workingRows = heldRows.slice();
3080
+ const workingKeys = heldDeltaIndex.keys;
3081
+ const nextMap = heldDeltaIndex.map;
3082
+ const netNewRows = [];
3083
+ const netNewKeys = [];
2593
3084
  for (let i = 0; i < upsertKeys.length; i++) {
2594
3085
  const key = upsertKeys[i];
2595
- if (!consumedUpsertKeys.has(key)) {
2596
- nextRows.push(upsertByKey.get(key));
3086
+ const existingIdx = nextMap.get(key);
3087
+ if (existingIdx !== undefined && !matchedDeleteKeys.has(key)) {
3088
+ workingRows[existingIdx] = materializedUpserts[i];
2597
3089
  }
2598
- }
3090
+ else {
3091
+ netNewRows.push(materializedUpserts[i]);
3092
+ netNewKeys.push(key);
3093
+ }
3094
+ }
3095
+ const deletedIndices = [];
3096
+ for (const delKey of matchedDeleteKeys) {
3097
+ const idx = nextMap.get(delKey);
3098
+ if (idx !== undefined) {
3099
+ deletedIndices.push(idx);
3100
+ nextMap.delete(delKey);
3101
+ }
3102
+ }
3103
+ deletedIndices.sort((a, b) => a - b);
3104
+ const nextLen = workingRows.length - deletedIndices.length + netNewRows.length;
3105
+ const nextRows = new Array(nextLen);
3106
+ const nextKeys = new Array(nextLen);
3107
+ let writePos = 0;
3108
+ let delCursor = 0;
3109
+ const minChangedPos = deletedIndices[0] ?? workingRows.length;
3110
+ for (let readPos = 0; readPos < workingRows.length; readPos++) {
3111
+ if (delCursor < deletedIndices.length && readPos === deletedIndices[delCursor]) {
3112
+ delCursor++;
3113
+ continue;
3114
+ }
3115
+ nextRows[writePos] = workingRows[readPos];
3116
+ const rowKey = workingKeys[readPos];
3117
+ nextKeys[writePos] = rowKey;
3118
+ if (writePos >= minChangedPos) {
3119
+ nextMap.set(rowKey, writePos);
3120
+ }
3121
+ writePos++;
3122
+ }
3123
+ for (let i = 0; i < netNewRows.length; i++) {
3124
+ nextRows[writePos] = netNewRows[i];
3125
+ nextKeys[writePos] = netNewKeys[i];
3126
+ nextMap.set(netNewKeys[i], writePos);
3127
+ writePos++;
3128
+ }
3129
+ deltaHeldRowIndexes.set(nextRows, {
3130
+ signature,
3131
+ length: nextRows.length,
3132
+ first: nextRows[0],
3133
+ last: nextRows[nextRows.length - 1],
3134
+ map: nextMap,
3135
+ keys: nextKeys,
3136
+ });
2599
3137
  return nextRows;
2600
3138
  }
2601
3139
  getHeldRowsForDelta(config) {
@@ -2693,15 +3231,23 @@ export class BaseEngine extends BaseSingleton {
2693
3231
  *
2694
3232
  * @param bypassCache - Read past the cache. When any request folded into a reload asks for
2695
3233
  * it, that reload bypasses the cache.
3234
+ * @param key - The one row this request is about, when it knows. A reload whose requests all
3235
+ * named their rows re-reads only those rows; one request without a key makes it a full reload.
2696
3236
  */
2697
- reloadAfterExternalChange(config, bypassCache = false) {
3237
+ reloadAfterExternalChange(config, bypassCache = false, key = null) {
2698
3238
  const running = this._externalChangeReloads.get(config.PropertyName);
2699
3239
  if (running) {
2700
3240
  running.Again = true;
2701
3241
  running.BypassCache = running.BypassCache || bypassCache;
3242
+ running.Keys = this.addReloadKey(running.Keys, key);
2702
3243
  return running.Done;
2703
3244
  }
2704
- const reload = { Again: false, BypassCache: bypassCache, Done: Promise.resolve() };
3245
+ const reload = {
3246
+ Again: false,
3247
+ BypassCache: bypassCache,
3248
+ Keys: this.addReloadKey(new Map(), key),
3249
+ Done: Promise.resolve()
3250
+ };
2705
3251
  this._externalChangeReloads.set(config.PropertyName, reload);
2706
3252
  reload.Done = this.runExternalChangeReloads(config, reload);
2707
3253
  return reload.Done;
@@ -2722,9 +3268,11 @@ export class BaseEngine extends BaseSingleton {
2722
3268
  await new Promise(resolve => setTimeout(resolve, wait));
2723
3269
  }
2724
3270
  const bypassCache = reload.BypassCache;
3271
+ const keys = reload.Keys;
2725
3272
  reload.Again = false;
2726
3273
  reload.BypassCache = false;
2727
- lastError = await this.runOneExternalChangeReload(config, bypassCache);
3274
+ reload.Keys = new Map();
3275
+ lastError = await this.runOneExternalChangeReload(config, bypassCache, keys);
2728
3276
  this._externalChangeReloadEndedAt.set(config.PropertyName, Date.now());
2729
3277
  if (lastError && reload.Again) {
2730
3278
  LogError(lastError);
@@ -2743,14 +3291,34 @@ export class BaseEngine extends BaseSingleton {
2743
3291
  const endedAt = this._externalChangeReloadEndedAt.get(propertyName);
2744
3292
  return endedAt === undefined ? 0 : Math.max(0, endedAt + BaseEngine.ExternalChangeFollowUpDelayMs - Date.now());
2745
3293
  }
2746
- /** One reload for {@link runExternalChangeReloads}. Returns the error it threw, or null. */
2747
- async runOneExternalChangeReload(config, bypassCache) {
3294
+ /**
3295
+ * Folds one request's key into a round's key set. Null (a full reload) absorbs everything: a
3296
+ * request without a key, or a round that already needs a full reload, stays a full reload.
3297
+ */
3298
+ addReloadKey(keys, key) {
3299
+ if (keys === null || key === null) {
3300
+ return null;
3301
+ }
3302
+ keys.set(key.ToConcatenatedString(), key);
3303
+ return keys;
3304
+ }
3305
+ /**
3306
+ * One reload for {@link runExternalChangeReloads}. Returns the error it threw, or null.
3307
+ * When the round named its rows and the config qualifies (see {@link canRefetchRowsByKey}), only
3308
+ * those rows are re-read; otherwise, or when that read fails, the whole config is reloaded.
3309
+ */
3310
+ async runOneExternalChangeReload(config, bypassCache, keys = null) {
2748
3311
  try {
2749
- // The reload replaces the property, so the derived state has to be rebuilt too —
2750
- // and the reload must NOT emit on its own, or a subscriber wakes between the new
3312
+ // Either path changes the property, so the derived state has to be rebuilt too —
3313
+ // and neither may emit on its own, or a subscriber wakes between the new
2751
3314
  // rows and the rebuild and reads derived state still pointing at the instances
2752
3315
  // this reload discarded.
2753
- await this.LoadSingleConfig(config, this._contextUser, bypassCache, /*suppressEmit*/ true);
3316
+ const refetched = keys !== null && keys.size > 0 && this.canRefetchRowsByKey(config, keys)
3317
+ ? await this.RefetchConfigRowsByKey(config, Array.from(keys.values()))
3318
+ : false;
3319
+ if (!refetched) {
3320
+ await this.LoadSingleConfig(config, this._contextUser, bypassCache, /*suppressEmit*/ true);
3321
+ }
2754
3322
  await this.RebuildDerivedState(this._contextUser);
2755
3323
  this.emitPropertyChange(config.PropertyName);
2756
3324
  return null;
@@ -2759,6 +3327,151 @@ export class BaseEngine extends BaseSingleton {
2759
3327
  return e instanceof Error ? e : new Error(String(e));
2760
3328
  }
2761
3329
  }
3330
+ /**
3331
+ * Whether a no-row-data invalidation round for `config` can re-read just the named rows instead
3332
+ * of the whole table. It cannot when: the config is a dataset; it has an `OrderBy` (the database's
3333
+ * collation decides order, and re-sorting in JS could differ); the entity does not resolve or has
3334
+ * a composite primary key; a key names another field; there are more keys than
3335
+ * {@link KeyedRefetchMaxKeys}; the config is not loaded; or a full refresh of it is in flight.
3336
+ */
3337
+ canRefetchRowsByKey(config, keys) {
3338
+ if (config.Type === 'dataset' || !config.EntityName || (config.OrderBy && config.OrderBy.trim().length > 0)) {
3339
+ return false;
3340
+ }
3341
+ if (keys.size > BaseEngine.KeyedRefetchMaxKeys) {
3342
+ return false;
3343
+ }
3344
+ if ((this._inFlightFullRefreshCount.get(config.PropertyName) ?? 0) > 0) {
3345
+ return false;
3346
+ }
3347
+ const entry = this._dataMap.get(config.PropertyName);
3348
+ if (!entry?.loadedSuccessfully || !Array.isArray(entry.data)) {
3349
+ return false;
3350
+ }
3351
+ const entityInfo = this.ProviderToUse?.EntityByName?.(config.EntityName);
3352
+ if (!entityInfo || entityInfo.PrimaryKeys.length !== 1) {
3353
+ return false;
3354
+ }
3355
+ const pkName = entityInfo.FirstPrimaryKey.Name.trim().toLowerCase(); // first-pk-ok: guarded by PrimaryKeys.length === 1 just above
3356
+ for (const key of keys.values()) {
3357
+ if (key.KeyValuePairs.length !== 1 || key.KeyValuePairs[0].FieldName.trim().toLowerCase() !== pkName) {
3358
+ return false;
3359
+ }
3360
+ }
3361
+ return true;
3362
+ }
3363
+ /**
3364
+ * Re-reads the given rows of `config` and applies them in place: a returned row replaces the held
3365
+ * one with its key or is appended; a requested key that is not returned is removed (deleted,
3366
+ * filtered out, or no longer visible to the engine's user). One RunView, the config's own filter
3367
+ * AND the key list, past the cache, as the engine's user on the engine's provider.
3368
+ *
3369
+ * Does not emit or rebuild derived state; the caller does both once.
3370
+ *
3371
+ * @returns true when applied; false when the caller must reload the whole config instead (the
3372
+ * read failed, or a key could not be written as a SQL literal).
3373
+ */
3374
+ async RefetchConfigRowsByKey(config, keys) {
3375
+ const entityInfo = this.ProviderToUse.EntityByName(config.EntityName);
3376
+ const pkField = entityInfo.FirstPrimaryKey; // first-pk-ok: only reached after canRefetchRowsByKey confirmed a single-column key
3377
+ const literals = [];
3378
+ for (const key of keys) {
3379
+ const literal = this.keyLiteral(key.KeyValuePairs[0].Value, pkField.NeedsQuotes);
3380
+ if (literal === null) {
3381
+ return false;
3382
+ }
3383
+ literals.push(literal);
3384
+ }
3385
+ const keyFilter = `${pkField.Name} IN (${literals.join(', ')})`;
3386
+ const stringFilter = typeof config.Filter === 'string' ? config.Filter.trim() : '';
3387
+ const params = {
3388
+ ...this.BuildRunViewParamsForConfig(config, /*bypassCache*/ true),
3389
+ ExtraFilter: stringFilter.length > 0 ? `(${stringFilter}) AND ${keyFilter}` : keyFilter,
3390
+ // A one-off read of a few rows: never worth a cache slot of its own.
3391
+ CacheLocal: false,
3392
+ };
3393
+ const generationBefore = this._configRefreshGeneration.get(config.PropertyName) ?? 0;
3394
+ let result;
3395
+ try {
3396
+ result = await new RunView(this.RunViewProviderToUse).RunView(params, this._contextUser);
3397
+ }
3398
+ catch (e) {
3399
+ LogWarning(`BaseEngine: keyed re-fetch of '${config.PropertyName}' threw (${e instanceof Error ? e.message : String(e)}) — reloading the config instead`, 'Cache');
3400
+ return false;
3401
+ }
3402
+ if (!result.Success) {
3403
+ LogWarning(`BaseEngine: keyed re-fetch of '${config.PropertyName}' failed (${result.ErrorMessage}) — reloading the config instead`, 'Cache');
3404
+ return false;
3405
+ }
3406
+ // The config may have been reloaded or dropped while the read ran. A reload that began
3407
+ // meanwhile may hold newer rows than this read, so do not write over it.
3408
+ if ((this._configRefreshGeneration.get(config.PropertyName) ?? 0) !== generationBefore ||
3409
+ (this._inFlightFullRefreshCount.get(config.PropertyName) ?? 0) > 0) {
3410
+ return false;
3411
+ }
3412
+ const heldNow = this.getHeldRowsForDelta(config);
3413
+ if (!heldNow) {
3414
+ return false;
3415
+ }
3416
+ // Write to a copy: the held array can be frozen when it is shared with a cache.
3417
+ const held = [...heldNow];
3418
+ const pkFields = [pkField.Name];
3419
+ const isUuidPk = [Boolean(pkField.IsUniqueIdentifier)];
3420
+ const requested = new Set();
3421
+ for (const key of keys) {
3422
+ requested.add(CanonicalPrimaryKeyValue(String(key.KeyValuePairs[0].Value), isUuidPk[0]));
3423
+ }
3424
+ // Index the held rows once: a burst can name up to KeyedRefetchMaxKeys rows of a large table.
3425
+ const indexByKey = new Map();
3426
+ held.forEach((h, i) => {
3427
+ const k = this.canonicalHeldRowPkKey(h, pkFields, isUuidPk);
3428
+ if (k !== null && !indexByKey.has(k))
3429
+ indexByKey.set(k, i);
3430
+ });
3431
+ const returned = new Set();
3432
+ for (const row of (result.Results ?? [])) {
3433
+ const rowKey = this.canonicalHeldRowPkKey(row, pkFields, isUuidPk);
3434
+ if (rowKey === null)
3435
+ continue;
3436
+ returned.add(rowKey);
3437
+ const index = indexByKey.get(rowKey);
3438
+ if (index !== undefined) {
3439
+ held[index] = row;
3440
+ this.NotifyDataChange(config, held, 'update', row instanceof BaseEntity ? row : undefined);
3441
+ }
3442
+ else {
3443
+ indexByKey.set(rowKey, held.length);
3444
+ held.push(row);
3445
+ this.NotifyDataChange(config, held, 'add', row instanceof BaseEntity ? row : undefined);
3446
+ }
3447
+ }
3448
+ // Removals last, highest index first, so earlier indexes stay valid.
3449
+ const removals = Array.from(requested)
3450
+ .filter(k => !returned.has(k))
3451
+ .map(k => indexByKey.get(k))
3452
+ .filter((i) => i !== undefined)
3453
+ .sort((a, b) => b - a);
3454
+ for (const index of removals) {
3455
+ const [removed] = held.splice(index, 1);
3456
+ this.NotifyDataChange(config, held, 'delete', removed instanceof BaseEntity ? removed : undefined);
3457
+ }
3458
+ if (config.AddToObject !== false) {
3459
+ Reflect.set(this, config.PropertyName, held);
3460
+ }
3461
+ this._dataMap.set(config.PropertyName, { entityName: config.EntityName, data: held, loadedSuccessfully: true });
3462
+ return true;
3463
+ }
3464
+ /** A key value as a SQL literal, or null when it cannot be written safely as one. */
3465
+ keyLiteral(value, needsQuotes) {
3466
+ if (value === null || value === undefined) {
3467
+ return null;
3468
+ }
3469
+ const text = value instanceof Date ? value.toISOString() : String(value);
3470
+ if (!needsQuotes) {
3471
+ return /^-?\d+(\.\d+)?$/.test(text.trim()) ? text.trim() : null;
3472
+ }
3473
+ return `'${text.split("'").join("''")}'`;
3474
+ }
2762
3475
  /**
2763
3476
  * True when `payloadRows` are the same row versions this config currently holds: the same
2764
3477
  * number of rows, and the same multiset of (primary key, `__mj_UpdatedAt`) pairs.
@@ -3111,9 +3824,63 @@ export class BaseEngine extends BaseSingleton {
3111
3824
  if (this._expirationTimers.has(propertyName)) {
3112
3825
  clearTimeout(this._expirationTimers.get(propertyName));
3113
3826
  }
3114
- const timer = setTimeout(() => this.RefreshItem(propertyName), expiration);
3827
+ const timer = setTimeout(() => this.runExpirationRefresh(propertyName, expiration, timer), expiration);
3828
+ // A cache-refresh timer must never keep a Node process alive on its own (CLI tools and
3829
+ // test runners load engines and then expect to exit). Browsers return a number: no-op.
3830
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function') {
3831
+ timer.unref();
3832
+ }
3115
3833
  this._expirationTimers.set(propertyName, timer);
3116
3834
  }
3835
+ /**
3836
+ * Makes the running timers match the loaded configs: a config with an Expiration and no timer
3837
+ * gets one, and a timer whose config no longer has an Expiration is stopped.
3838
+ *
3839
+ * A successful load arms its own timer from {@link HandleSingleViewResult}, but a failed one does
3840
+ * not — without this a failed first load would leave that property with no refresh until restart.
3841
+ * And a reload that drops the Expiration (an interval set to 0) must stop the timer, which
3842
+ * {@link runExpirationRefresh} would otherwise keep re-arming at the old interval.
3843
+ */
3844
+ reconcileExpirationTimers() {
3845
+ for (const c of this._metadataConfigs) {
3846
+ if (c.Expiration && !this._expirationTimers.has(c.PropertyName)) {
3847
+ this.setExpirationTimer(c.PropertyName, c.Expiration);
3848
+ }
3849
+ else if (!c.Expiration && this._expirationTimers.has(c.PropertyName)) {
3850
+ clearTimeout(this._expirationTimers.get(c.PropertyName));
3851
+ this._expirationTimers.delete(c.PropertyName);
3852
+ }
3853
+ }
3854
+ }
3855
+ /**
3856
+ * Runs one timed refresh and keeps the timer alive. A successful load re-arms the timer from
3857
+ * {@link HandleSingleViewResult}; a failed one (an unsuccessful result, or a thrown connection
3858
+ * error) does not, so without this the refresh would stop for good after a single failed read
3859
+ * and the property would keep its last rows indefinitely.
3860
+ * The re-arm uses the config as it is now, so a reload that dropped the Expiration while this
3861
+ * tick was running stops the timer instead of keeping it at the old interval.
3862
+ * @param timer - The handle that fired; if the map no longer holds it, a successful load, a
3863
+ * {@link reconcileExpirationTimers} or a {@link RemoveDynamicConfig} already
3864
+ * decided what happens next.
3865
+ */
3866
+ async runExpirationRefresh(propertyName, expiration, timer) {
3867
+ try {
3868
+ await this.RefreshItem(propertyName);
3869
+ }
3870
+ catch (e) {
3871
+ LogError(`${this.constructor.name}: timed refresh of ${propertyName} failed — ${e.message}. Retrying in ${expiration} ms.`);
3872
+ }
3873
+ if (this._expirationTimers.get(propertyName) !== timer) {
3874
+ return;
3875
+ }
3876
+ const config = this._metadataConfigs.find(c => c.PropertyName === propertyName) || this._dynamicConfigs.get(propertyName);
3877
+ if (config?.Expiration) {
3878
+ this.setExpirationTimer(propertyName, config.Expiration);
3879
+ }
3880
+ else {
3881
+ this._expirationTimers.delete(propertyName);
3882
+ }
3883
+ }
3117
3884
  /**
3118
3885
  * Adds a dynamic metadata configuration at runtime.
3119
3886
  * @param config - The metadata configuration to add
@@ -3150,7 +3917,9 @@ export class BaseEngine extends BaseSingleton {
3150
3917
  async RefreshItem(propertyName) {
3151
3918
  const config = this._metadataConfigs.find(c => c.PropertyName === propertyName) || this._dynamicConfigs.get(propertyName);
3152
3919
  if (config) {
3153
- await this.LoadSingleConfig(config, this._contextUser, /*bypassCache*/ false, /*suppressEmit*/ true);
3920
+ // A config with an Expiration exists to pick up changes made outside this process, which
3921
+ // the local cache never hears about — so its timed refresh must read the database.
3922
+ await this.LoadSingleConfig(config, this._contextUser, /*bypassCache*/ !!config.Expiration, /*suppressEmit*/ true);
3154
3923
  await this.RebuildDerivedState(this._contextUser);
3155
3924
  this.emitPropertyChange(config.PropertyName);
3156
3925
  }