@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
@@ -19,7 +19,7 @@ import { ExplorerNavigationItem } from "./explorerNavigationItem.js";
19
19
  import { Metadata } from "./metadata.js";
20
20
  import { RunView, IsMaterializedDataSource, ExtractRunViewParameterNames } from "../views/runView.js";
21
21
  import { IsPlatformSQL } from "./platformSQL.js";
22
- import { GetDataHooks } from "./dataHooks.js";
22
+ import { GetDataHooks, IsPostRunViewProtectedEntity } from "./dataHooks.js";
23
23
  import { TransformSimpleObjectToEntityObject } from "./util.js";
24
24
  import { LoadRelatedRecordsBatched } from "./relatedRecordBatchLoader.js";
25
25
  import { GetLocalTimeZone } from "./contextTokens.js";
@@ -115,6 +115,39 @@ export const AllMetadataArrays = [
115
115
  { key: 'AllLibraries', class: LibraryInfo },
116
116
  { key: 'AllExplorerNavigationItems', class: ExplorerNavigationItem }
117
117
  ];
118
+ /**
119
+ * Produces a canonical, order- and case-insensitive key for a requested `Fields` list, suitable
120
+ * for keying memoized row projections and wire-serialization caches. Returns `''` when no field
121
+ * list is provided.
122
+ */
123
+ export function CanonicalFieldsKey(fields) {
124
+ if (!fields || fields.length === 0) {
125
+ return '';
126
+ }
127
+ const unique = new Set();
128
+ for (const f of fields) {
129
+ const normalized = f.trim().toLowerCase();
130
+ if (normalized.length > 0) {
131
+ unique.add(normalized);
132
+ }
133
+ }
134
+ if (unique.size === 0) {
135
+ return '';
136
+ }
137
+ return Array.from(unique).sort().join(',');
138
+ }
139
+ /**
140
+ * Memoizes frozen subset-projected row objects per `(sourceRow, canonicalFieldsKey)` when
141
+ * `ProjectRowsToFields` runs with `{ PreserveFrozen: true }` on frozen L1/cache rows. Weakly
142
+ * keyed on the source row so entries are automatically garbage-collected when cache slots evict.
143
+ */
144
+ const FrozenProjectedRowCache = new WeakMap();
145
+ /**
146
+ * Memoizes the entire frozen projected result array per `(frozenSourceArray, canonicalFieldsKey)`
147
+ * when `ProjectRowsToFields` runs with `{ PreserveFrozen: true }` on a frozen cached array.
148
+ * Turns repeat N-row subset projections into a single O(1) WeakMap lookup.
149
+ */
150
+ const FrozenProjectedArrayCache = new WeakMap();
118
151
  /**
119
152
  * Projects plain-object rows down to a caller-requested field subset, matching
120
153
  * field names case-insensitively (and ignoring surrounding whitespace).
@@ -131,11 +164,22 @@ export const AllMetadataArrays = [
131
164
  *
132
165
  * @param rows - Plain-object result rows (NOT BaseEntity objects)
133
166
  * @param requestedFields - The caller's original Fields list, or null for "all fields"
167
+ * @param options - Optional mutability/freeze preservation controls
134
168
  */
135
- export function ProjectRowsToFields(rows, requestedFields) {
169
+ export function ProjectRowsToFields(rows, requestedFields, options) {
136
170
  if (!requestedFields || requestedFields.length === 0 || !rows || rows.length === 0) {
137
171
  return rows;
138
172
  }
173
+ const preserveFrozen = Boolean(options?.PreserveFrozen);
174
+ const rowsAreFrozen = Object.isFrozen(rows);
175
+ const canonicalKey = preserveFrozen ? CanonicalFieldsKey(requestedFields) : '';
176
+ // O(1) array-level hit for repeat subset projections over the same frozen cached array.
177
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
178
+ const cachedArray = FrozenProjectedArrayCache.get(rows)?.get(canonicalKey);
179
+ if (cachedArray) {
180
+ return cachedArray;
181
+ }
182
+ }
139
183
  const requestedFieldSet = new Set(requestedFields.map(f => f.trim().toLowerCase()));
140
184
  // No-op probe: SQL result rows are uniform (same SELECT list), so if every key of
141
185
  // the first row is requested, the projection would copy every row unchanged —
@@ -155,18 +199,28 @@ export function ProjectRowsToFields(rows, requestedFields) {
155
199
  // to yield a per-caller row set the caller may mutate, and full coverage is not a
156
200
  // narrower promise than partial coverage — it just happens to project to the same
157
201
  // shape. Frozen input means `rows` is the cache's shared array, so returning it here
158
- // would quietly hand a Fields caller immutable rows and break that contract for the
159
- // one field list that covers everything. Fall through to the copy path in that case;
160
- // unfrozen input (the DB-miss path) keeps the allocation-free fast path.
161
- if (!Object.isFrozen(rows)) {
202
+ // would quietly hand a Fields caller immutable rows and break that contract unless
203
+ // the caller explicitly opts into `PreserveFrozen: true` (read-only wire transport).
204
+ if (preserveFrozen || !rowsAreFrozen) {
162
205
  return rows;
163
206
  }
164
207
  }
165
208
  }
166
209
  // Cache lowercase key→keep decisions across rows to avoid repeated allocations
167
210
  const keyCache = new Map();
168
- return rows.map((row) => {
211
+ const projected = rows.map((row) => {
169
212
  const source = row;
213
+ const canMemoizeFrozen = preserveFrozen &&
214
+ canonicalKey.length > 0 &&
215
+ source !== null &&
216
+ typeof source === 'object' &&
217
+ Object.isFrozen(source);
218
+ if (canMemoizeFrozen) {
219
+ const cachedProjected = FrozenProjectedRowCache.get(source)?.get(canonicalKey);
220
+ if (cachedProjected) {
221
+ return cachedProjected;
222
+ }
223
+ }
170
224
  const filtered = {};
171
225
  for (const key of Object.keys(source)) {
172
226
  let keep = keyCache.get(key);
@@ -178,8 +232,27 @@ export function ProjectRowsToFields(rows, requestedFields) {
178
232
  filtered[key] = source[key];
179
233
  }
180
234
  }
235
+ if (canMemoizeFrozen) {
236
+ Object.freeze(filtered);
237
+ let fieldMap = FrozenProjectedRowCache.get(source);
238
+ if (!fieldMap) {
239
+ fieldMap = new Map();
240
+ FrozenProjectedRowCache.set(source, fieldMap);
241
+ }
242
+ fieldMap.set(canonicalKey, filtered);
243
+ }
181
244
  return filtered;
182
245
  });
246
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
247
+ Object.freeze(projected);
248
+ let arrayMap = FrozenProjectedArrayCache.get(rows);
249
+ if (!arrayMap) {
250
+ arrayMap = new Map();
251
+ FrozenProjectedArrayCache.set(rows, arrayMap);
252
+ }
253
+ arrayMap.set(canonicalKey, projected);
254
+ }
255
+ return projected;
183
256
  }
184
257
  /**
185
258
  * Base class for all metadata providers in MemberJunction.
@@ -249,6 +322,14 @@ export class ProviderBase {
249
322
  */
250
323
  this._inflightViews = new Map();
251
324
  this._lingerInvalidationWired = false;
325
+ /**
326
+ * Lazily registers this instance (once per provider instance) for write-invalidation
327
+ * of in-flight/lingered RunView entries touching a written entity. Deleting an IN-FLIGHT
328
+ * entry is deliberate: late joiners must not share a query that may have read pre-commit
329
+ * data; the original caller still gets its own result, and the orphaned promise's stash
330
+ * step no-ops safely.
331
+ */
332
+ this._invalidationTargetRef = null;
252
333
  /**
253
334
  * Per-entity monotonic mutation counter incremented whenever an entity receives a
254
335
  * BaseEntity save/delete/remote-invalidate or an explicit {@link InvalidateRunViewDedupCache}
@@ -300,6 +381,12 @@ export class ProviderBase {
300
381
  this._peerMetadataNoticeRetries = 0;
301
382
  /** Debounce timer for {@link HandlePeerMetadataNotice}. */
302
383
  this._peerMetadataNoticeTimer = null;
384
+ /**
385
+ * One-shot handoff from {@link RefreshAfterMetadataMemberChange} to {@link ReloadMetadata}
386
+ * (via {@link Refresh}) indicating that `_latestRemoteMetadataTimestamps` was just read from
387
+ * the authoritative status query and need not be re-queried on the first pass.
388
+ */
389
+ this._metadataRefreshStampsFresh = false;
303
390
  /**
304
391
  * Set by a write-event refresh that found a reload in flight and queued a follow-up pass; that
305
392
  * pass consumes it and applies {@link applyWriteEventRule}. Without it the follow-up would take
@@ -325,6 +412,9 @@ export class ProviderBase {
325
412
  this._lastRemoteTimestampReadReached = true;
326
413
  /** Guard for {@link logMetadataSnapshotDisabledOnce}. */
327
414
  this._metadataSnapshotSkipLogged = false;
415
+ this._metadataSaveTimer = null;
416
+ this._inFlightMetadataSave = null;
417
+ this._hasPendingMetadataSaveWhileInFlight = false;
328
418
  }
329
419
  /**
330
420
  * Whether this provider can execute a multi-record unit of work atomically, in-process.
@@ -552,12 +642,26 @@ export class ProviderBase {
552
642
  return results;
553
643
  }
554
644
  /**
555
- * Lazily registers this instance (once per provider instance) for write-invalidation
556
- * of in-flight/lingered RunView entries touching a written entity. Deleting an IN-FLIGHT
557
- * entry is deliberate: late joiners must not share a query that may have read pre-commit
558
- * data; the original caller still gets its own result, and the orphaned promise's stash
559
- * step no-ops safely.
645
+ * Number of live/uncollected `ProviderBase` instances currently registered for in-flight
646
+ * view invalidation callbacks.
560
647
  */
648
+ static get ActiveInvalidationTargetCount() {
649
+ return ProviderBase._invalidationTargets.size;
650
+ }
651
+ /**
652
+ * Immediately removes this provider instance from the global in-flight invalidation target set
653
+ * and clears per-instance mutation state. Call on short-lived per-request server providers
654
+ * when the HTTP response closes so `_invalidationTargets` does not accumulate thousands of
655
+ * `WeakRef`s between major garbage collections.
656
+ */
657
+ DetachInvalidationListeners() {
658
+ if (this._invalidationTargetRef) {
659
+ ProviderBase._invalidationTargets.delete(this._invalidationTargetRef);
660
+ this._invalidationTargetRef = null;
661
+ }
662
+ this._lingerInvalidationWired = false;
663
+ this._entityMutationVersions.clear();
664
+ }
561
665
  ensureInflightViewInvalidation() {
562
666
  // Deliberately ABOVE the per-instance guard: the static wiring is re-checked on every call,
563
667
  // not just the first. A long-lived provider (Explorer's client provider, MJServer's system
@@ -569,7 +673,9 @@ export class ProviderBase {
569
673
  return;
570
674
  }
571
675
  this._lingerInvalidationWired = true;
572
- ProviderBase._invalidationTargets.add(new WeakRef(this));
676
+ const ref = new WeakRef(this);
677
+ this._invalidationTargetRef = ref;
678
+ ProviderBase._invalidationTargets.add(ref);
573
679
  }
574
680
  /**
575
681
  * Returns the current monotonic mutation version for `entityName` (case-insensitive).
@@ -717,6 +823,9 @@ export class ProviderBase {
717
823
  names.add(n);
718
824
  }
719
825
  }
826
+ for (const skipped of this.skippedMetadataEntityNames(dataset.Results ?? [])) {
827
+ names.delete(skipped);
828
+ }
720
829
  if (names.size === 0) {
721
830
  return; // a failed/empty load must not erase a previously recorded set
722
831
  }
@@ -732,6 +841,93 @@ export class ProviderBase {
732
841
  }));
733
842
  this.ensureInflightViewInvalidation();
734
843
  }
844
+ /**
845
+ * The MJ_Metadata item codes that hold the saved-query metadata: the saved-query family (see
846
+ * {@link PartialRefreshMetadataItemCodes}) and the SQL dialects. They are read only when the
847
+ * provider is configured with {@link ProviderConfigDataBase.LoadQueryMetadata}.
848
+ */
849
+ static get QueryMetadataItemCodes() {
850
+ return [...ProviderBase._queryFamilyItemCodes, 'SQLDialects'];
851
+ }
852
+ /**
853
+ * Whether this provider loads the saved-query metadata into its metadata object (see
854
+ * {@link ProviderConfigDataBase.LoadQueryMetadata}). False unless the configuration says true.
855
+ * A provider that adopted the global provider's metadata reports the global provider's
856
+ * setting instead, since that is what decided whether the adopted metadata holds queries.
857
+ */
858
+ get LoadsQueryMetadata() {
859
+ return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
860
+ }
861
+ /**
862
+ * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
863
+ * local dataset cache — so all of them describe the same row set. Null when every item is read.
864
+ * Otherwise each item this provider does not load gets a `1=0` filter: the server runs no SQL
865
+ * for it, and its status is constant, so writes to it never make the metadata look stale.
866
+ */
867
+ get MetadataDatasetItemFilters() {
868
+ if (this.LoadsQueryMetadata) {
869
+ return null;
870
+ }
871
+ return ProviderBase.QueryMetadataItemCodes.map(code => ({ ItemCode: code, Filter: '1=0' }));
872
+ }
873
+ /**
874
+ * The MJ_Metadata item codes THIS provider builds its metadata from: {@link MetadataBuildItemCodes}
875
+ * without the items it does not read (see {@link MetadataDatasetItemFilters}). A change only to
876
+ * the others needs no reload, as for any item the build never reads.
877
+ */
878
+ get BuiltMetadataItemCodes() {
879
+ if (this.LoadsQueryMetadata) {
880
+ return ProviderBase.MetadataBuildItemCodes;
881
+ }
882
+ const built = new Set(ProviderBase.MetadataBuildItemCodes);
883
+ for (const code of ProviderBase.QueryMetadataItemCodes) {
884
+ built.delete(code);
885
+ }
886
+ return built;
887
+ }
888
+ /**
889
+ * Empties the query-metadata arrays of `metadata` when this provider does not load them. A stored
890
+ * snapshot written by a process that did load them would otherwise hold those rows in memory for
891
+ * the life of this process, behind getters that return nothing.
892
+ */
893
+ dropUnloadedQueryMetadata(metadata) {
894
+ if (this.LoadsQueryMetadata) {
895
+ return;
896
+ }
897
+ metadata.AllQueryCategories = [];
898
+ metadata.AllQueries = [];
899
+ metadata.AllQueryFields = [];
900
+ metadata.AllQueryPermissions = [];
901
+ metadata.AllQueryEntities = [];
902
+ metadata.AllQueryParameters = [];
903
+ metadata.AllQueryDependencies = [];
904
+ metadata.AllSQLDialects = [];
905
+ metadata.AllQuerySQLs = [];
906
+ }
907
+ /** Whether `code` is an MJ_Metadata item this provider does not read (see {@link MetadataDatasetItemFilters}). */
908
+ isSkippedMetadataItem(code) {
909
+ return !!code && !this.LoadsQueryMetadata && ProviderBase.QueryMetadataItemCodes.includes(code);
910
+ }
911
+ /**
912
+ * Lowercased names of the entities that back only items this provider does not read. A write to
913
+ * one of them cannot change this provider's metadata, so they are left out of the membership set
914
+ * — otherwise each such write would schedule a refresh that finds no timestamp moved and falls
915
+ * back to a full reload.
916
+ */
917
+ skippedMetadataEntityNames(items) {
918
+ const skipped = new Set();
919
+ const read = new Set();
920
+ for (const item of items) {
921
+ const name = item.EntityName?.trim().toLowerCase();
922
+ if (name) {
923
+ (this.isSkippedMetadataItem(item.Code) ? skipped : read).add(name);
924
+ }
925
+ }
926
+ for (const name of read) {
927
+ skipped.delete(name);
928
+ }
929
+ return skipped;
930
+ }
735
931
  /**
736
932
  * Result of {@link SweepMetadataAgainstDatabase}.
737
933
  */
@@ -931,6 +1127,17 @@ export class ProviderBase {
931
1127
  && (event.Category || CacheCategory.Default) === CacheCategory.Default
932
1128
  && event.CacheKey === this.LocalStoragePrefix + ProviderBase.localStorageTimestampsKey;
933
1129
  }
1130
+ /**
1131
+ * True while a peer metadata notice check must wait rather than run immediately.
1132
+ * Defaults to {@link MetadataMemberRefreshMustWait} for providers whose metadata reads
1133
+ * cannot bypass an open transaction. Database providers whose `MJ_Metadata` reads run on
1134
+ * the connection pool regardless of unrelated ambient transactions (#4514) override this
1135
+ * to `false` unless {@link MetadataReadsJoinTransaction} is set, so unrelated background
1136
+ * writes on the global provider (such as scheduled jobs) do not defer peer metadata sync.
1137
+ */
1138
+ get PeerMetadataNoticeMustWait() {
1139
+ return this.MetadataMemberRefreshMustWait;
1140
+ }
934
1141
  /**
935
1142
  * Reacts to another server saving its metadata snapshot: after a short debounce, runs the
936
1143
  * normal staleness check ({@link RefreshIfNeeded}, bypassing the check throttle). The check
@@ -939,6 +1146,11 @@ export class ProviderBase {
939
1146
  * poll. A server that is already current does no refresh and saves nothing, so notices do not
940
1147
  * echo around the fleet.
941
1148
  *
1149
+ * Random thundering-herd jitter ({@link PeerMetadataNoticeJitterMs}) applies only to `removed`
1150
+ * notices (e.g. `mj migrate` clearing the shared snapshot so every server would otherwise query
1151
+ * the database together). On a `set` notice the peer's updated snapshot is already in shared
1152
+ * storage, so only {@link MetadataDatasetRefreshDebounceMs} is waited.
1153
+ *
942
1154
  * @returns true when the event was a metadata notice (and a check was scheduled)
943
1155
  */
944
1156
  HandlePeerMetadataNotice(event) {
@@ -955,21 +1167,24 @@ export class ProviderBase {
955
1167
  if (this._peerMetadataNoticeTimer) {
956
1168
  clearTimeout(this._peerMetadataNoticeTimer);
957
1169
  }
1170
+ const jitterMs = event.Action === 'removed'
1171
+ ? Math.floor(Math.random() * ProviderBase.PeerMetadataNoticeJitterMs)
1172
+ : 0;
958
1173
  const timer = setTimeout(() => {
959
1174
  this._peerMetadataNoticeTimer = null;
960
- // A provider inside a transaction cannot run the check now (its reads would see the
961
- // transaction's own uncommitted world, and SQL Server's RefreshIfNeeded refuses
962
- // outright). Re-arm instead of dropping the notice, which used to lose it entirely.
1175
+ // A provider whose metadata reads would join an open transaction cannot run the check
1176
+ // now (its reads would see the transaction's own uncommitted world). Re-arm instead of
1177
+ // dropping the notice, which used to lose it entirely.
963
1178
  // The deferral budget is deliberately NOT cleared here: it bounds how long one check
964
1179
  // may be put off, and the check has not run yet. Clearing it as the timer fires ended
965
1180
  // the budget exactly when deferral began, leaving the retry count as the only real
966
1181
  // bound.
967
- if (this.MetadataMemberRefreshMustWait) {
1182
+ if (this.PeerMetadataNoticeMustWait) {
968
1183
  this.handlePeerMetadataNoticeRetry();
969
1184
  return;
970
1185
  }
971
1186
  this.runPeerMetadataCheck();
972
- }, ProviderBase.MetadataDatasetRefreshDebounceMs + Math.floor(Math.random() * ProviderBase.PeerMetadataNoticeJitterMs));
1187
+ }, ProviderBase.MetadataDatasetRefreshDebounceMs + jitterMs);
973
1188
  if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
974
1189
  timer.unref();
975
1190
  }
@@ -1008,7 +1223,7 @@ export class ProviderBase {
1008
1223
  }
1009
1224
  const timer = setTimeout(() => {
1010
1225
  this._peerMetadataNoticeTimer = null;
1011
- if (this.MetadataMemberRefreshMustWait) {
1226
+ if (this.PeerMetadataNoticeMustWait) {
1012
1227
  this.handlePeerMetadataNoticeRetry();
1013
1228
  return;
1014
1229
  }
@@ -1100,7 +1315,16 @@ export class ProviderBase {
1100
1315
  return this.ReloadMetadata(true, undefined, true, true);
1101
1316
  }
1102
1317
  LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
1103
- return this.Refresh();
1318
+ // RefreshRemoteMetadataTimestamps() just succeeded above, so let the first ReloadMetadata
1319
+ // pass triggered by Refresh() reuse those timestamps instead of issuing a second full
1320
+ // metadata-status SQL batch back-to-back.
1321
+ this._metadataRefreshStampsFresh = true;
1322
+ try {
1323
+ return await this.Refresh();
1324
+ }
1325
+ finally {
1326
+ this._metadataRefreshStampsFresh = false;
1327
+ }
1104
1328
  }
1105
1329
  /**
1106
1330
  * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
@@ -1199,6 +1423,20 @@ export class ProviderBase {
1199
1423
  get TrustLocalCacheCompletely() {
1200
1424
  return false;
1201
1425
  }
1426
+ /**
1427
+ * Whether {@link CheckToSeeIfRefreshNeeded} may inspect remote timestamps and adopt a newer
1428
+ * snapshot from shared storage. Defaults to {@link AllowRefresh}.
1429
+ *
1430
+ * Providers that transiently suspend {@link AllowRefresh} while a save is running SQL
1431
+ * (such as `SQLServerDataProvider`) can override this to `true`: metadata status queries run
1432
+ * on the connection pool (`ignoreAmbientTransaction`), and adopting a peer's snapshot from
1433
+ * shared storage atomically replaces `_localMetadata` without mutating any `EntityInfo` held
1434
+ * by an in-flight save. Suspending checks on in-flight saves caused peer metadata notices
1435
+ * arriving during background writes (e.g. scheduled jobs) to be silently dropped.
1436
+ */
1437
+ get AllowRefreshCheck() {
1438
+ return this.AllowRefresh;
1439
+ }
1202
1440
  /**
1203
1441
  * Returns a record's name for synchronous display code, or `undefined` when it is not at hand.
1204
1442
  *
@@ -1333,29 +1571,30 @@ export class ProviderBase {
1333
1571
  // BypassCache skips this entirely — used by maintenance actions that need
1334
1572
  // to see the true DB state after direct SQL inserts.
1335
1573
  const preResult = await this.PreRunView(params, contextUser);
1574
+ const effectiveParams = preResult.effectiveParams ?? params;
1336
1575
  if (preResult.cachedResult) {
1337
1576
  // Cache hit — transform and return directly
1338
- LogStatusEx({ message: ` ✅ [Cache HIT] RunView "${params.EntityName || params.ViewName || 'unknown'}" — ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
1339
- await this.TransformSimpleObjectToEntityObject(params, preResult.cachedResult, contextUser);
1340
- await this.ApplyPostRunViewHooksToCacheHit(params, preResult.cachedResult, contextUser);
1577
+ LogStatusEx({ message: ` ✅ [Cache HIT] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || 'unknown'}" — ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
1578
+ await this.TransformSimpleObjectToEntityObject(effectiveParams, preResult.cachedResult, contextUser);
1579
+ await this.ApplyPostRunViewHooksToCacheHit(effectiveParams, preResult.cachedResult, contextUser);
1341
1580
  TelemetryManager.Instance.EndEvent(preResult.telemetryEventId, {
1342
1581
  cacheHit: true,
1343
1582
  cacheStatus: preResult.cacheStatus,
1344
1583
  resultCount: preResult.cachedResult.Results?.length ?? 0
1345
1584
  });
1346
- if (params.OnDataChanged && preResult.fingerprint) {
1347
- preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, params.OnDataChanged);
1585
+ if (effectiveParams.OnDataChanged && preResult.fingerprint) {
1586
+ preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, effectiveParams.OnDataChanged);
1348
1587
  }
1349
- ProviderBase.clearSkippedTotalRowCount(params, preResult.cachedResult);
1588
+ ProviderBase.clearSkippedTotalRowCount(effectiveParams, preResult.cachedResult);
1350
1589
  return preResult.cachedResult;
1351
1590
  }
1352
1591
  // Cache miss — execute query, then post-process (stores in cache)
1353
- LogStatusEx({ message: ` 🔍 [Cache MISS] RunView "${params.EntityName || params.ViewName || 'unknown'}" — querying database`, verboseOnly: true });
1354
- const result = await this.InternalRunView(params, contextUser);
1592
+ LogStatusEx({ message: ` 🔍 [Cache MISS] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || 'unknown'}" — querying database`, verboseOnly: true });
1593
+ const result = await this.InternalRunView(effectiveParams, contextUser);
1355
1594
  // PostRunView copies any hook-supplied replacement onto `result` in place, so this
1356
1595
  // reference reflects the hook chain's output.
1357
- await this.PostRunView(result, params, preResult, contextUser);
1358
- ProviderBase.clearSkippedTotalRowCount(params, result);
1596
+ await this.PostRunView(result, effectiveParams, preResult, contextUser);
1597
+ ProviderBase.clearSkippedTotalRowCount(effectiveParams, result);
1359
1598
  return result;
1360
1599
  }
1361
1600
  // Delegate to RunViews, which uses the smart cache check (lightweight maxUpdatedAt +
@@ -1400,6 +1639,9 @@ export class ProviderBase {
1400
1639
  return this.enqueueCoalescedRunViews(params, contextUser);
1401
1640
  }
1402
1641
  const key = this.generateDedupKey(params, contextUser);
1642
+ if (key === null) {
1643
+ return this.executeRunViewsPipeline(params, contextUser);
1644
+ }
1403
1645
  const existing = this._inflightViews.get(key);
1404
1646
  // ── Linger hit: resolved result still within the linger window ──
1405
1647
  if (existing?.resolvedResults && existing.resolvedAt) {
@@ -1650,6 +1892,11 @@ export class ProviderBase {
1650
1892
  const entryIndices = [];
1651
1893
  for (const param of entry.params) {
1652
1894
  const key = this.generateDedupKey([param], contextUser);
1895
+ if (key === null) {
1896
+ entryIndices.push(uniqueParams.length);
1897
+ uniqueParams.push(param);
1898
+ continue;
1899
+ }
1653
1900
  let idx = uniqueKeys.get(key);
1654
1901
  if (idx === undefined) {
1655
1902
  idx = uniqueParams.length;
@@ -1812,6 +2059,9 @@ export class ProviderBase {
1812
2059
  }
1813
2060
  async runViewsUncoalesced(params, contextUser) {
1814
2061
  const key = this.generateDedupKey(params, contextUser);
2062
+ if (key === null) {
2063
+ return this.executeRunViewsPipeline(params, contextUser);
2064
+ }
1815
2065
  const existing = this._inflightViews.get(key);
1816
2066
  // ── Linger hit ──
1817
2067
  if (existing?.resolvedResults && existing.resolvedAt) {
@@ -2060,7 +2310,18 @@ export class ProviderBase {
2060
2310
  }
2061
2311
  return result;
2062
2312
  }
2313
+ static { this.UUID_VALUE_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; }
2314
+ static normalizeDedupScalarString(value) {
2315
+ const trimmed = value.trim();
2316
+ return ProviderBase.UUID_VALUE_REGEX.test(trimmed) ? NormalizeUUID(trimmed) : trimmed;
2317
+ }
2063
2318
  generateDedupKey(params, contextUser) {
2319
+ const effectiveUser = contextUser ?? this.CurrentUser;
2320
+ const contextScope = this.ComputeRunViewDedupContextScope(effectiveUser);
2321
+ if (contextScope === null) {
2322
+ return null;
2323
+ }
2324
+ const userIdSegment = contextUser?.ID ? NormalizeUUID(contextUser.ID) : '';
2064
2325
  const parts = params.map(p => {
2065
2326
  const base = LocalCacheManager.Instance.GenerateRunViewFingerprint(p, this.InstanceConnectionString);
2066
2327
  const extras = [
@@ -2071,11 +2332,101 @@ export class ProviderBase {
2071
2332
  p.ViewName ?? '',
2072
2333
  IsExplicitBaseViewOverride(p) ? 'abv_override:base' : '',
2073
2334
  p.TimeZone ?? '',
2074
- contextUser?.ID ?? ''
2335
+ userIdSegment
2075
2336
  ].join('|');
2076
2337
  return `${base}|${extras}`;
2077
2338
  });
2078
- return `${parts.join('||')}|||${this.RunViewDedupScope}`;
2339
+ const baseScope = this.RunViewDedupScope;
2340
+ const combinedScope = contextScope
2341
+ ? (baseScope ? `${baseScope}|${contextScope}` : contextScope)
2342
+ : baseScope;
2343
+ return `${parts.join('||')}|||${combinedScope}`;
2344
+ }
2345
+ /**
2346
+ * Per-call security and tenant scope appended to the RunView dedup key alongside
2347
+ * {@link RunViewDedupScope}. Because request deduplication and the linger window run
2348
+ * before `PreRunView` hooks (which inject tenant filters from `contextUser.TenantContext`)
2349
+ * and before RLS evaluation, two callers sharing the same `contextUser.ID` under different
2350
+ * tenant, magic-link, widget-guest, or API-key scopes must never share an in-flight or
2351
+ * lingering dedup slot.
2352
+ *
2353
+ * Returns `''` when the user carries no per-request isolation context, keeping unscoped
2354
+ * dedup keys unchanged. Returns `null` to bypass deduplication for the call when an
2355
+ * unknown / non-primitive `TenantContext` field shape (e.g. a nested object or array of
2356
+ * objects) is present so isolation is never silently weakened. Subclasses may override
2357
+ * this (calling `super`) to fold in additional per-call scope such as async-local tenant state.
2358
+ */
2359
+ ComputeRunViewDedupContextScope(contextUser) {
2360
+ if (!contextUser)
2361
+ return '';
2362
+ const segments = [];
2363
+ if (contextUser.TenantContext) {
2364
+ const scalarEntries = [];
2365
+ for (const [key, value] of Object.entries(contextUser.TenantContext)) {
2366
+ if (value === undefined || value === null) {
2367
+ continue;
2368
+ }
2369
+ if (typeof value === 'string') {
2370
+ // Only lower-case genuine UUIDs; non-UUID tenant IDs can be case-sensitive (e.g. PostgreSQL)
2371
+ scalarEntries.push(`${key}=${ProviderBase.normalizeDedupScalarString(value)}`);
2372
+ }
2373
+ else if (typeof value === 'number' || typeof value === 'boolean') {
2374
+ scalarEntries.push(`${key}=${String(value)}`);
2375
+ }
2376
+ else if (Array.isArray(value) && value.every(v => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')) {
2377
+ const serialized = value
2378
+ .map(v => (typeof v === 'string' ? ProviderBase.normalizeDedupScalarString(v) : String(v)))
2379
+ .sort()
2380
+ .join(',');
2381
+ scalarEntries.push(`${key}=[${serialized}]`);
2382
+ }
2383
+ else {
2384
+ // Fail closed: nested objects or arrays of objects cannot be safely folded
2385
+ // into a flat scalar key, so bypass dedup for this call.
2386
+ return null;
2387
+ }
2388
+ }
2389
+ scalarEntries.sort();
2390
+ segments.push(`tc:${scalarEntries.join(',')}`);
2391
+ }
2392
+ if (contextUser.MagicLinkScope) {
2393
+ const rt = (contextUser.MagicLinkScope.ResourceType ?? '').trim().toLowerCase();
2394
+ const rid = contextUser.MagicLinkScope.ResourceID ? NormalizeUUID(contextUser.MagicLinkScope.ResourceID) : '';
2395
+ segments.push(`ml:${rt}:${rid}`);
2396
+ }
2397
+ if (contextUser.APIKeyActingContext) {
2398
+ const ak = contextUser.APIKeyActingContext;
2399
+ const orgId = ak.ActingOrganizationID ? NormalizeUUID(ak.ActingOrganizationID) : '';
2400
+ const personId = ak.ActingPersonID ? NormalizeUUID(ak.ActingPersonID) : '';
2401
+ const scopeId = (ak.ActingScopeID ?? '').trim().toLowerCase();
2402
+ const companies = (ak.ActingCompanyIDs ?? []).map(id => NormalizeUUID(id)).sort().join(',');
2403
+ segments.push(`ak:${orgId}:${personId}:${scopeId}:${companies}`);
2404
+ }
2405
+ if (contextUser.APIKeyRowFilters && contextUser.APIKeyRowFilters.length > 0) {
2406
+ const filters = contextUser.APIKeyRowFilters
2407
+ .map(f => `${NormalizeUUID(f.EntityID)}:${f.PermissionType}:${NormalizeUUID(f.FilterID)}`)
2408
+ .sort()
2409
+ .join(',');
2410
+ segments.push(`akf:${filters}`);
2411
+ }
2412
+ if (contextUser.WidgetGuestContext) {
2413
+ const widgetId = contextUser.WidgetGuestContext.WidgetID
2414
+ ? NormalizeUUID(contextUser.WidgetGuestContext.WidgetID)
2415
+ : '';
2416
+ segments.push(`wg:${widgetId}`);
2417
+ }
2418
+ if (contextUser.AnonymousVisitorID) {
2419
+ segments.push(`av:${contextUser.AnonymousVisitorID.trim().toLowerCase()}`);
2420
+ }
2421
+ if (contextUser.IsMagicLinkAnonymous) {
2422
+ const roles = (contextUser.UserRoles ?? [])
2423
+ .map(r => (r.RoleID ? NormalizeUUID(r.RoleID) : ''))
2424
+ .filter(Boolean)
2425
+ .sort()
2426
+ .join(',');
2427
+ segments.push(`mla:1:${roles}`);
2428
+ }
2429
+ return segments.join('|');
2079
2430
  }
2080
2431
  /**
2081
2432
  * What, besides the request itself and the user, decides whether two identical RunViews may
@@ -2507,7 +2858,10 @@ export class ProviderBase {
2507
2858
  * `resolvable` is true.
2508
2859
  *
2509
2860
  * The BASE implementation resolves from the metadata `Queries` cache and enforces the
2510
- * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer.
2861
+ * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer. That cache
2862
+ * is loaded only when the provider is configured with `LoadQueryMetadata`; otherwise every
2863
+ * request is unresolvable here, so a provider that executes or caches saved queries overrides
2864
+ * this to resolve from `QueryEngine`.
2511
2865
  * Providers with richer query metadata MUST override this to enforce the SAME authorization
2512
2866
  * their miss path enforces (`GenericDatabaseProvider` overrides with
2513
2867
  * `MJQueryEntityExtended.UserCanRun`, which adds entity CanRead + recursive composition
@@ -2517,6 +2871,9 @@ export class ProviderBase {
2517
2871
  * the miss path also checked entity read permissions).
2518
2872
  */
2519
2873
  ResolveQueryCacheAuthorization(params, user) {
2874
+ if (!this.LoadsQueryMetadata) {
2875
+ return { resolvable: false, authorized: false };
2876
+ }
2520
2877
  const requestedPath = params.CategoryPath?.trim().toLowerCase();
2521
2878
  const qInfo = this.Queries.find(q => (params.QueryID && UUIDsEqual(q.ID, params.QueryID))
2522
2879
  || (!params.QueryID && params.QueryName
@@ -3541,6 +3898,7 @@ export class ProviderBase {
3541
3898
  // PostRunView to project cache-miss DB results back to the caller's shape
3542
3899
  callerRequestedFields: callerRequestedFieldsForPost,
3543
3900
  populateCache: willPopulateCache,
3901
+ effectiveParams: params,
3544
3902
  };
3545
3903
  }
3546
3904
  /**
@@ -4373,7 +4731,7 @@ export class ProviderBase {
4373
4731
  async RunPreRunViewHooks(params, contextUser) {
4374
4732
  const hooks = GetDataHooks('PreRunView');
4375
4733
  for (const hook of hooks) {
4376
- params = await hook(params, contextUser);
4734
+ params = await hook(params, contextUser, this);
4377
4735
  }
4378
4736
  return params;
4379
4737
  }
@@ -4391,7 +4749,7 @@ export class ProviderBase {
4391
4749
  async RunPostRunViewHooks(params, result, contextUser) {
4392
4750
  const hooks = GetDataHooks('PostRunView');
4393
4751
  for (const hook of hooks) {
4394
- result = await hook(params, result, contextUser);
4752
+ result = await hook(params, result, contextUser, this);
4395
4753
  }
4396
4754
  return result;
4397
4755
  }
@@ -4539,6 +4897,10 @@ export class ProviderBase {
4539
4897
  // wasted `Fields` widening and futile cache lookups.
4540
4898
  if (entity.ExternalDataSourceID)
4541
4899
  return false;
4900
+ // PostRunView-protected entities enforce per-caller ACL filtering inside PostRunView hooks
4901
+ // from sibling permission tables whose mutations never change this entity's table timestamps.
4902
+ if (IsPostRunViewProtectedEntity(entity.Name))
4903
+ return false;
4542
4904
  return entity.TrustServerCacheCompletely !== false;
4543
4905
  }
4544
4906
  shouldAutoCache(params, result, contextUser) {
@@ -5054,8 +5416,23 @@ export class ProviderBase {
5054
5416
  * @param data - Configuration including schema filters and connection info
5055
5417
  * @returns True if configuration was successful
5056
5418
  */
5419
+ /**
5420
+ * Synchronously configures this provider from an already-initialized global `Metadata.Provider`
5421
+ * without allocating promises or awaiting async cache initialization. Returns `false` if global
5422
+ * metadata or `LocalCacheManager` has not finished initializing yet.
5423
+ */
5424
+ ConfigureFromGlobalMetadataSync(data) {
5425
+ if (!Metadata.Provider || data.IgnoreExistingMetadata || this._refresh || !LocalCacheManager.Instance.IsInitialized) { // global-provider-ok: bootstrap checks for an existing global registration
5426
+ return false;
5427
+ }
5428
+ this._ConfigData = data;
5429
+ this._adoptedLoadsQueryMetadata = undefined;
5430
+ this._configLoadedFromServer = false;
5431
+ return this.CopyMetadataFromGlobalProvider();
5432
+ }
5057
5433
  async Config(data, providerToUse) {
5058
5434
  this._ConfigData = data;
5435
+ this._adoptedLoadsQueryMetadata = undefined;
5059
5436
  // Describes THIS Config only: a flag left by an earlier Refresh() must not make the
5060
5437
  // pre-validation that follows a Config which loaded nothing skip its check.
5061
5438
  this._configLoadedFromServer = false;
@@ -5172,10 +5549,12 @@ export class ProviderBase {
5172
5549
  await this._metadataReloadInFlight;
5173
5550
  return true;
5174
5551
  }
5552
+ const initialStampsFresh = stampsFresh || this._metadataRefreshStampsFresh;
5553
+ this._metadataRefreshStampsFresh = false;
5175
5554
  this._metadataReloadInFlight = (async () => {
5176
5555
  let effectiveHardRefresh = hardRefresh;
5177
5556
  let tryScoped = scopedFirst;
5178
- let timestampsFresh = stampsFresh;
5557
+ let timestampsFresh = initialStampsFresh;
5179
5558
  do {
5180
5559
  this._metadataReloadQueued = false;
5181
5560
  // The local timestamps must describe the snapshot about to be loaded. On the
@@ -5311,7 +5690,7 @@ export class ProviderBase {
5311
5690
  const rollup = norm(ProviderBase._allMetadataTypeName);
5312
5691
  const prevLocal = this._latestLocalMetadataTimestamps ?? [];
5313
5692
  const datasetItems = this._metadataDatasetItems;
5314
- const built = ProviderBase.MetadataBuildItemCodes;
5693
+ const built = this.BuiltMetadataItemCodes;
5315
5694
  const resRecord = res;
5316
5695
  let hasMismatch = false;
5317
5696
  const reconciled = [];
@@ -5396,7 +5775,7 @@ export class ProviderBase {
5396
5775
  if (!hasMismatch) {
5397
5776
  return remote;
5398
5777
  }
5399
- this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName).catch(() => { });
5778
+ this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters).catch(() => { });
5400
5779
  const remoteRollup = remote.find(r => norm(r.Type) === rollup);
5401
5780
  if (remoteRollup) {
5402
5781
  const priorRollup = prevLocal.find(m => norm(m.Type) === rollup);
@@ -5437,7 +5816,7 @@ export class ProviderBase {
5437
5816
  return { Kind: 'full', Reason: 'the metadata timestamps are not known' };
5438
5817
  }
5439
5818
  const family = new Set(ProviderBase.PartialRefreshMetadataItemCodes);
5440
- const built = ProviderBase.MetadataBuildItemCodes;
5819
+ const built = this.BuiltMetadataItemCodes;
5441
5820
  const norm = (v) => (v ?? '').trim().toLowerCase();
5442
5821
  const rollup = norm(ProviderBase._allMetadataTypeName);
5443
5822
  let anyItemChanged = false;
@@ -5520,8 +5899,9 @@ export class ProviderBase {
5520
5899
  }
5521
5900
  try {
5522
5901
  const keep = new Set(codes);
5902
+ // Items this provider does not load stay unread even when they are in the family.
5523
5903
  const skipOthers = items
5524
- .filter(item => !keep.has(item.Code))
5904
+ .filter(item => !keep.has(item.Code) || this.isSkippedMetadataItem(item.Code))
5525
5905
  .map(item => ({ ItemCode: item.Code, Filter: '1=0' }));
5526
5906
  const start = Date.now();
5527
5907
  const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, skipOthers, this.CurrentUser, providerToUse, true);
@@ -5785,6 +6165,9 @@ export class ProviderBase {
5785
6165
  else {
5786
6166
  this.UpdateLocalMetadata(adopted);
5787
6167
  }
6168
+ if (globalProvider instanceof ProviderBase) {
6169
+ this._adoptedLoadsQueryMetadata = globalProvider.LoadsQueryMetadata;
6170
+ }
5788
6171
  return true;
5789
6172
  }
5790
6173
  return false;
@@ -5882,9 +6265,10 @@ export class ProviderBase {
5882
6265
  // NOTE: Schema filters (IncludeSchemas/ExcludeSchemas) are for CodeGen only, not for runtime
5883
6266
  // metadata loading. We always load all schemas — there are no sys/staging entities in metadata anyway.
5884
6267
  const mutationSeqAtStart = this._metadataMemberMutationSeq;
6268
+ const itemFilters = this.MetadataDatasetItemFilters;
5885
6269
  // Get the dataset and cache it for anyone else who wants to use it
5886
6270
  // When forceRefresh is true (from a hard Refresh() call), bypass LocalCacheManager
5887
- const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse, forceRefresh);
6271
+ const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, itemFilters, this.CurrentUser, providerToUse, forceRefresh);
5888
6272
  // A dataset with no entities is a failed read, whatever its Success flag says: there
5889
6273
  // is no deployment in which MJ_Metadata legitimately holds zero entities. Returning
5890
6274
  // undefined here keeps the metadata already loaded (Config() treats undefined as
@@ -5909,16 +6293,15 @@ export class ProviderBase {
5909
6293
  this._metadataMemberMutationSeq !== mutationSeqAtStart ||
5910
6294
  this.hasDatasetRemoteRowCountMismatch(d);
5911
6295
  if (!mutatedDuringLoad) {
5912
- await this.CacheDataset(ProviderBase._mjMetadataDatasetName, null, d);
6296
+ await this.CacheDataset(ProviderBase._mjMetadataDatasetName, itemFilters, d);
5913
6297
  }
5914
6298
  else {
5915
- await this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName);
5916
- }
5917
- // got the results, let's build our response in the format we need
5918
- const simpleMetadata = {};
5919
- for (let r of d.Results) {
5920
- simpleMetadata[r.Code] = r.Results;
6299
+ await this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName, itemFilters);
5921
6300
  }
6301
+ // got the results, let's build our response in the format we need. The assembly
6302
+ // below attaches child collections to rows, so it works on copies of those rows:
6303
+ // the dataset's own rows stay exactly as read (see metadataAssemblyInput).
6304
+ const simpleMetadata = ProviderBase.metadataAssemblyInput(d);
5922
6305
  // Post Process Entities because there's some special handling of the sub-objects
5923
6306
  simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews, simpleMetadata.EntityUniqueKeys);
5924
6307
  // Post Process the Applications, because we want to handle the sub-objects properly.
@@ -5945,6 +6328,31 @@ export class ProviderBase {
5945
6328
  this._lastMetadataLoadError = e instanceof Error ? e : new Error(String(e));
5946
6329
  }
5947
6330
  }
6331
+ /**
6332
+ * The MJ_Metadata item codes whose rows the metadata assembly writes to: entity rows get their
6333
+ * fields, permissions, relationships, settings, organic keys, alternate views and unique keys;
6334
+ * field rows their values and field permissions; organic keys their related entities;
6335
+ * applications their entities and settings. The entity array is also sorted.
6336
+ */
6337
+ static { this._assemblyWrittenItemCodes = new Set(['Entities', 'EntityFields', 'EntityOrganicKeys', 'Applications']); }
6338
+ /**
6339
+ * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
6340
+ * the assembly writes to are shallow copies (a new array of new row objects), the rest are the
6341
+ * dataset's own arrays. The dataset's rows are the ones the dataset cache holds and serves to
6342
+ * every later reader — on a server, every client's metadata request — so writing child
6343
+ * collections onto them would send each entity's fields, permissions and relationships a second
6344
+ * time, nested inside the entity rows, with every response.
6345
+ */
6346
+ static metadataAssemblyInput(dataset) {
6347
+ const input = {};
6348
+ for (const item of dataset.Results ?? []) {
6349
+ const rows = Array.isArray(item.Results) ? item.Results : [];
6350
+ input[item.Code] = ProviderBase._assemblyWrittenItemCodes.has(item.Code)
6351
+ ? rows.map(row => ({ ...row }))
6352
+ : rows;
6353
+ }
6354
+ return input;
6355
+ }
5948
6356
  /** Logs a failed metadata download and keeps it for {@link LastMetadataLoadError}. */
5949
6357
  recordMetadataLoadFailure(error) {
5950
6358
  LogError(error.message);
@@ -5968,7 +6376,12 @@ export class ProviderBase {
5968
6376
  // SaveLocalMetadataToStorage avoids a multi-MB JSON.stringify + gzip + IDB
5969
6377
  // write pass on the main thread during startup.
5970
6378
  if (previousUserJson !== JSON.stringify(user)) {
5971
- void this.SaveLocalMetadataToStorage();
6379
+ if (Object.prototype.hasOwnProperty.call(this, 'SaveLocalMetadataToStorage')) {
6380
+ void this.SaveLocalMetadataToStorage();
6381
+ }
6382
+ else {
6383
+ this.ScheduleSaveLocalMetadataToStorage();
6384
+ }
5972
6385
  }
5973
6386
  return user;
5974
6387
  }
@@ -6169,41 +6582,87 @@ export class ProviderBase {
6169
6582
  get AuthorizationRoles() {
6170
6583
  return this._localMetadata.AllAuthorizationRoles;
6171
6584
  }
6172
- /** @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6585
+ /** Whether {@link deprecatedQueryMetadata} has logged its warning in this process. */
6586
+ static { this._queryMetadataWarningLogged = false; }
6587
+ /**
6588
+ * What a deprecated query-metadata getter returns: the loaded array when the provider loads query
6589
+ * metadata, otherwise an empty array and a warning, logged once per process, naming the
6590
+ * replacement.
6591
+ */
6592
+ deprecatedQueryMetadata(items, getterName) {
6593
+ if (this.LoadsQueryMetadata) {
6594
+ return items;
6595
+ }
6596
+ if (!ProviderBase._queryMetadataWarningLogged) {
6597
+ ProviderBase._queryMetadataWarningLogged = true;
6598
+ LogWarning(`Metadata.${getterName} and the other query-metadata getters are empty: query metadata is not loaded into the ` +
6599
+ `metadata object. Use QueryEngine from @memberjunction/core-entities, or set LoadQueryMetadata ` +
6600
+ `(databaseSettings.loadQueryMetadata on MJAPI) until the code is migrated.`, 'Metadata');
6601
+ }
6602
+ return [];
6603
+ }
6604
+ /**
6605
+ * @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Empty unless the
6606
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6607
+ */
6173
6608
  get Queries() {
6174
- return this._localMetadata.AllQueries;
6609
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueries, 'Queries');
6175
6610
  }
6176
- /** @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6611
+ /**
6612
+ * @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Empty unless the
6613
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6614
+ */
6177
6615
  get QueryCategories() {
6178
- return this._localMetadata.AllQueryCategories;
6616
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryCategories, 'QueryCategories');
6179
6617
  }
6180
- /** @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6618
+ /**
6619
+ * @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Empty unless the
6620
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6621
+ */
6181
6622
  get QueryFields() {
6182
- return this._localMetadata.AllQueryFields;
6623
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryFields, 'QueryFields');
6183
6624
  }
6184
- /** @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6625
+ /**
6626
+ * @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Empty unless the
6627
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6628
+ */
6185
6629
  get QueryPermissions() {
6186
- return this._localMetadata.AllQueryPermissions;
6630
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryPermissions, 'QueryPermissions');
6187
6631
  }
6188
- /** @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6632
+ /**
6633
+ * @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Empty unless the
6634
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6635
+ */
6189
6636
  get QueryEntities() {
6190
- return this._localMetadata.AllQueryEntities;
6637
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryEntities, 'QueryEntities');
6191
6638
  }
6192
- /** @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6639
+ /**
6640
+ * @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Empty unless the
6641
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6642
+ */
6193
6643
  get QueryParameters() {
6194
- return this._localMetadata.AllQueryParameters;
6644
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryParameters, 'QueryParameters');
6195
6645
  }
6196
- /** @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6646
+ /**
6647
+ * @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Empty unless the
6648
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6649
+ */
6197
6650
  get QueryDependencies() {
6198
- return this._localMetadata.AllQueryDependencies;
6651
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryDependencies, 'QueryDependencies');
6199
6652
  }
6200
- /** @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6653
+ /**
6654
+ * @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Empty unless the
6655
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6656
+ */
6201
6657
  get SQLDialects() {
6202
- return this._localMetadata.AllSQLDialects;
6658
+ return this.deprecatedQueryMetadata(this._localMetadata.AllSQLDialects, 'SQLDialects');
6203
6659
  }
6204
- /** @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6660
+ /**
6661
+ * @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Empty unless the
6662
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6663
+ */
6205
6664
  get QuerySQLs() {
6206
- return this._localMetadata.AllQuerySQLs;
6665
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQuerySQLs, 'QuerySQLs');
6207
6666
  }
6208
6667
  /**
6209
6668
  * Gets all library definitions in the system.
@@ -6306,7 +6765,7 @@ export class ProviderBase {
6306
6765
  * {@link preValidateAndRefresh}) already caught it; {@link Config} did not.
6307
6766
  */
6308
6767
  async CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval) {
6309
- if (!this.AllowRefresh)
6768
+ if (!this.AllowRefreshCheck)
6310
6769
  return false;
6311
6770
  if (!bypassMinCheckInterval && this._refreshCheckInFlight) {
6312
6771
  LogStatusEx({ message: `[RefreshCheck] Skipped — a check is already in flight; its caller acts on the answer`, verboseOnly: true });
@@ -6918,7 +7377,7 @@ export class ProviderBase {
6918
7377
  let d;
6919
7378
  try {
6920
7379
  // No schema filters for metadata — see comment in GetAllMetadata
6921
- d = await this.GetDatasetStatusByName(ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse);
7380
+ d = await this.GetDatasetStatusByName(ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters, this.CurrentUser, providerToUse);
6922
7381
  }
6923
7382
  catch (e) {
6924
7383
  if (!IsTransportError(e)) {
@@ -7084,13 +7543,53 @@ export class ProviderBase {
7084
7543
  const membershipKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetMembershipKey;
7085
7544
  const itemsKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetItemsKey;
7086
7545
  const readStart = Date.now();
7087
- const all = await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey]);
7546
+ let raw = null;
7547
+ let tsRaw = null;
7548
+ let format = null;
7549
+ let membershipRaw = null;
7550
+ let itemsRaw = null;
7551
+ if (typeof ls.GetObject === 'function') {
7552
+ const otherKeys = [tsKey, fmtKey, membershipKey, itemsKey];
7553
+ const [metadataObj, otherItems] = await Promise.all([
7554
+ ls.GetObject(dataKey),
7555
+ typeof ls.GetItems === 'function' ? ls.GetItems(otherKeys) : null
7556
+ ]);
7557
+ raw = metadataObj !== null && metadataObj !== undefined
7558
+ ? metadataObj
7559
+ : await ls.GetItem(dataKey);
7560
+ if (otherItems) {
7561
+ tsRaw = otherItems.get(tsKey) ?? null;
7562
+ format = otherItems.get(fmtKey) ?? null;
7563
+ membershipRaw = otherItems.get(membershipKey) ?? null;
7564
+ itemsRaw = otherItems.get(itemsKey) ?? null;
7565
+ }
7566
+ else {
7567
+ tsRaw = await ls.GetItem(tsKey);
7568
+ format = await ls.GetItem(fmtKey);
7569
+ membershipRaw = await ls.GetItem(membershipKey);
7570
+ itemsRaw = await ls.GetItem(itemsKey);
7571
+ }
7572
+ }
7573
+ else {
7574
+ const all = typeof ls.GetItems === 'function'
7575
+ ? await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey])
7576
+ : null;
7577
+ if (all) {
7578
+ tsRaw = all.get(tsKey) ?? null;
7579
+ format = all.get(fmtKey) ?? null;
7580
+ raw = all.get(dataKey) ?? null;
7581
+ membershipRaw = all.get(membershipKey) ?? null;
7582
+ itemsRaw = all.get(itemsKey) ?? null;
7583
+ }
7584
+ else {
7585
+ tsRaw = await ls.GetItem(tsKey);
7586
+ format = await ls.GetItem(fmtKey);
7587
+ raw = await ls.GetItem(dataKey);
7588
+ membershipRaw = await ls.GetItem(membershipKey);
7589
+ itemsRaw = await ls.GetItem(itemsKey);
7590
+ }
7591
+ }
7088
7592
  const readMs = Date.now() - readStart;
7089
- const tsRaw = all.get(tsKey) ?? null;
7090
- const format = all.get(fmtKey) ?? null;
7091
- const raw = all.get(dataKey) ?? null;
7092
- const membershipRaw = all.get(membershipKey) ?? null;
7093
- const itemsRaw = all.get(itemsKey) ?? null;
7094
7593
  // The timestamps are a freshness claim FOR THE PAYLOAD, so they are only adopted when the
7095
7594
  // payload is there to adopt with them. Timestamps without a payload happen whenever the
7096
7595
  // two keys do not disappear together: the timestamps key is written last (and removed
@@ -7116,27 +7615,19 @@ export class ProviderBase {
7116
7615
  // boot that never calls GetAllMetadata (the stale-while-revalidate fast start). The
7117
7616
  // set is only stored after a successful dataset load, so restoring it is exactly as
7118
7617
  // trustworthy as restoring the metadata itself.
7119
- if (membershipRaw) {
7120
- try {
7121
- const names = JSON.parse(membershipRaw);
7122
- if (Array.isArray(names) && names.length > 0) {
7123
- this._metadataDatasetEntityNames = new Set(names);
7124
- this.ensureInflightViewInvalidation();
7125
- }
7126
- }
7127
- catch (membershipErr) {
7128
- LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
7129
- }
7130
- }
7131
7618
  // Restore the dataset item list the same way, so a warm boot can attribute a change to
7132
7619
  // its item and reload only what changed (see MetadataRefreshScope). Without it, every
7133
- // change seen by a process that started from the snapshot was a full reload.
7620
+ // change seen by a process that started from the snapshot was a full reload. Restored
7621
+ // first: the membership below is narrowed by it.
7134
7622
  if (itemsRaw) {
7135
7623
  this.restoreMetadataDatasetItems(itemsRaw);
7136
7624
  }
7625
+ if (membershipRaw) {
7626
+ this.restoreMetadataDatasetMembership(membershipRaw);
7627
+ }
7137
7628
  if (!raw)
7138
7629
  return;
7139
- // Decompress if stored in compressed format, otherwise parse directly
7630
+ // Decompress if stored in compressed format, otherwise parse directly or adopt object directly
7140
7631
  const parseStart = Date.now();
7141
7632
  let temp;
7142
7633
  if (format === 'gzip' && typeof raw === 'string') {
@@ -7148,9 +7639,13 @@ export class ProviderBase {
7148
7639
  const jsonString = await new Response(decompressedStream).text();
7149
7640
  temp = JSON.parse(jsonString);
7150
7641
  }
7151
- else {
7152
- // Legacy uncompressed path
7153
- temp = typeof raw === 'string' ? JSON.parse(raw) : raw;
7642
+ else if (typeof raw === 'string') {
7643
+ // Legacy uncompressed string path
7644
+ temp = JSON.parse(raw);
7645
+ }
7646
+ else if (typeof raw === 'object' && raw !== null) {
7647
+ // Structured clone object path: directly adopt the cloned object
7648
+ temp = raw;
7154
7649
  }
7155
7650
  const parseMs = Date.now() - parseStart;
7156
7651
  if (!temp)
@@ -7160,6 +7655,7 @@ export class ProviderBase {
7160
7655
  const metadata = MetadataFromSimpleObject(temp, this);
7161
7656
  const deserializeMs = Date.now() - deserializeStart;
7162
7657
  if (metadata) {
7658
+ this.dropUnloadedQueryMetadata(metadata);
7163
7659
  this.UpdateLocalMetadata(metadata);
7164
7660
  const totalMs = Date.now() - overallStart;
7165
7661
  LogStatusEx({
@@ -7189,6 +7685,30 @@ export class ProviderBase {
7189
7685
  ProviderBase.localStorageDatasetMembershipKey,
7190
7686
  ProviderBase.localStorageDatasetItemsKey,
7191
7687
  ]; }
7688
+ /**
7689
+ * Adopts a stored metadata-member entity set. The entities that back only items this provider
7690
+ * does not read are removed, so a snapshot saved by a process configured to read them cannot
7691
+ * make writes to them schedule refreshes here.
7692
+ */
7693
+ restoreMetadataDatasetMembership(membershipRaw) {
7694
+ try {
7695
+ const names = JSON.parse(membershipRaw);
7696
+ if (!Array.isArray(names) || names.length === 0) {
7697
+ return;
7698
+ }
7699
+ const restored = new Set(names.filter((n) => typeof n === 'string'));
7700
+ for (const skipped of this.skippedMetadataEntityNames(this._metadataDatasetItems ?? [])) {
7701
+ restored.delete(skipped);
7702
+ }
7703
+ if (restored.size > 0) {
7704
+ this._metadataDatasetEntityNames = restored;
7705
+ this.ensureInflightViewInvalidation();
7706
+ }
7707
+ }
7708
+ catch (membershipErr) {
7709
+ LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
7710
+ }
7711
+ }
7192
7712
  /**
7193
7713
  * Adopts a stored dataset item list. Only a well-formed list replaces the one held: a damaged or
7194
7714
  * empty value must not erase the list a load already recorded.
@@ -7305,6 +7825,115 @@ export class ProviderBase {
7305
7825
  verboseOnly: false
7306
7826
  });
7307
7827
  }
7828
+ /** Default debounce duration in milliseconds for coalesced metadata snapshot writes to local storage. */
7829
+ static { this.MetadataSnapshotSaveDebounceMs = 250; }
7830
+ /**
7831
+ * Schedules a trailing-edge coalesced background call to `SaveLocalMetadataToStorage()`,
7832
+ * deduplicating rapid back-to-back calls within the window and serializing execution if an
7833
+ * in-flight save is already running.
7834
+ *
7835
+ * @param delayMs - Debounce window duration in milliseconds (defaults to `ProviderBase.MetadataSnapshotSaveDebounceMs`)
7836
+ */
7837
+ ScheduleSaveLocalMetadataToStorage(delayMs = ProviderBase.MetadataSnapshotSaveDebounceMs) {
7838
+ if (!this.LocalStorageProvider)
7839
+ return;
7840
+ if (!this.MetadataSnapshotPersistenceEnabled) {
7841
+ this.logMetadataSnapshotDisabledOnce();
7842
+ return;
7843
+ }
7844
+ if (this._inFlightMetadataSave) {
7845
+ this._hasPendingMetadataSaveWhileInFlight = true;
7846
+ return;
7847
+ }
7848
+ if (this._metadataSaveTimer) {
7849
+ clearTimeout(this._metadataSaveTimer);
7850
+ }
7851
+ this._metadataSaveTimer = setTimeout(() => {
7852
+ this._metadataSaveTimer = null;
7853
+ void this.triggerSerializedMetadataSave();
7854
+ }, delayMs);
7855
+ if (typeof this._metadataSaveTimer?.unref === 'function') {
7856
+ this._metadataSaveTimer.unref();
7857
+ }
7858
+ }
7859
+ /**
7860
+ * Cancels any pending debounce timer and awaits `SaveLocalMetadataToStorage()` immediately
7861
+ * (or awaits any in-flight save plus trailing save), so tests and shutdown hooks can
7862
+ * deterministically flush pending writes.
7863
+ */
7864
+ async FlushPendingMetadataStorageSave() {
7865
+ if (this._metadataSaveTimer) {
7866
+ clearTimeout(this._metadataSaveTimer);
7867
+ this._metadataSaveTimer = null;
7868
+ this._hasPendingMetadataSaveWhileInFlight = true;
7869
+ }
7870
+ if (this._inFlightMetadataSave) {
7871
+ await this._inFlightMetadataSave;
7872
+ return;
7873
+ }
7874
+ if (this._hasPendingMetadataSaveWhileInFlight) {
7875
+ await this.triggerSerializedMetadataSave();
7876
+ }
7877
+ }
7878
+ /**
7879
+ * Clears any pending metadata snapshot save timer without saving.
7880
+ */
7881
+ CancelPendingMetadataStorageSave() {
7882
+ if (this._metadataSaveTimer) {
7883
+ clearTimeout(this._metadataSaveTimer);
7884
+ this._metadataSaveTimer = null;
7885
+ }
7886
+ this._hasPendingMetadataSaveWhileInFlight = false;
7887
+ }
7888
+ triggerSerializedMetadataSave() {
7889
+ if (!this._inFlightMetadataSave) {
7890
+ this._inFlightMetadataSave = this.executeSerializedMetadataSave().finally(() => {
7891
+ this._inFlightMetadataSave = null;
7892
+ });
7893
+ }
7894
+ return this._inFlightMetadataSave;
7895
+ }
7896
+ async executeSerializedMetadataSave() {
7897
+ do {
7898
+ this._hasPendingMetadataSaveWhileInFlight = false;
7899
+ try {
7900
+ await this.SaveLocalMetadataToStorage();
7901
+ }
7902
+ catch {
7903
+ // SaveLocalMetadataToStorage catches its own errors; guard here as well
7904
+ }
7905
+ } while (this._hasPendingMetadataSaveWhileInFlight);
7906
+ }
7907
+ /**
7908
+ * Converts BaseInfo instances and nested objects into plain structured-cloneable
7909
+ * objects without JSON.stringify/JSON.parse, stripping functions and WeakRefs.
7910
+ */
7911
+ static toCloneableValue(val) {
7912
+ if (val == null || typeof val !== 'object') {
7913
+ return val;
7914
+ }
7915
+ if (val instanceof Date || val instanceof RegExp || val instanceof ArrayBuffer || ArrayBuffer.isView(val)) {
7916
+ return val;
7917
+ }
7918
+ if (Array.isArray(val)) {
7919
+ const out = new Array(val.length);
7920
+ for (let i = 0; i < val.length; i++) {
7921
+ out[i] = ProviderBase.toCloneableValue(val[i]);
7922
+ }
7923
+ return out;
7924
+ }
7925
+ const maybeToJson = val;
7926
+ if (typeof maybeToJson.toJSON === 'function') {
7927
+ return ProviderBase.toCloneableValue(maybeToJson.toJSON());
7928
+ }
7929
+ const out = {};
7930
+ for (const [k, v] of Object.entries(val)) {
7931
+ if (typeof v !== 'function' && !(typeof WeakRef !== 'undefined' && v instanceof WeakRef)) {
7932
+ out[k] = ProviderBase.toCloneableValue(v);
7933
+ }
7934
+ }
7935
+ return out;
7936
+ }
7308
7937
  /**
7309
7938
  * Saves current metadata to local storage for caching.
7310
7939
  * Serializes both timestamps and full metadata collections.
@@ -7321,14 +7950,22 @@ export class ProviderBase {
7321
7950
  return;
7322
7951
  }
7323
7952
  const start = Date.now();
7324
- // Serialize the AllMetadata object FIRST. If this throws (or the payload write below
7325
- // fails), nothing else has been written yet, so the previously stored timestamps still
7326
- // describe the previously stored payload and LocalMetadataObsolete() will report
7327
- // obsolete on the next boot — which is what makes the save retry. Writing timestamps
7328
- // before the payload left the cache claiming freshness with no payload behind it, and
7329
- // that state was never retried.
7330
- const jsonString = JSON.stringify(this._localMetadata);
7331
- const snapshot = await this.writeMetadataSnapshot(ls, jsonString);
7953
+ const dataKey = this.LocalStoragePrefix + ProviderBase.localStorageAllMetadataKey;
7954
+ const formatKey = this.LocalStoragePrefix + ProviderBase.localStorageFormatKey;
7955
+ let snapshot;
7956
+ if (typeof ls.SetObject === 'function') {
7957
+ // Structured-clone path: convert BaseInfo instances to plain cloneable objects (stripping
7958
+ // WeakRef/provider back-references without JSON.stringify/gzip/JSON.parse or lazy field hydration)
7959
+ const cloneableMetadata = ProviderBase.toCloneableValue(this._localMetadata);
7960
+ await ls.SetObject(dataKey, cloneableMetadata);
7961
+ await ls.SetItem(formatKey, 'structured-clone');
7962
+ snapshot = { compressed: false, storedLength: 0 };
7963
+ }
7964
+ else {
7965
+ // Serialized string path (JSON.stringify + gzip/base64 when CompressionStream is available)
7966
+ const jsonString = JSON.stringify(this._localMetadata);
7967
+ snapshot = await this.writeMetadataSnapshot(ls, jsonString);
7968
+ }
7332
7969
  // Persist the metadata-member entity set beside the snapshot it belongs to, so the
7333
7970
  // event-driven refresh survives a warm boot (see LoadLocalMetadataFromStorage).
7334
7971
  if (this._metadataDatasetEntityNames?.size) {
@@ -7343,7 +7980,7 @@ export class ProviderBase {
7343
7980
  const timestampsRaw = JSON.stringify(this._latestLocalMetadataTimestamps);
7344
7981
  await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageTimestampsKey, timestampsRaw);
7345
7982
  this._storedTimestampsRaw = timestampsRaw;
7346
- this.logMetadataSaveComplete(Date.now() - start, jsonString.length, snapshot);
7983
+ this.logMetadataSaveComplete(Date.now() - start, snapshot.storedLength, snapshot);
7347
7984
  }
7348
7985
  catch (e) {
7349
7986
  LogError(`[Metadata Cache] SaveLocalMetadataToStorage failed: ${e instanceof Error ? e.message : String(e)}`);
@@ -7390,6 +8027,12 @@ export class ProviderBase {
7390
8027
  verboseOnly: true
7391
8028
  });
7392
8029
  }
8030
+ else if (snapshot.storedLength === 0) {
8031
+ LogStatusEx({
8032
+ message: `[Metadata Cache] Save complete (structured-clone): ${elapsedMs}ms`,
8033
+ verboseOnly: true
8034
+ });
8035
+ }
7393
8036
  else {
7394
8037
  LogStatusEx({
7395
8038
  message: `[Metadata Cache] Save complete (uncompressed): ${elapsedMs}ms, size=${mb(rawLength)}MB`,