@memberjunction/realtime-widget 6.3.0-edge.2 → 6.3.0-edge.3

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.
@@ -50,7 +50,7 @@ import {
50
50
  shareReplay,
51
51
  switchMap,
52
52
  uuidv4
53
- } from "./chunk-KHEWGJIZ.js";
53
+ } from "./chunk-CUZ32HGY.js";
54
54
 
55
55
  // ../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
56
56
  var require_ms = __commonJS({
@@ -4416,9 +4416,9 @@ GO`;
4416
4416
  `EXEC sp_addextendedproperty`,
4417
4417
  ` @name = N'MS_Description',`,
4418
4418
  ` @value = N'${escaped}',`,
4419
- ` @level0type = N'SCHEMA', @level0name = '${schema}',`,
4420
- ` @level1type = N'TABLE', @level1name = '${table}',`,
4421
- ` @level2type = N'COLUMN', @level2name = '${column}';`
4419
+ ` @level0type = N'SCHEMA', @level0name = ${this.escapeUnicodeLiteral(schema)},`,
4420
+ ` @level1type = N'TABLE', @level1name = ${this.escapeUnicodeLiteral(table)},`,
4421
+ ` @level2type = N'COLUMN', @level2name = ${this.escapeUnicodeLiteral(column)};`
4422
4422
  ].join("\n");
4423
4423
  }
4424
4424
  FallbackType() {
@@ -4457,8 +4457,8 @@ GO`;
4457
4457
  `EXEC sp_addextendedproperty`,
4458
4458
  ` @name = N'MS_Description',`,
4459
4459
  ` @value = N'${escapedComment}',`,
4460
- ` @level0type = N'SCHEMA', @level0name = N'${schema}',`,
4461
- ` @level1type = N'${level1Type}', @level1name = N'${name}'`
4460
+ ` @level0type = N'SCHEMA', @level0name = ${this.escapeUnicodeLiteral(schema)},`,
4461
+ ` @level1type = ${this.escapeUnicodeLiteral(level1Type)}, @level1name = ${this.escapeUnicodeLiteral(name)}`
4462
4462
  ].join("\n");
4463
4463
  }
4464
4464
  CreateTableIfAbsent(fullTable, columnsBody) {
@@ -4488,13 +4488,13 @@ ${this.IndexDDL(options)};`;
4488
4488
  CommentOnObjectIfAbsent(objectType, schema, name, comment) {
4489
4489
  const level1Type = this.objectTypeToLevel1Type(objectType);
4490
4490
  return [
4491
- `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'${schema}', N'${level1Type}', N'${name}', NULL, NULL))`,
4491
+ `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', ${this.escapeUnicodeLiteral(schema)}, ${this.escapeUnicodeLiteral(level1Type)}, ${this.escapeUnicodeLiteral(name)}, NULL, NULL))`,
4492
4492
  `${this.CommentOnObject(objectType, schema, name, comment)};`
4493
4493
  ].join("\n");
4494
4494
  }
4495
4495
  CommentOnColumnIfAbsent(schema, table, column, comment) {
4496
4496
  return [
4497
- `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'${schema}', N'TABLE', N'${table}', N'COLUMN', N'${column}'))`,
4497
+ `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', ${this.escapeUnicodeLiteral(schema)}, N'TABLE', ${this.escapeUnicodeLiteral(table)}, N'COLUMN', ${this.escapeUnicodeLiteral(column)}))`,
4498
4498
  this.CommentOnColumn(schema, table, column, comment)
4499
4499
  ].join("\n");
4500
4500
  }
@@ -4605,6 +4605,9 @@ COMMIT TRANSACTION;`;
4605
4605
  }
4606
4606
  return "NVARCHAR(255)";
4607
4607
  }
4608
+ escapeUnicodeLiteral(value) {
4609
+ return `N'${EscapeSQLString(value)}'`;
4610
+ }
4608
4611
  objectTypeToLevel1Type(objectType) {
4609
4612
  switch (objectType.toUpperCase()) {
4610
4613
  case "TABLE":
@@ -6607,6 +6610,59 @@ function IsNetworkSQLType(typeName) {
6607
6610
  return NETWORK_TYPE_SET.has(normalize(typeName));
6608
6611
  }
6609
6612
 
6613
+ // ../../SQLDialect/dist/indexCatalog.js
6614
+ function buildPostgreSQLIndexCatalogSQL(whereClauses) {
6615
+ return `
6616
+ SELECT
6617
+ n.nspname AS "SchemaName",
6618
+ t.relname AS "TableName",
6619
+ i.relname AS "IndexName",
6620
+ am.amname AS "NativeType",
6621
+ ix.indisunique AS "IsUnique",
6622
+ ix.indisprimary AS "IsPrimaryKey",
6623
+ ix.indisclustered AS "IsClustered",
6624
+ pg_get_expr(ix.indpred, ix.indrelid) AS "FilterDefinition",
6625
+ (ix.indexprs IS NOT NULL) AS "HasExpressions",
6626
+ CASE WHEN k.attnum = 0 THEN NULL ELSE a.attname::text END AS "ColumnName",
6627
+ CASE WHEN k.attnum = 0 THEN pg_get_indexdef(ix.indexrelid, k.ord::int, true) ELSE NULL END AS "Expression",
6628
+ k.ord::int AS "Sequence",
6629
+ (k.ord > ix.indnkeyatts) AS "IsIncluded",
6630
+ CASE
6631
+ WHEN k.ord <= ix.indnkeyatts THEN ((ix.indoption[k.ord - 1] & 1) = 1)
6632
+ ELSE false
6633
+ END AS "IsDescending"
6634
+ FROM pg_index ix
6635
+ INNER JOIN pg_class i ON i.oid = ix.indexrelid
6636
+ INNER JOIN pg_class t ON t.oid = ix.indrelid
6637
+ INNER JOIN pg_namespace n ON n.oid = t.relnamespace
6638
+ INNER JOIN pg_am am ON am.oid = i.relam
6639
+ LEFT JOIN LATERAL unnest(ix.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) ON true
6640
+ LEFT JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum AND k.attnum > 0
6641
+ WHERE ${whereClauses.join("\n AND ")}
6642
+ ORDER BY n.nspname, t.relname, i.relname, k.ord
6643
+ `.trim();
6644
+ }
6645
+ var POSTGRESQL_INDEX_CATALOG_QUERY = buildPostgreSQLIndexCatalogSQL([
6646
+ "n.nspname = $1",
6647
+ "t.relkind IN ('r', 'p')",
6648
+ "ix.indisvalid",
6649
+ "ix.indisready"
6650
+ ]);
6651
+ var MYSQL_INDEX_CATALOG_QUERY = `
6652
+ SELECT
6653
+ TABLE_SCHEMA AS SchemaName,
6654
+ TABLE_NAME AS TableName,
6655
+ INDEX_NAME AS IndexName,
6656
+ NON_UNIQUE AS NonUnique,
6657
+ INDEX_TYPE AS NativeType,
6658
+ COLUMN_NAME AS ColumnName,
6659
+ SEQ_IN_INDEX AS Sequence,
6660
+ COLLATION AS Collation
6661
+ FROM information_schema.STATISTICS
6662
+ WHERE TABLE_SCHEMA = ?
6663
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
6664
+ `.trim();
6665
+
6610
6666
  // ../../MJCore/dist/generic/util.js
6611
6667
  function CanonicalPrimaryKeyValue(value, isUuid) {
6612
6668
  const text = value.trim();
@@ -7135,6 +7191,18 @@ var UserInfo = class extends BaseInfo {
7135
7191
  set APIKeyActingContext(value) {
7136
7192
  this._aPIKeyActingContext = value;
7137
7193
  }
7194
+ /**
7195
+ * Per-request impersonation attribution context stamped server-side onto cloned `UserInfo`
7196
+ * instances for active impersonation sessions. Consumed by `DatabaseProviderBase.BuildRecordChangePayload`
7197
+ * so `MJ: Record Changes` rows written during `ActAs` record both the target user and the
7198
+ * impersonating actor. Not a DB/GraphQL field and never exposed to clients.
7199
+ */
7200
+ get ImpersonationContext() {
7201
+ return this._impersonationContext;
7202
+ }
7203
+ set ImpersonationContext(value) {
7204
+ this._impersonationContext = value;
7205
+ }
7138
7206
  /**
7139
7207
  * Row-filter bindings for the API key this session authenticated with,
7140
7208
  * resolved per request from the key's scope rules and stamped on the CLONED
@@ -7244,6 +7312,7 @@ var UserInfo = class extends BaseInfo {
7244
7312
  this._tenantContext = void 0;
7245
7313
  this._magicLinkScope = void 0;
7246
7314
  this._aPIKeyActingContext = void 0;
7315
+ this._impersonationContext = void 0;
7247
7316
  this._aPIKeyRowFilters = void 0;
7248
7317
  this._returningVisitorContext = void 0;
7249
7318
  this._widgetGuestContext = void 0;
@@ -8330,6 +8399,7 @@ var CONTEXT_TOKENS = [
8330
8399
  "Context.StartOfQuarter",
8331
8400
  "Context.StartOfYear"
8332
8401
  ];
8402
+ var CONTEXT_TOKEN_CONTRACT_VERSION = 1;
8333
8403
  var PROPERTY_VALUE_TYPES = ["string", "number", "boolean", "date", "uuid"];
8334
8404
  var PROPERTY_OFFSET_UNITS = ["day", "week", "month", "quarter", "year"];
8335
8405
  var TIME_ZONE_HEADER = "x-mj-timezone";
@@ -10612,6 +10682,93 @@ var EntityUniqueKeyInfo = class extends BaseInfo {
10612
10682
  }
10613
10683
  }
10614
10684
  };
10685
+ var EntityIndexFieldInfo = class extends BaseInfo {
10686
+ /** True when this key position is an expression rather than a plain base-table column. */
10687
+ get IsExpression() {
10688
+ return this.EntityFieldID == null;
10689
+ }
10690
+ /** True when this entry is a key part (not an INCLUDE column). */
10691
+ get IsKey() {
10692
+ return this.Role === "Key";
10693
+ }
10694
+ /** True when this entry is a non-key INCLUDE column. */
10695
+ get IsInclude() {
10696
+ return this.Role === "Include";
10697
+ }
10698
+ constructor(initData = null) {
10699
+ super();
10700
+ this.ID = null;
10701
+ this.EntityIndexID = null;
10702
+ this.EntityFieldID = null;
10703
+ this.Expression = null;
10704
+ this.Sequence = 0;
10705
+ this.Role = "Key";
10706
+ this.SortDirection = "ASC";
10707
+ this.__mj_CreatedAt = null;
10708
+ this.__mj_UpdatedAt = null;
10709
+ this.EntityIndex = null;
10710
+ this.EntityField = null;
10711
+ if (initData) {
10712
+ this.copyInitData(initData);
10713
+ }
10714
+ }
10715
+ };
10716
+ var EntityIndexInfo = class _EntityIndexInfo extends BaseInfo {
10717
+ static {
10718
+ this.CHILD_INIT_KEYS = /* @__PURE__ */ new Set([
10719
+ "EntityIndexFields",
10720
+ "_Fields",
10721
+ "Fields"
10722
+ ]);
10723
+ }
10724
+ /** All key and INCLUDE entries of this index, sorted by `Sequence`. */
10725
+ get Fields() {
10726
+ return this._fields;
10727
+ }
10728
+ /** Ordered key entries of this index (including expression key parts), sorted by `Sequence`. */
10729
+ get KeyFields() {
10730
+ return this._fields.filter((f) => f.Role === "Key");
10731
+ }
10732
+ /** Ordered non-key INCLUDE entries of this index, sorted by `Sequence`. */
10733
+ get IncludeFields() {
10734
+ return this._fields.filter((f) => f.Role === "Include");
10735
+ }
10736
+ /** True when the index has a non-empty filter/partial predicate. */
10737
+ get IsFiltered() {
10738
+ return this.FilterDefinition != null && this.FilterDefinition.trim().length > 0;
10739
+ }
10740
+ /** True when the index exists in the database (`Status === 'Active'`). */
10741
+ get IsActive() {
10742
+ return this.Status === "Active";
10743
+ }
10744
+ constructor(initData = null) {
10745
+ super();
10746
+ this.ID = null;
10747
+ this.EntityID = null;
10748
+ this.Name = null;
10749
+ this.IndexType = "BTree";
10750
+ this.NativeType = "";
10751
+ this.IsUnique = false;
10752
+ this.IsPrimaryKey = false;
10753
+ this.IsClustered = false;
10754
+ this.FilterDefinition = null;
10755
+ this.HasExpressions = false;
10756
+ this.Source = "Database";
10757
+ this.Status = "Active";
10758
+ this.Description = null;
10759
+ this.__mj_CreatedAt = null;
10760
+ this.__mj_UpdatedAt = null;
10761
+ this.Entity = null;
10762
+ this._fields = [];
10763
+ if (initData) {
10764
+ this.copyInitData(initData, _EntityIndexInfo.CHILD_INIT_KEYS);
10765
+ const rawFields = initData.EntityIndexFields || initData._Fields || initData.Fields;
10766
+ if (Array.isArray(rawFields)) {
10767
+ this._fields = rawFields.map((item) => item instanceof EntityIndexFieldInfo ? item : new EntityIndexFieldInfo(item)).sort((a, b) => a.Sequence - b.Sequence || ordinalCompare(a.ID, b.ID));
10768
+ }
10769
+ }
10770
+ }
10771
+ };
10615
10772
  var EntityAlternateBaseViewInfo = class extends BaseInfo {
10616
10773
  /**
10617
10774
  * The parent alternate base view on the same entity when {@link ParentID} is set,
@@ -11782,6 +11939,54 @@ var EntityFieldInfo = class _EntityFieldInfo extends BaseInfo {
11782
11939
  this._fixedWidthColumnCache = IsFixedWidthStringSQLType(this.Type);
11783
11940
  return this._fixedWidthColumnCache;
11784
11941
  }
11942
+ /**
11943
+ * Records the owning {@link EntityInfo} so field-level index helpers
11944
+ * ({@link IsIndexed}, {@link IsLeadingIndexColumn}) can inspect `EntityInfo.Indexes`
11945
+ * without consulting a global provider.
11946
+ */
11947
+ SetOwningEntity(entity) {
11948
+ this._owningEntity = entity;
11949
+ }
11950
+ matchesIndexField(indexField) {
11951
+ if (indexField.IsExpression) {
11952
+ return false;
11953
+ }
11954
+ if (this.ID && indexField.EntityFieldID) {
11955
+ return UUIDsEqual(this.ID, indexField.EntityFieldID);
11956
+ }
11957
+ if (this.Name && indexField.EntityField) {
11958
+ return this.Name.trim().toLowerCase() === indexField.EntityField.trim().toLowerCase();
11959
+ }
11960
+ return false;
11961
+ }
11962
+ /**
11963
+ * True when this field appears as a `Key` column in at least one `Active` database index
11964
+ * on the owning entity. `Include`-only columns, `Proposed`/`Rejected` indexes, and
11965
+ * expression key parts do not count.
11966
+ */
11967
+ get IsIndexed() {
11968
+ if (!this._owningEntity) {
11969
+ return false;
11970
+ }
11971
+ return this._owningEntity.Indexes.some((idx) => idx.IsActive && idx.KeyFields.some((f) => this.matchesIndexField(f)));
11972
+ }
11973
+ /**
11974
+ * True when this field is the leading (first `Key`) column of at least one `Active`
11975
+ * database index on the owning entity. An index whose first key part is an expression
11976
+ * does not make a subsequent column the leading column.
11977
+ */
11978
+ get IsLeadingIndexColumn() {
11979
+ if (!this._owningEntity) {
11980
+ return false;
11981
+ }
11982
+ return this._owningEntity.Indexes.some((idx) => {
11983
+ if (!idx.IsActive) {
11984
+ return false;
11985
+ }
11986
+ const leading = idx.KeyFields[0];
11987
+ return leading != null && this.matchesIndexField(leading);
11988
+ });
11989
+ }
11785
11990
  /**
11786
11991
  * Returns true if the field has a default value set
11787
11992
  */
@@ -12024,6 +12229,7 @@ var EntityFieldInfo = class _EntityFieldInfo extends BaseInfo {
12024
12229
  this._isDeletedAtFieldCache = void 0;
12025
12230
  this._isUniqueIdentifierCache = void 0;
12026
12231
  this._fixedWidthColumnCache = void 0;
12232
+ this._owningEntity = null;
12027
12233
  this._parsedDefaultValueCache = void 0;
12028
12234
  if (initData) {
12029
12235
  this.copyInitData(initData, _EntityFieldInfo.CHILD_INIT_KEYS);
@@ -12715,6 +12921,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12715
12921
  if (md) {
12716
12922
  field.SetOwningProvider(md);
12717
12923
  }
12924
+ field.SetOwningEntity(this);
12718
12925
  fields.push(field);
12719
12926
  }
12720
12927
  this._fields = fields;
@@ -13384,6 +13591,28 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13384
13591
  get UniqueKeySets() {
13385
13592
  return this._uniqueKeySets;
13386
13593
  }
13594
+ /**
13595
+ * All database indexes and advisor proposals registered for this entity's base table,
13596
+ * sorted by name. Maintained by CodeGen from the database catalog.
13597
+ * @returns {EntityIndexInfo[]} Array of index definitions
13598
+ */
13599
+ get Indexes() {
13600
+ return this._indexes;
13601
+ }
13602
+ /**
13603
+ * Active database indexes currently present on this entity's base table (`Status === 'Active'`).
13604
+ * @returns {EntityIndexInfo[]} Array of active index definitions
13605
+ */
13606
+ get ActiveIndexes() {
13607
+ return this._indexes.filter((idx) => idx.IsActive);
13608
+ }
13609
+ /**
13610
+ * Replaces the entity's loaded index metadata (sorted deterministically by Name, ID). Used by
13611
+ * `ProviderBase.EnsureEntityIndexesLoaded` to hydrate indexes lazily after initial metadata boot.
13612
+ */
13613
+ SetIndexes(indexes) {
13614
+ this._indexes = [...indexes].sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
13615
+ }
13387
13616
  /**
13388
13617
  * Whether a row is identified by its values in `fieldNames`: true when the names include every
13389
13618
  * primary key field, a field that is unique on its own ({@link EntityFieldInfo.IsUnique}, which
@@ -14432,6 +14661,9 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14432
14661
  "EntityUniqueKeys",
14433
14662
  "_UniqueKeySets",
14434
14663
  "UniqueKeySets",
14664
+ "EntityIndexes",
14665
+ "_Indexes",
14666
+ "Indexes",
14435
14667
  "EntityAlternateBaseViews",
14436
14668
  "_AlternateBaseViews",
14437
14669
  "AlternateBaseViews"
@@ -14535,6 +14767,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14535
14767
  this._fieldCategories = null;
14536
14768
  this._organicKeys = [];
14537
14769
  this._uniqueKeySets = [];
14770
+ this._indexes = [];
14538
14771
  this._alternateBaseViews = [];
14539
14772
  this._lazyHasIdField = void 0;
14540
14773
  this._lazyVirtualCount = void 0;
@@ -14632,6 +14865,14 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14632
14865
  }
14633
14866
  this._uniqueKeySets.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
14634
14867
  }
14868
+ this._indexes = [];
14869
+ const idx = initData.EntityIndexes || initData._Indexes || initData.Indexes;
14870
+ if (idx && Array.isArray(idx)) {
14871
+ for (const item of idx) {
14872
+ this._indexes.push(item instanceof EntityIndexInfo ? item : new EntityIndexInfo(item));
14873
+ }
14874
+ this._indexes.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
14875
+ }
14635
14876
  this._alternateBaseViews = [];
14636
14877
  const abv = initData.EntityAlternateBaseViews || initData._AlternateBaseViews || initData.AlternateBaseViews;
14637
14878
  if (abv && Array.isArray(abv)) {
@@ -30834,14 +31075,16 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
30834
31075
  }
30835
31076
  }
30836
31077
  /**
30837
- * True when the registry must stay in this process: the storage is shared with other
30838
- * processes, so a persisted registry would be one key every server overwrites with its own
30839
- * view (and publishes to every peer on each write), and a booting server would adopt another
30840
- * server's accounting. Entries written by other processes are found through the provider's
31078
+ * True when the registry must stay in this process: either the storage is shared across a
31079
+ * multi-server fleet (`SharedAcrossProcesses`), or the provider explicitly requests a
31080
+ * process/tab-local registry (`ProcessLocalRegistry`, e.g. browser tabs sharing IndexedDB
31081
+ * through a SharedWorker without multi-server fleet semantics). Keeping the registry in
31082
+ * memory prevents peers/tabs from overwriting one shared registry key with their own
31083
+ * accounting. Entries written by other processes are found through the provider's
30841
31084
  * per-entity index instead ({@link resolveFingerprintsForEntity}).
30842
31085
  */
30843
31086
  registryIsProcessLocalOnly() {
30844
- return this._storageProvider?.SharedAcrossProcesses === true;
31087
+ return this._storageProvider?.SharedAcrossProcesses === true || this._storageProvider?.ProcessLocalRegistry === true;
30845
31088
  }
30846
31089
  /**
30847
31090
  * Loads the registry from storage.
@@ -33175,6 +33418,70 @@ function memberName(token) {
33175
33418
  return token.slice(QUERY_CONTEXT_NAME.length + 1);
33176
33419
  }
33177
33420
 
33421
+ // ../../MJCore/dist/generic/wellKnownUserSource.js
33422
+ var WellKnownUserSource = class _WellKnownUserSource {
33423
+ static {
33424
+ this._globalStoreKey = "___SINGLETON__WellKnownUserSource";
33425
+ }
33426
+ /**
33427
+ * The registered source for this process, resolved once through the class factory and
33428
+ * stored in the Global Object Store so bundler duplication cannot split the cached instance.
33429
+ *
33430
+ * Cached because {@link IsSystemUser} sits behind permission checks that run per entity and
33431
+ * per user; resolving (and allocating) on every call would be needless churn. Registrations
33432
+ * happen as module-load side effects of importing a data-provider package, which always
33433
+ * precedes any permission evaluation, so caching cannot capture a stale answer in practice.
33434
+ * Tests that register a source after first use should call {@link ResetInstance}.
33435
+ */
33436
+ static get Instance() {
33437
+ const g = GetGlobalObjectStore();
33438
+ if (g) {
33439
+ if (!g[_WellKnownUserSource._globalStoreKey]) {
33440
+ g[_WellKnownUserSource._globalStoreKey] = MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
33441
+ }
33442
+ return g[_WellKnownUserSource._globalStoreKey];
33443
+ }
33444
+ return MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
33445
+ }
33446
+ /**
33447
+ * Drops the cached {@link Instance} so the next access re-resolves through the class
33448
+ * factory. Intended for tests that register a source after the cache was populated.
33449
+ */
33450
+ static ResetInstance() {
33451
+ const g = GetGlobalObjectStore();
33452
+ if (g) {
33453
+ delete g[_WellKnownUserSource._globalStoreKey];
33454
+ }
33455
+ }
33456
+ /**
33457
+ * True when `user` is the MJ system user — the server's own service account, not a person.
33458
+ *
33459
+ * Synchronous on purpose: this is consumed by permission checks that cannot await. The base
33460
+ * returns false, which is the right answer anywhere no server-side source is registered —
33461
+ * a browser has no system account, so no user it holds can be one.
33462
+ *
33463
+ * Implementations must be null/undefined-safe so callers can pass an optional user directly.
33464
+ */
33465
+ IsSystemUser(user) {
33466
+ return false;
33467
+ }
33468
+ /**
33469
+ * The MJ system user for the given provider's connection, with `UserRoles` populated, or
33470
+ * null when this process has no such identity to offer.
33471
+ *
33472
+ * Implementations MUST NOT throw — a missing user row, an unconfigured provider, or a
33473
+ * failed lookup all resolve to null so callers can degrade rather than crash. Callers MUST
33474
+ * treat null as "no elevated identity available" and fall back to their existing behavior.
33475
+ *
33476
+ * @param provider The provider whose connection the user is being resolved for. Passed
33477
+ * explicitly (rather than read from a global) so a process holding several connections
33478
+ * resolves the account belonging to the one actually in use.
33479
+ */
33480
+ async GetSystemUser(provider) {
33481
+ return null;
33482
+ }
33483
+ };
33484
+
33178
33485
  // ../../MJCore/dist/generic/providerBase.js
33179
33486
  function MetadataFromSimpleObject(data, md) {
33180
33487
  try {
@@ -33360,6 +33667,12 @@ var ProviderBase = class _ProviderBase {
33360
33667
  this._metadataRefreshRetries = 0;
33361
33668
  this._metadataScopedReloadFailures = 0;
33362
33669
  this._metadataMemberRefreshTimer = null;
33670
+ this._entityIndexesMetadataGeneration = 0;
33671
+ this._entityIndexesLoadedGeneration = -1;
33672
+ this._entityIndexesLoadPromise = null;
33673
+ this._entityIndexesLastFailedAt = 0;
33674
+ this._entityIndexesLastFailedGeneration = -1;
33675
+ this._entityIndexesSystemUserFallbackWarned = false;
33363
33676
  this._peerMetadataNoticeFirstAt = null;
33364
33677
  this._peerMetadataNoticeRetries = 0;
33365
33678
  this._peerMetadataNoticeTimer = null;
@@ -33751,6 +34064,140 @@ var ProviderBase = class _ProviderBase {
33751
34064
  get LoadsQueryMetadata() {
33752
34065
  return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
33753
34066
  }
34067
+ static {
34068
+ this.EntityIndexesFailureCooldownMs = 3e4;
34069
+ }
34070
+ /**
34071
+ * True when `EntityInfo.Indexes` / `EntityInfo.ActiveIndexes` have been hydrated for the
34072
+ * current metadata generation via {@link EnsureEntityIndexesLoaded}.
34073
+ */
34074
+ get EntityIndexesLoaded() {
34075
+ return this._entityIndexesLoadedGeneration === this._entityIndexesMetadataGeneration;
34076
+ }
34077
+ /**
34078
+ * Resolves the principal used to hydrate shared index metadata (Finding 285):
34079
+ * - On server (`ProviderType.Database`) providers, loads as the MJ system user via
34080
+ * {@link WellKnownUserSource} so a restricted first caller can never cache a partial set
34081
+ * process-wide (falling back to `this.CurrentUser ?? contextUser` only if no system user
34082
+ * source is registered).
34083
+ * - On client (`ProviderType.Network`) providers, uses `contextUser ?? this.CurrentUser`.
34084
+ */
34085
+ async resolveEntityIndexLoadUser(contextUser) {
34086
+ if (this.ProviderType !== ProviderType.Database) {
34087
+ return contextUser ?? this.CurrentUser;
34088
+ }
34089
+ let systemUser = null;
34090
+ try {
34091
+ const source = MJGlobal.Instance.ClassFactory.CreateInstance(WellKnownUserSource);
34092
+ systemUser = await source?.GetSystemUser(this) ?? null;
34093
+ } catch (e) {
34094
+ LogError(`EnsureEntityIndexesLoaded: WellKnownUserSource.GetSystemUser threw: ${e instanceof Error ? e.message : String(e)}`);
34095
+ }
34096
+ if (systemUser) {
34097
+ return systemUser;
34098
+ }
34099
+ if (!this._entityIndexesSystemUserFallbackWarned && contextUser && !this.CurrentUser) {
34100
+ this._entityIndexesSystemUserFallbackWarned = true;
34101
+ LogWarning("EnsureEntityIndexesLoaded: could not resolve the MJ system user for server-side index metadata loading \u2014 falling back to the calling user. Index metadata is cached process-wide, so a restricted caller could leave incomplete data cached.", "Cache");
34102
+ }
34103
+ return this.CurrentUser ?? contextUser;
34104
+ }
34105
+ /**
34106
+ * Lazily loads `MJ: Entity Indices` and `MJ: Entity Index Fields` once per metadata generation
34107
+ * and attaches them to each {@link EntityInfo} via {@link EntityInfo.SetIndexes} (Findings 267, 285).
34108
+ * Single-flight and zero-cost once hydrated; keeps `MJ_Metadata` boot payloads free of ~4,600–5,800
34109
+ * index rows (~8–10% overhead). Failed attempts back off for {@link EntityIndexesFailureCooldownMs}
34110
+ * within the current metadata generation so callers do not retry-storm on every request.
34111
+ */
34112
+ async EnsureEntityIndexesLoaded(contextUser) {
34113
+ if (this.EntityIndexesLoaded) {
34114
+ return;
34115
+ }
34116
+ if (this._entityIndexesLoadPromise) {
34117
+ return this._entityIndexesLoadPromise;
34118
+ }
34119
+ const gen = this._entityIndexesMetadataGeneration;
34120
+ if (this._entityIndexesLastFailedGeneration === gen && _ProviderBase.EntityIndexesFailureCooldownMs > 0 && Date.now() - this._entityIndexesLastFailedAt < _ProviderBase.EntityIndexesFailureCooldownMs) {
34121
+ return;
34122
+ }
34123
+ const loadPromise = (async () => {
34124
+ try {
34125
+ if (!this.EntityByName("MJ: Entity Indices") || !this.EntityByName("MJ: Entity Index Fields")) {
34126
+ if (this._entityIndexesMetadataGeneration === gen) {
34127
+ this._entityIndexesLoadedGeneration = gen;
34128
+ this._entityIndexesLastFailedAt = 0;
34129
+ this._entityIndexesLastFailedGeneration = -1;
34130
+ }
34131
+ return;
34132
+ }
34133
+ const loadUser = await this.resolveEntityIndexLoadUser(contextUser);
34134
+ const results = await this.RunViews([
34135
+ { EntityName: "MJ: Entity Indices", ResultType: "simple", IgnoreMaxRows: true },
34136
+ { EntityName: "MJ: Entity Index Fields", ResultType: "simple", IgnoreMaxRows: true }
34137
+ ], loadUser);
34138
+ if (!results || results.length < 2 || !results[0].Success || !results[1].Success) {
34139
+ if (this._entityIndexesMetadataGeneration === gen) {
34140
+ this._entityIndexesLastFailedGeneration = gen;
34141
+ this._entityIndexesLastFailedAt = Date.now();
34142
+ }
34143
+ LogError(`EnsureEntityIndexesLoaded failed: indices=${results?.[0]?.ErrorMessage ?? "no result"}, fields=${results?.[1]?.ErrorMessage ?? "no result"}`);
34144
+ return;
34145
+ }
34146
+ if (this._entityIndexesMetadataGeneration !== gen) {
34147
+ return;
34148
+ }
34149
+ const fieldsByIndexId = /* @__PURE__ */ new Map();
34150
+ for (const row of results[1].Results ?? []) {
34151
+ const idxId = typeof row.EntityIndexID === "string" ? NormalizeUUID(row.EntityIndexID) : "";
34152
+ if (!idxId) {
34153
+ continue;
34154
+ }
34155
+ let list = fieldsByIndexId.get(idxId);
34156
+ if (!list) {
34157
+ list = [];
34158
+ fieldsByIndexId.set(idxId, list);
34159
+ }
34160
+ list.push(row);
34161
+ }
34162
+ const indexesByEntityId = /* @__PURE__ */ new Map();
34163
+ for (const row of results[0].Results ?? []) {
34164
+ const entityId = typeof row.EntityID === "string" ? NormalizeUUID(row.EntityID) : "";
34165
+ const idxId = typeof row.ID === "string" ? NormalizeUUID(row.ID) : "";
34166
+ if (!entityId || !idxId) {
34167
+ continue;
34168
+ }
34169
+ const idxInfo = new EntityIndexInfo({
34170
+ ...row,
34171
+ EntityIndexFields: fieldsByIndexId.get(idxId) ?? []
34172
+ });
34173
+ let list = indexesByEntityId.get(entityId);
34174
+ if (!list) {
34175
+ list = [];
34176
+ indexesByEntityId.set(entityId, list);
34177
+ }
34178
+ list.push(idxInfo);
34179
+ }
34180
+ for (const entity of this.Entities) {
34181
+ entity.SetIndexes(indexesByEntityId.get(NormalizeUUID(entity.ID)) ?? []);
34182
+ }
34183
+ this._entityIndexesLastFailedAt = 0;
34184
+ this._entityIndexesLastFailedGeneration = -1;
34185
+ this._entityIndexesLoadedGeneration = gen;
34186
+ } catch (e) {
34187
+ if (this._entityIndexesMetadataGeneration === gen) {
34188
+ this._entityIndexesLastFailedGeneration = gen;
34189
+ this._entityIndexesLastFailedAt = Date.now();
34190
+ }
34191
+ LogError(`EnsureEntityIndexesLoaded threw: ${e instanceof Error ? e.message : String(e)}`);
34192
+ } finally {
34193
+ if (this._entityIndexesLoadPromise === loadPromise) {
34194
+ this._entityIndexesLoadPromise = null;
34195
+ }
34196
+ }
34197
+ })();
34198
+ this._entityIndexesLoadPromise = loadPromise;
34199
+ return loadPromise;
34200
+ }
33754
34201
  /**
33755
34202
  * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
33756
34203
  * local dataset cache — so all of them describe the same row set. Null when every item is read.
@@ -38339,7 +38786,7 @@ var ProviderBase = class _ProviderBase {
38339
38786
  await this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName, itemFilters);
38340
38787
  }
38341
38788
  const simpleMetadata = _ProviderBase.metadataAssemblyInput(d);
38342
- 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);
38789
+ 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, simpleMetadata.EntityIndexes, simpleMetadata.EntityIndexFields);
38343
38790
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
38344
38791
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
38345
38792
  a.ApplicationSettings = simpleMetadata.ApplicationSettings.filter((as) => UUIDsEqual(as.ApplicationID, a.ID));
@@ -38358,7 +38805,7 @@ var ProviderBase = class _ProviderBase {
38358
38805
  }
38359
38806
  }
38360
38807
  static {
38361
- this._assemblyWrittenItemCodes = /* @__PURE__ */ new Set(["Entities", "EntityFields", "EntityOrganicKeys", "Applications"]);
38808
+ this._assemblyWrittenItemCodes = /* @__PURE__ */ new Set(["Entities", "EntityFields", "EntityOrganicKeys", "EntityIndexes", "Applications"]);
38362
38809
  }
38363
38810
  /**
38364
38811
  * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
@@ -38435,7 +38882,7 @@ var ProviderBase = class _ProviderBase {
38435
38882
  }
38436
38883
  return map2;
38437
38884
  }
38438
- PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys) {
38885
+ PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys, entityIndexes, entityIndexFields) {
38439
38886
  const result = [];
38440
38887
  const sortedEntities = entities.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
38441
38888
  if (fieldValues && fieldValues.length > 0) {
@@ -38459,6 +38906,12 @@ var ProviderBase = class _ProviderBase {
38459
38906
  ok.EntityOrganicKeyRelatedEntities = okreByOrganicKeyId.get(NormalizeUUID(ok.ID)) || [];
38460
38907
  }
38461
38908
  }
38909
+ if (entityIndexes && entityIndexes.length > 0 && entityIndexFields && entityIndexFields.length > 0) {
38910
+ const fieldsByIndexId = this.groupByNormalizedUUID(entityIndexFields, (f) => f.EntityIndexID);
38911
+ for (const idx of entityIndexes) {
38912
+ idx.EntityIndexFields = fieldsByIndexId.get(NormalizeUUID(idx.ID)) || [];
38913
+ }
38914
+ }
38462
38915
  const fieldsByEntityId = this.groupByNormalizedUUID(fields, (f) => f.EntityID);
38463
38916
  const permissionsByEntityId = this.groupByNormalizedUUID(permissions, (p) => p.EntityID);
38464
38917
  const relationshipsByEntityId = this.groupByNormalizedUUID(relationships, (r) => r.EntityID);
@@ -38466,6 +38919,7 @@ var ProviderBase = class _ProviderBase {
38466
38919
  const activeOrganicKeysByEntityId = organicKeys ? this.groupByNormalizedUUID(organicKeys.filter((ok) => ok.Status === "Active"), (ok) => ok.EntityID) : /* @__PURE__ */ new Map();
38467
38920
  const alternateBaseViewsByEntityId = alternateBaseViews && alternateBaseViews.length > 0 ? this.groupByNormalizedUUID(alternateBaseViews, (abv) => abv.EntityID) : /* @__PURE__ */ new Map();
38468
38921
  const uniqueKeysByEntityId = uniqueKeys && uniqueKeys.length > 0 ? this.groupByNormalizedUUID(uniqueKeys, (uk) => uk.EntityID) : /* @__PURE__ */ new Map();
38922
+ const indexesByEntityId = entityIndexes && entityIndexes.length > 0 ? this.groupByNormalizedUUID(entityIndexes, (idx) => idx.EntityID) : /* @__PURE__ */ new Map();
38469
38923
  for (const e of sortedEntities) {
38470
38924
  const entityIdKey = NormalizeUUID(e.ID);
38471
38925
  const entityFields = fieldsByEntityId.get(entityIdKey) || [];
@@ -38482,6 +38936,9 @@ var ProviderBase = class _ProviderBase {
38482
38936
  if (uniqueKeys) {
38483
38937
  e.EntityUniqueKeys = uniqueKeysByEntityId.get(entityIdKey) || [];
38484
38938
  }
38939
+ if (entityIndexes) {
38940
+ e.EntityIndexes = indexesByEntityId.get(entityIdKey) || [];
38941
+ }
38485
38942
  result.push(new EntityInfo(e, this));
38486
38943
  }
38487
38944
  const distinctSchemas = new Set(result.map((e) => e.SchemaName?.toLowerCase()));
@@ -39319,6 +39776,13 @@ var ProviderBase = class _ProviderBase {
39319
39776
  */
39320
39777
  UpdateLocalMetadata(res) {
39321
39778
  this._localMetadata = res;
39779
+ this._entityIndexesMetadataGeneration++;
39780
+ this._entityIndexesLoadPromise = null;
39781
+ this._entityIndexesLastFailedAt = 0;
39782
+ this._entityIndexesLastFailedGeneration = -1;
39783
+ if (res?.AllEntities?.some((e) => (e?.Indexes?.length ?? 0) > 0) ?? false) {
39784
+ this._entityIndexesLoadedGeneration = this._entityIndexesMetadataGeneration;
39785
+ }
39322
39786
  this.RebuildEntityMaps();
39323
39787
  }
39324
39788
  /**
@@ -41261,11 +41725,41 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
41261
41725
  */
41262
41726
  async GetRecordChanges(entityName, compositeKey, contextUser) {
41263
41727
  try {
41264
- const safeEntityName = entityName.replace(/'/g, "''");
41265
- const safeRecordID = compositeKey.ToConcatenatedString().replace(/'/g, "''");
41728
+ const safeEntityName = EscapeSQLString(entityName);
41729
+ const safeRecordID = EscapeSQLString(compositeKey.ToConcatenatedString());
41266
41730
  const schema = this.MJCoreSchemaName;
41267
41731
  const sSQL = `SELECT * FROM ${this.QuoteSchemaAndView(schema, "vwRecordChanges")} WHERE ${this.QuoteIdentifier("Entity")}='${safeEntityName}' AND ${this.QuoteIdentifier("RecordID")}='${safeRecordID}' ORDER BY ${this.QuoteIdentifier("ChangedAt")} DESC`;
41268
- return this.ExecuteSQL(sSQL, void 0, void 0, contextUser);
41732
+ const rows = await this.ExecuteSQL(sSQL, void 0, void 0, contextUser);
41733
+ if (!rows || rows.length === 0) {
41734
+ return rows;
41735
+ }
41736
+ const hooks = GetDataHooks("PostRunView");
41737
+ if (hooks.length === 0) {
41738
+ return rows;
41739
+ }
41740
+ const effectiveUser = contextUser ?? this.CurrentUser;
41741
+ const hookParams = {
41742
+ EntityName: "MJ: Record Changes",
41743
+ ExtraFilter: `Entity='${safeEntityName}' AND RecordID='${safeRecordID}'`,
41744
+ ResultType: "simple"
41745
+ };
41746
+ let hookResult = {
41747
+ Success: true,
41748
+ Results: rows,
41749
+ RowCount: rows.length,
41750
+ TotalRowCount: rows.length,
41751
+ ExecutionTime: 0,
41752
+ ErrorMessage: "",
41753
+ UserViewRunID: ""
41754
+ };
41755
+ for (const hook of hooks) {
41756
+ hookResult = await hook(hookParams, hookResult, effectiveUser, this);
41757
+ if (!hookResult.Success) {
41758
+ LogError(`DatabaseProviderBase.GetRecordChanges: PostRunView hook failed for '${entityName}' (${compositeKey.ToConcatenatedString()}): ${hookResult.ErrorMessage || "unknown error"}`);
41759
+ return [];
41760
+ }
41761
+ }
41762
+ return hookResult.Results ?? [];
41269
41763
  } catch (e) {
41270
41764
  LogError(e);
41271
41765
  throw e;
@@ -42874,7 +43368,9 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42874
43368
  fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
42875
43369
  }
42876
43370
  const changesJSON = changes !== null ? JSON.stringify(changes) : "";
42877
- const changesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
43371
+ const baseChangesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
43372
+ const impCtx = user?.ImpersonationContext;
43373
+ const changesDescription = impCtx ? `${baseChangesDescription} [Impersonated by ActorUserID=${impCtx.ActorUserID ?? "unknown"}, APIKeyID=${impCtx.APIKeyID}, Mode=${impCtx.Mode}]` : baseChangesDescription;
42878
43374
  const source = restoreContext ? "Restore" : cloneContext ? "Clone" : syncContext ? "Sync" : "Internal";
42879
43375
  const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : syncContext ? SerializeSyncChangeContext(syncContext) : null;
42880
43376
  return {
@@ -43131,70 +43627,6 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
43131
43627
  }
43132
43628
  };
43133
43629
 
43134
- // ../../MJCore/dist/generic/wellKnownUserSource.js
43135
- var WellKnownUserSource = class _WellKnownUserSource {
43136
- static {
43137
- this._globalStoreKey = "___SINGLETON__WellKnownUserSource";
43138
- }
43139
- /**
43140
- * The registered source for this process, resolved once through the class factory and
43141
- * stored in the Global Object Store so bundler duplication cannot split the cached instance.
43142
- *
43143
- * Cached because {@link IsSystemUser} sits behind permission checks that run per entity and
43144
- * per user; resolving (and allocating) on every call would be needless churn. Registrations
43145
- * happen as module-load side effects of importing a data-provider package, which always
43146
- * precedes any permission evaluation, so caching cannot capture a stale answer in practice.
43147
- * Tests that register a source after first use should call {@link ResetInstance}.
43148
- */
43149
- static get Instance() {
43150
- const g = GetGlobalObjectStore();
43151
- if (g) {
43152
- if (!g[_WellKnownUserSource._globalStoreKey]) {
43153
- g[_WellKnownUserSource._globalStoreKey] = MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
43154
- }
43155
- return g[_WellKnownUserSource._globalStoreKey];
43156
- }
43157
- return MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
43158
- }
43159
- /**
43160
- * Drops the cached {@link Instance} so the next access re-resolves through the class
43161
- * factory. Intended for tests that register a source after the cache was populated.
43162
- */
43163
- static ResetInstance() {
43164
- const g = GetGlobalObjectStore();
43165
- if (g) {
43166
- delete g[_WellKnownUserSource._globalStoreKey];
43167
- }
43168
- }
43169
- /**
43170
- * True when `user` is the MJ system user — the server's own service account, not a person.
43171
- *
43172
- * Synchronous on purpose: this is consumed by permission checks that cannot await. The base
43173
- * returns false, which is the right answer anywhere no server-side source is registered —
43174
- * a browser has no system account, so no user it holds can be one.
43175
- *
43176
- * Implementations must be null/undefined-safe so callers can pass an optional user directly.
43177
- */
43178
- IsSystemUser(user) {
43179
- return false;
43180
- }
43181
- /**
43182
- * The MJ system user for the given provider's connection, with `UserRoles` populated, or
43183
- * null when this process has no such identity to offer.
43184
- *
43185
- * Implementations MUST NOT throw — a missing user row, an unconfigured provider, or a
43186
- * failed lookup all resolve to null so callers can degrade rather than crash. Callers MUST
43187
- * treat null as "no elevated identity available" and fall back to their existing behavior.
43188
- *
43189
- * @param provider The provider whose connection the user is being resolved for. Passed
43190
- * explicitly (rather than read from a global) so a process holding several connections
43191
- * resolves the account belonging to the one actually in use.
43192
- */
43193
- async GetSystemUser(provider) {
43194
- return null;
43195
- }
43196
- };
43197
-
43198
43630
  // ../../MJCore/dist/generic/baseEngine.js
43199
43631
  var primaryKeyIndexes = /* @__PURE__ */ new WeakMap();
43200
43632
  var deltaHeldRowIndexes = /* @__PURE__ */ new WeakMap();
@@ -43843,9 +44275,10 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
43843
44275
  }
43844
44276
  }
43845
44277
  }
43846
- const newInstance = new subclassConstructor();
43847
- newInstance.SetProvider(provider);
43848
- return newInstance;
44278
+ const singletonCtor = subclassConstructor;
44279
+ const engineInstance = singletonCtor.Instance ?? (typeof singletonCtor.getInstance === "function" ? singletonCtor.getInstance() : new subclassConstructor());
44280
+ engineInstance.SetProvider(provider);
44281
+ return engineInstance;
43849
44282
  }
43850
44283
  /**
43851
44284
  * Removes all cached engine instances for the given connection. Call this when a connection
@@ -46613,15 +47046,16 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
46613
47046
  * derived state until something else happened to rebuild it.
46614
47047
  *
46615
47048
  * @param propertyName - The name of the property to refresh
47049
+ * @param bypassCache - When `true`, forces a server/database read instead of consulting `LocalCacheManager`
46616
47050
  */
46617
- async RefreshItem(propertyName) {
47051
+ async RefreshItem(propertyName, bypassCache) {
46618
47052
  const config = this._metadataConfigs.find((c) => c.PropertyName === propertyName) || this._dynamicConfigs.get(propertyName);
46619
47053
  if (config) {
46620
47054
  await this.LoadSingleConfig(
46621
47055
  config,
46622
47056
  this._contextUser,
46623
47057
  /*bypassCache*/
46624
- !!config.Expiration,
47058
+ bypassCache ?? !!config.Expiration,
46625
47059
  /*suppressEmit*/
46626
47060
  true
46627
47061
  );
@@ -47453,10 +47887,13 @@ var CODE_FALLBACK_LIMITS = {
47453
47887
  MaxInitialArtifactOperations: 100,
47454
47888
  MaxDirectInIds: 2500,
47455
47889
  MaxAgentsOfferedInDraft: 40,
47456
- MaxStepsPerSignal: 1e3
47890
+ MaxStepsPerSignal: 1e3,
47891
+ // A normal fingerprint recording is a read and one row write, far below five seconds; five
47892
+ // seconds is short enough that a run held behind the caller's own row lock returns promptly.
47893
+ QueryApprovalRecordingWaitMs: 5e3
47457
47894
  },
47458
47895
  Isolation: {
47459
- DefaultIsolation: "InProcess",
47896
+ DefaultIsolation: "Worker",
47460
47897
  DraftDefaultIsolation: "Worker",
47461
47898
  WorkerMaxOldGenerationSizeMb: 256,
47462
47899
  WorkerMaxYoungGenerationSizeMb: 64,
@@ -47479,6 +47916,21 @@ var CODE_FALLBACK_LIMITS = {
47479
47916
  MaxEnqueueRedeliveryAttempts: 5,
47480
47917
  EnqueuePublishRetryAttempts: 3,
47481
47918
  CallerNotificationRetentionMs: 864e5
47919
+ },
47920
+ Liveness: {
47921
+ Enabled: true,
47922
+ InactivityTimeoutMs: 9e5,
47923
+ OuterMaxWallClockMs: 2592e5,
47924
+ StreamChunkTouchThrottleMs: 5e3,
47925
+ HttpHeadersTimeoutMs: 18e5,
47926
+ HttpBodyTimeoutMs: 18e5
47927
+ },
47928
+ StuckDetector: {
47929
+ Enabled: true,
47930
+ WindowSize: 10,
47931
+ IdenticalToolCallThreshold: 3,
47932
+ ReadOnlyStepThreshold: 30,
47933
+ ReadOnlyPostDirectiveGraceSteps: 5
47482
47934
  }
47483
47935
  };
47484
47936
  var RESOURCE_GUARD_KEYS = [
@@ -47524,7 +47976,8 @@ var TUNING_KEYS = [
47524
47976
  "MaxInitialArtifactOperations",
47525
47977
  "MaxDirectInIds",
47526
47978
  "MaxAgentsOfferedInDraft",
47527
- "MaxStepsPerSignal"
47979
+ "MaxStepsPerSignal",
47980
+ "QueryApprovalRecordingWaitMs"
47528
47981
  ];
47529
47982
  var ISOLATION_NUMERIC_KEYS = [
47530
47983
  "WorkerMaxOldGenerationSizeMb",
@@ -47557,6 +48010,24 @@ var TASK_GRAPH_QUEUE_KEYS = [
47557
48010
  "DefaultEnqueueTopicName",
47558
48011
  ...TASK_GRAPH_QUEUE_NUMERIC_KEYS
47559
48012
  ];
48013
+ var LIVENESS_KEYS = [
48014
+ "Enabled",
48015
+ "InactivityTimeoutMs",
48016
+ "OuterMaxWallClockMs",
48017
+ "StreamChunkTouchThrottleMs",
48018
+ "HttpHeadersTimeoutMs",
48019
+ "HttpBodyTimeoutMs"
48020
+ ];
48021
+ var STUCK_DETECTOR_NUMERIC_KEYS = [
48022
+ "WindowSize",
48023
+ "IdenticalToolCallThreshold",
48024
+ "ReadOnlyStepThreshold",
48025
+ "ReadOnlyPostDirectiveGraceSteps"
48026
+ ];
48027
+ var STUCK_DETECTOR_KEYS = [
48028
+ "Enabled",
48029
+ ...STUCK_DETECTOR_NUMERIC_KEYS
48030
+ ];
47560
48031
  var LIMITS_KEY_PATHS = [
47561
48032
  "AgentChannelConsecutiveTurns",
47562
48033
  "AgentChannelWakesPerHour",
@@ -47594,7 +48065,9 @@ var LIMITS_KEY_PATHS = [
47594
48065
  ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
47595
48066
  ...TUNING_KEYS.map((k) => `Tuning.${k}`),
47596
48067
  ...ISOLATION_KEYS.map((k) => `Isolation.${k}`),
47597
- ...TASK_GRAPH_QUEUE_KEYS.map((k) => `TaskGraphQueue.${k}`)
48068
+ ...TASK_GRAPH_QUEUE_KEYS.map((k) => `TaskGraphQueue.${k}`),
48069
+ ...LIVENESS_KEYS.map((k) => `Liveness.${k}`),
48070
+ ...STUCK_DETECTOR_KEYS.map((k) => `StuckDetector.${k}`)
47598
48071
  ];
47599
48072
  var NUMERIC_CEILING_KEYS = /* @__PURE__ */ new Set([
47600
48073
  "AgentChannelConsecutiveTurns",
@@ -47618,7 +48091,12 @@ var NUMERIC_CEILING_KEYS = /* @__PURE__ */ new Set([
47618
48091
  "ProgressDetector.FastJudgeMaxInputChars",
47619
48092
  ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
47620
48093
  ...ISOLATION_NUMERIC_KEYS.map((k) => `Isolation.${k}`),
47621
- ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => `TaskGraphQueue.${k}`)
48094
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => `TaskGraphQueue.${k}`),
48095
+ "Liveness.InactivityTimeoutMs",
48096
+ "Liveness.OuterMaxWallClockMs",
48097
+ "StuckDetector.IdenticalToolCallThreshold",
48098
+ "StuckDetector.ReadOnlyStepThreshold",
48099
+ "StuckDetector.ReadOnlyPostDirectiveGraceSteps"
47622
48100
  ]);
47623
48101
  var LIMITS_KEY_ROLES = Object.fromEntries(LIMITS_KEY_PATHS.map((key) => [
47624
48102
  key,
@@ -47750,6 +48228,53 @@ function normalizeTaskGraphQueueOverride(raw) {
47750
48228
  }
47751
48229
  return Object.keys(out).length > 0 ? out : void 0;
47752
48230
  }
48231
+ function normalizeLivenessOverride(raw) {
48232
+ if (!isLimitsInputObject(raw)) {
48233
+ return void 0;
48234
+ }
48235
+ const out = {};
48236
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled", "LivenessEnabled", "livenessEnabled"]));
48237
+ if (enabled !== void 0)
48238
+ out.Enabled = enabled;
48239
+ const inactivity = readPositiveInteger(readObjectProperty(raw, ["InactivityTimeoutMs", "inactivityTimeoutMs"]));
48240
+ if (inactivity !== void 0)
48241
+ out.InactivityTimeoutMs = inactivity;
48242
+ const outerMax = readPositiveInteger(readObjectProperty(raw, ["OuterMaxWallClockMs", "outerMaxWallClockMs"]));
48243
+ if (outerMax !== void 0)
48244
+ out.OuterMaxWallClockMs = outerMax;
48245
+ const throttle = readFiniteNonNegativeNumber(readObjectProperty(raw, ["StreamChunkTouchThrottleMs", "streamChunkTouchThrottleMs"]));
48246
+ if (throttle !== void 0)
48247
+ out.StreamChunkTouchThrottleMs = Math.trunc(throttle);
48248
+ const headersTimeout = readFiniteNonNegativeNumber(readObjectProperty(raw, ["HttpHeadersTimeoutMs", "httpHeadersTimeoutMs"]));
48249
+ if (headersTimeout !== void 0)
48250
+ out.HttpHeadersTimeoutMs = Math.trunc(headersTimeout);
48251
+ const bodyTimeout = readFiniteNonNegativeNumber(readObjectProperty(raw, ["HttpBodyTimeoutMs", "httpBodyTimeoutMs"]));
48252
+ if (bodyTimeout !== void 0)
48253
+ out.HttpBodyTimeoutMs = Math.trunc(bodyTimeout);
48254
+ return Object.keys(out).length > 0 ? out : void 0;
48255
+ }
48256
+ function normalizeStuckDetectorOverride(raw) {
48257
+ if (!isLimitsInputObject(raw)) {
48258
+ return void 0;
48259
+ }
48260
+ const out = {};
48261
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled"]));
48262
+ if (enabled !== void 0)
48263
+ out.Enabled = enabled;
48264
+ const numeric = normalizePositiveIntSection(raw, STUCK_DETECTOR_NUMERIC_KEYS);
48265
+ if (numeric) {
48266
+ Object.assign(out, numeric);
48267
+ }
48268
+ const legacyIdentical = readPositiveInteger(readObjectProperty(raw, ["RepeatedToolCallThreshold", "repeatedToolCallThreshold"]));
48269
+ if (out.IdenticalToolCallThreshold === void 0 && legacyIdentical !== void 0) {
48270
+ out.IdenticalToolCallThreshold = legacyIdentical;
48271
+ }
48272
+ const legacyReadOnly = readPositiveInteger(readObjectProperty(raw, ["ReadOnlySpiralThreshold", "readOnlySpiralThreshold"]));
48273
+ if (out.ReadOnlyStepThreshold === void 0 && legacyReadOnly !== void 0) {
48274
+ out.ReadOnlyStepThreshold = legacyReadOnly;
48275
+ }
48276
+ return Object.keys(out).length > 0 ? out : void 0;
48277
+ }
47753
48278
  function normalizeScopeBudgetOverride(raw) {
47754
48279
  if (!isLimitsInputObject(raw)) {
47755
48280
  return void 0;
@@ -47930,6 +48455,12 @@ function NormalizeLimitsInput(raw) {
47930
48455
  const taskGraphQueue = normalizeTaskGraphQueueOverride(readObjectProperty(raw, ["TaskGraphQueue", "taskGraphQueue"]));
47931
48456
  if (taskGraphQueue)
47932
48457
  out.TaskGraphQueue = taskGraphQueue;
48458
+ const liveness = normalizeLivenessOverride(readObjectProperty(raw, ["Liveness", "liveness"]));
48459
+ if (liveness)
48460
+ out.Liveness = liveness;
48461
+ const stuckDetector = normalizeStuckDetectorOverride(readObjectProperty(raw, ["StuckDetector", "stuckDetector"]));
48462
+ if (stuckDetector)
48463
+ out.StuckDetector = stuckDetector;
47933
48464
  return out;
47934
48465
  }
47935
48466
  function cloneDefaultLimits() {
@@ -47947,7 +48478,9 @@ function cloneDefaultLimits() {
47947
48478
  ResourceGuards: { ...CODE_FALLBACK_LIMITS.ResourceGuards },
47948
48479
  Tuning: { ...CODE_FALLBACK_LIMITS.Tuning },
47949
48480
  Isolation: { ...CODE_FALLBACK_LIMITS.Isolation },
47950
- TaskGraphQueue: { ...CODE_FALLBACK_LIMITS.TaskGraphQueue }
48481
+ TaskGraphQueue: { ...CODE_FALLBACK_LIMITS.TaskGraphQueue },
48482
+ Liveness: { ...CODE_FALLBACK_LIMITS.Liveness },
48483
+ StuckDetector: { ...CODE_FALLBACK_LIMITS.StuckDetector }
47951
48484
  };
47952
48485
  }
47953
48486
  function extractTierValue(layer, key) {
@@ -47967,6 +48500,14 @@ function extractTierValue(layer, key) {
47967
48500
  const subKey = key.slice("TaskGraphQueue.".length);
47968
48501
  return layer.TaskGraphQueue?.[subKey];
47969
48502
  }
48503
+ if (key.startsWith("Liveness.")) {
48504
+ const subKey = key.slice("Liveness.".length);
48505
+ return layer.Liveness?.[subKey];
48506
+ }
48507
+ if (key.startsWith("StuckDetector.")) {
48508
+ const subKey = key.slice("StuckDetector.".length);
48509
+ return layer.StuckDetector?.[subKey];
48510
+ }
47970
48511
  switch (key) {
47971
48512
  case "AgentChannelConsecutiveTurns":
47972
48513
  return layer.AgentChannelConsecutiveTurns;
@@ -48067,6 +48608,24 @@ function assignResolvedValue(target, key, value) {
48067
48608
  }
48068
48609
  return;
48069
48610
  }
48611
+ if (key.startsWith("Liveness.")) {
48612
+ const subKey = key.slice("Liveness.".length);
48613
+ if (subKey === "Enabled") {
48614
+ target.Liveness.Enabled = value;
48615
+ } else {
48616
+ target.Liveness[subKey] = value;
48617
+ }
48618
+ return;
48619
+ }
48620
+ if (key.startsWith("StuckDetector.")) {
48621
+ const subKey = key.slice("StuckDetector.".length);
48622
+ if (subKey === "Enabled") {
48623
+ target.StuckDetector.Enabled = value;
48624
+ } else {
48625
+ target.StuckDetector[subKey] = value;
48626
+ }
48627
+ return;
48628
+ }
48070
48629
  switch (key) {
48071
48630
  case "AgentChannelConsecutiveTurns":
48072
48631
  target.AgentChannelConsecutiveTurns = value;
@@ -48269,13 +48828,26 @@ function ValidateLimitsConfig(config) {
48269
48828
  ...RESOURCE_GUARD_KEYS.map((k) => [`ResourceGuards.${k}`, config.ResourceGuards[k]]),
48270
48829
  ...TUNING_KEYS.map((k) => [`Tuning.${k}`, config.Tuning[k]]),
48271
48830
  ...ISOLATION_NUMERIC_KEYS.map((k) => [`Isolation.${k}`, config.Isolation[k]]),
48272
- ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => [`TaskGraphQueue.${k}`, config.TaskGraphQueue[k]])
48831
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => [`TaskGraphQueue.${k}`, config.TaskGraphQueue[k]]),
48832
+ ["Liveness.InactivityTimeoutMs", config.Liveness.InactivityTimeoutMs],
48833
+ ["Liveness.OuterMaxWallClockMs", config.Liveness.OuterMaxWallClockMs],
48834
+ ...STUCK_DETECTOR_NUMERIC_KEYS.map((k) => [`StuckDetector.${k}`, config.StuckDetector[k]])
48273
48835
  ];
48274
48836
  for (const [key, val] of positiveIntChecks) {
48275
48837
  if (!Number.isFinite(val) || val < 1) {
48276
48838
  issues.push({ Key: key, Message: `${key} must be a positive number >= 1.` });
48277
48839
  }
48278
48840
  }
48841
+ const nonNegativeLivenessChecks = [
48842
+ ["Liveness.StreamChunkTouchThrottleMs", config.Liveness.StreamChunkTouchThrottleMs],
48843
+ ["Liveness.HttpHeadersTimeoutMs", config.Liveness.HttpHeadersTimeoutMs],
48844
+ ["Liveness.HttpBodyTimeoutMs", config.Liveness.HttpBodyTimeoutMs]
48845
+ ];
48846
+ for (const [key, val] of nonNegativeLivenessChecks) {
48847
+ if (!Number.isFinite(val) || val < 0) {
48848
+ issues.push({ Key: key, Message: `${key} must be a non-negative number >= 0.` });
48849
+ }
48850
+ }
48279
48851
  if (!IsTaskGraphIsolationLevel(config.Isolation.DefaultIsolation)) {
48280
48852
  issues.push({
48281
48853
  Key: "Isolation.DefaultIsolation",
@@ -48930,6 +49502,915 @@ var PermissionDeniedError = class _PermissionDeniedError extends Error {
48930
49502
  }
48931
49503
  };
48932
49504
 
49505
+ // ../../MJCore/dist/generic/visibilityContentOrigin.js
49506
+ var CONTENT_ITEMS_ENTITY = "MJ: Content Items";
49507
+ var CONTENT_CHUNKS_ENTITY = "MJ: Content Item Chunks";
49508
+ var ENTITY_RECORD_DOCUMENTS_ENTITY = "MJ: Entity Record Documents";
49509
+ function GetContentFamilyLevel(entity, provider) {
49510
+ const visited = /* @__PURE__ */ new Set();
49511
+ let current = entity;
49512
+ while (current && !visited.has(current.ID)) {
49513
+ if (current.Name === CONTENT_CHUNKS_ENTITY)
49514
+ return "chunk";
49515
+ if (current.Name === CONTENT_ITEMS_ENTITY)
49516
+ return "item";
49517
+ visited.add(current.ID);
49518
+ current = current.ParentID ? safeEntityByID(provider, current.ParentID) : void 0;
49519
+ }
49520
+ return null;
49521
+ }
49522
+ async function EvaluateContentOriginGate(entity, level, items, ctx, narrowOutcome) {
49523
+ const rv = ctx.CreateRunView();
49524
+ const recordIDs = Array.from(new Set(items.map((i) => i.CanonicalRecordID)));
49525
+ let perPrincipalOrigins;
49526
+ try {
49527
+ perPrincipalOrigins = await Promise.all(ctx.Principals.map((principal) => resolveContentOriginsForPrincipal(rv, entity, level, recordIDs, principal, ctx.Provider)));
49528
+ } catch (err) {
49529
+ const msg = err instanceof Error ? err.message : String(err);
49530
+ LogError(`ResolveVisibility: content origin resolution failed for "${entity.Name}": ${msg}`);
49531
+ for (const item of items) {
49532
+ narrowOutcome(item, "Hidden", "DerivedContent", msg);
49533
+ }
49534
+ return;
49535
+ }
49536
+ const originRefsToCheck = [];
49537
+ const originRefByItemKey = /* @__PURE__ */ new Map();
49538
+ for (const item of items) {
49539
+ const firstOrigin = perPrincipalOrigins[0].get(item.CanonicalRecordID);
49540
+ if (firstOrigin === void 0) {
49541
+ narrowOutcome(item, "Hidden", "DerivedContent", "Content origin chain could not be read");
49542
+ continue;
49543
+ }
49544
+ let audienceFailed = false;
49545
+ let resolvedOrigin = firstOrigin;
49546
+ for (let i = 1; i < perPrincipalOrigins.length; i++) {
49547
+ const otherOrigin = perPrincipalOrigins[i].get(item.CanonicalRecordID);
49548
+ if (otherOrigin === void 0) {
49549
+ audienceFailed = true;
49550
+ break;
49551
+ }
49552
+ if (!resolvedOrigin && otherOrigin) {
49553
+ resolvedOrigin = otherOrigin;
49554
+ }
49555
+ }
49556
+ if (audienceFailed) {
49557
+ narrowOutcome(item, "Hidden", "AudienceIntersection", "Content origin chain not readable by all audience readers");
49558
+ continue;
49559
+ }
49560
+ originRefByItemKey.set(item.Key, resolvedOrigin);
49561
+ if (resolvedOrigin) {
49562
+ originRefsToCheck.push(resolvedOrigin);
49563
+ }
49564
+ }
49565
+ if (originRefsToCheck.length === 0) {
49566
+ return;
49567
+ }
49568
+ const originDecisions = await ctx.ResolveSubNodes(originRefsToCheck, { SkipBaseRowCheck: false });
49569
+ for (const item of items) {
49570
+ const origin = originRefByItemKey.get(item.Key);
49571
+ if (!origin) {
49572
+ continue;
49573
+ }
49574
+ const originKey = ctx.NodeKey(origin);
49575
+ const decision = originDecisions.get(originKey);
49576
+ if (!decision || decision.Outcome === "Hidden") {
49577
+ const step = decision?.DecidingStep === "DelegatedDocument" || decision?.DecidingStep === "AudienceIntersection" ? decision.DecidingStep : "DerivedContent";
49578
+ narrowOutcome(item, "Hidden", step, decision?.Reason ?? `Origin record ${origin.EntityName} is hidden`);
49579
+ } else if (decision.Outcome === "Redacted") {
49580
+ narrowOutcome(item, "Redacted", decision.DecidingStep, decision.Reason ?? `Origin record ${origin.EntityName} is redacted`);
49581
+ }
49582
+ }
49583
+ }
49584
+ async function resolveContentOriginsForPrincipal(rv, entity, level, recordIDs, principal, provider) {
49585
+ const itemOfRecord = level === "chunk" ? await lookupChunkItems(rv, entity, recordIDs, principal) : new Map(recordIDs.map((id) => [id, id]));
49586
+ const itemIDs = Array.from(new Set(itemOfRecord.values()));
49587
+ const erdOfItem = await lookupItemOrigins(rv, itemIDs, principal);
49588
+ const erdIDs = Array.from(new Set(Array.from(erdOfItem.values()).filter((id) => id !== null)));
49589
+ const originOfErd = await lookupEntityRecordDocuments(rv, erdIDs, principal, provider);
49590
+ const origins = /* @__PURE__ */ new Map();
49591
+ for (const id of recordIDs) {
49592
+ const itemID = itemOfRecord.get(id);
49593
+ if (itemID === void 0)
49594
+ continue;
49595
+ const erdID = erdOfItem.get(itemID);
49596
+ if (erdID === void 0)
49597
+ continue;
49598
+ if (erdID === null) {
49599
+ origins.set(id, null);
49600
+ continue;
49601
+ }
49602
+ const origin = originOfErd.get(erdID);
49603
+ if (origin) {
49604
+ origins.set(id, origin);
49605
+ }
49606
+ }
49607
+ return origins;
49608
+ }
49609
+ async function lookupChunkItems(rv, entity, chunkIDs, principal) {
49610
+ const pkName = entity.FirstPrimaryKey.Name;
49611
+ const rows = await runStrictLookup(rv, entity.Name, [pkName, "ContentItemID"], pkName, chunkIDs, principal);
49612
+ if (!rows) {
49613
+ throw new Error(`lookup of "${entity.Name}" failed; every chunk depends on it`);
49614
+ }
49615
+ const map2 = /* @__PURE__ */ new Map();
49616
+ for (const row of rows) {
49617
+ const pk = row[pkName];
49618
+ const itemID = row["ContentItemID"];
49619
+ if (typeof pk === "string" && typeof itemID === "string") {
49620
+ map2.set(NormalizeUUID(pk), NormalizeUUID(itemID));
49621
+ }
49622
+ }
49623
+ return map2;
49624
+ }
49625
+ async function lookupItemOrigins(rv, itemIDs, principal) {
49626
+ const fields = ["ID", "ParentID", "RootParentID", "EntityRecordDocumentID"];
49627
+ const rows = await runStrictLookup(rv, CONTENT_ITEMS_ENTITY, fields, "ID", itemIDs, principal);
49628
+ if (!rows) {
49629
+ throw new Error(`lookup of "${CONTENT_ITEMS_ENTITY}" failed; every content row depends on it`);
49630
+ }
49631
+ const map2 = /* @__PURE__ */ new Map();
49632
+ const rootOfChild = /* @__PURE__ */ new Map();
49633
+ for (const row of rows) {
49634
+ const id = NormalizeUUID(row.ID);
49635
+ const root = row.RootParentID ? NormalizeUUID(row.RootParentID) : null;
49636
+ if (row.EntityRecordDocumentID) {
49637
+ map2.set(id, NormalizeUUID(row.EntityRecordDocumentID));
49638
+ } else if (!row.ParentID) {
49639
+ map2.set(id, null);
49640
+ } else if (root && root !== id) {
49641
+ rootOfChild.set(id, root);
49642
+ } else {
49643
+ LogError(`ResolveVisibility: content item ${id} has ParentID without a resolvable RootParentID; hiding.`);
49644
+ }
49645
+ }
49646
+ if (rootOfChild.size === 0) {
49647
+ return map2;
49648
+ }
49649
+ const roots = Array.from(new Set(rootOfChild.values()));
49650
+ const rootRows = await runStrictLookup(rv, CONTENT_ITEMS_ENTITY, fields, "ID", roots, principal) ?? [];
49651
+ const docOfRoot = new Map(rootRows.map((r) => [NormalizeUUID(r.ID), r.EntityRecordDocumentID ? NormalizeUUID(r.EntityRecordDocumentID) : null]));
49652
+ for (const [child, root] of rootOfChild) {
49653
+ const doc = docOfRoot.get(root);
49654
+ if (doc !== void 0) {
49655
+ map2.set(child, doc);
49656
+ }
49657
+ }
49658
+ return map2;
49659
+ }
49660
+ async function lookupEntityRecordDocuments(rv, erdIDs, principal, provider) {
49661
+ const map2 = /* @__PURE__ */ new Map();
49662
+ if (erdIDs.length === 0) {
49663
+ return map2;
49664
+ }
49665
+ const res = await rv.RunView({
49666
+ EntityName: ENTITY_RECORD_DOCUMENTS_ENTITY,
49667
+ Fields: ["ID", "Entity", "EntityID", "RecordID"],
49668
+ ExtraFilter: `ID IN (${erdIDs.map((id) => `'${EscapeSQLString(id)}'`).join(",")})`,
49669
+ ResultType: "simple",
49670
+ MaxRows: erdIDs.length,
49671
+ SkipTotalRowCount: true
49672
+ }, principal);
49673
+ if (!res.Success) {
49674
+ LogError(`ResolveVisibility: lookup of "${ENTITY_RECORD_DOCUMENTS_ENTITY}" failed for user ${principal.ID}: ${res.ErrorMessage ?? "unknown error"}`);
49675
+ return map2;
49676
+ }
49677
+ const rows = res.Results ?? [];
49678
+ for (const row of rows) {
49679
+ const hasId = Object.prototype.hasOwnProperty.call(row, "ID");
49680
+ const hasRecordId = Object.prototype.hasOwnProperty.call(row, "RecordID");
49681
+ const hasEntity = Object.prototype.hasOwnProperty.call(row, "Entity") || Object.prototype.hasOwnProperty.call(row, "EntityID");
49682
+ if (!hasId || !hasRecordId || !hasEntity) {
49683
+ LogError(`ResolveVisibility: lookup of "${ENTITY_RECORD_DOCUMENTS_ENTITY}" omitted required link column for user ${principal.ID} (FLS denial); failing closed.`);
49684
+ return /* @__PURE__ */ new Map();
49685
+ }
49686
+ const originEntity = safeEntityLookup(provider, row.Entity ?? "", row.EntityID ?? void 0);
49687
+ const entityName = originEntity?.Name ?? (row.Entity ?? "");
49688
+ if (entityName && row.RecordID) {
49689
+ map2.set(NormalizeUUID(row.ID), {
49690
+ EntityName: entityName,
49691
+ ...originEntity?.ID ? { EntityID: originEntity.ID } : row.EntityID ? { EntityID: row.EntityID } : {},
49692
+ RecordID: row.RecordID
49693
+ });
49694
+ }
49695
+ }
49696
+ return map2;
49697
+ }
49698
+ async function runStrictLookup(rv, entityName, fields, keyField, ids, principal) {
49699
+ if (ids.length === 0) {
49700
+ return [];
49701
+ }
49702
+ const res = await rv.RunView({
49703
+ EntityName: entityName,
49704
+ Fields: fields,
49705
+ ExtraFilter: `${keyField} IN (${ids.map((id) => `'${EscapeSQLString(id)}'`).join(",")})`,
49706
+ ResultType: "simple",
49707
+ MaxRows: ids.length,
49708
+ SkipTotalRowCount: true
49709
+ }, principal);
49710
+ if (!res.Success) {
49711
+ LogError(`ResolveVisibility: lookup of "${entityName}" failed for user ${principal.ID}: ${res.ErrorMessage ?? "unknown error"}`);
49712
+ return null;
49713
+ }
49714
+ const missing = fields.find((f) => (res.Results ?? []).some((row) => !Object.prototype.hasOwnProperty.call(row, f)));
49715
+ if (missing) {
49716
+ LogError(`ResolveVisibility: lookup of "${entityName}" omitted required column "${missing}" for user ${principal.ID} (FLS denial); failing closed.`);
49717
+ return null;
49718
+ }
49719
+ return res.Results ?? [];
49720
+ }
49721
+ function safeEntityLookup(provider, entityName, entityId) {
49722
+ if (entityId) {
49723
+ const byId = safeEntityByID(provider, entityId);
49724
+ if (byId)
49725
+ return byId;
49726
+ }
49727
+ try {
49728
+ return provider.EntityByName(entityName) ?? void 0;
49729
+ } catch {
49730
+ return void 0;
49731
+ }
49732
+ }
49733
+ function safeEntityByID(provider, entityId) {
49734
+ try {
49735
+ return provider.EntityByID(entityId) ?? void 0;
49736
+ } catch {
49737
+ return void 0;
49738
+ }
49739
+ }
49740
+
49741
+ // ../../MJCore/dist/generic/visibilityAudit.js
49742
+ var VISIBILITY_AUDIT_LOG_TYPE_NAME = "Visibility Evaluation";
49743
+ var VISIBILITY_AUDIT_SINKS_STORE_KEY = "___MJ_VISIBILITY_AUDIT_SINKS___";
49744
+ var VISIBILITY_AUDIT_PENDING_WRITES_KEY = "___MJ_VISIBILITY_AUDIT_PENDING_WRITES___";
49745
+ function EmitConsolidatedVisibilityAuditEvent(caller, principals, decisions, provider) {
49746
+ EmitVisibilityAuditEvent(caller, principals, decisions, provider);
49747
+ }
49748
+ function EmitVisibilityAuditEvent(caller, principals, decisions, provider) {
49749
+ if (decisions.size === 0) {
49750
+ return;
49751
+ }
49752
+ let allowedCount = 0;
49753
+ let redactedCount = 0;
49754
+ let hiddenCount = 0;
49755
+ const entries = [];
49756
+ for (const d of decisions.values()) {
49757
+ if (d.Outcome === "Allowed")
49758
+ allowedCount++;
49759
+ else if (d.Outcome === "Redacted")
49760
+ redactedCount++;
49761
+ else
49762
+ hiddenCount++;
49763
+ entries.push({
49764
+ Key: d.Key,
49765
+ EntityName: d.Ref.EntityName,
49766
+ RecordID: d.Ref.RecordID,
49767
+ Outcome: d.Outcome,
49768
+ DecidingStep: d.DecidingStep
49769
+ });
49770
+ }
49771
+ const event = {
49772
+ Timestamp: /* @__PURE__ */ new Date(),
49773
+ Caller: caller,
49774
+ PrincipalIDs: principals.map((p) => p.ID),
49775
+ NodeCount: entries.length,
49776
+ AllowedCount: allowedCount,
49777
+ RedactedCount: redactedCount,
49778
+ HiddenCount: hiddenCount,
49779
+ Decisions: entries
49780
+ };
49781
+ for (const sink of getVisibilityAuditSinksList()) {
49782
+ try {
49783
+ const maybePromise = sink(event, provider, principals);
49784
+ if (maybePromise && typeof maybePromise.then === "function") {
49785
+ trackBackgroundAuditPromise(Promise.resolve(maybePromise).catch((err) => {
49786
+ LogError(`ResolveVisibility: visibility audit sink threw: ${err instanceof Error ? err.message : String(err)}`);
49787
+ }));
49788
+ }
49789
+ } catch (err) {
49790
+ LogError(`ResolveVisibility: visibility audit sink threw: ${err instanceof Error ? err.message : String(err)}`);
49791
+ }
49792
+ }
49793
+ if (provider instanceof DatabaseProviderBase) {
49794
+ const hasType = provider.AuditLogTypes?.some((a) => a?.Name?.trim().toLowerCase() === VISIBILITY_AUDIT_LOG_TYPE_NAME.toLowerCase());
49795
+ if (hasType) {
49796
+ trackBackgroundAuditPromise(persistVisibilityAuditLog(provider, event, principals));
49797
+ }
49798
+ }
49799
+ }
49800
+ function trackBackgroundAuditPromise(promise) {
49801
+ const pending = getPendingAuditWritesSet();
49802
+ const tracked = promise.finally(() => {
49803
+ pending.delete(tracked);
49804
+ });
49805
+ pending.add(tracked);
49806
+ }
49807
+ async function persistVisibilityAuditLog(provider, event, principals) {
49808
+ try {
49809
+ if (event.Decisions.length === 0) {
49810
+ return;
49811
+ }
49812
+ const distinctEntityNames = /* @__PURE__ */ new Set();
49813
+ let singleEntityName = null;
49814
+ for (const d of event.Decisions) {
49815
+ const norm = d.EntityName?.trim().toLowerCase();
49816
+ if (norm) {
49817
+ distinctEntityNames.add(norm);
49818
+ if (singleEntityName === null) {
49819
+ singleEntityName = d.EntityName.trim();
49820
+ }
49821
+ }
49822
+ }
49823
+ if (distinctEntityNames.size === 1 && distinctEntityNames.has("mj: audit logs")) {
49824
+ return;
49825
+ }
49826
+ let entityId = null;
49827
+ let recordId = null;
49828
+ if (distinctEntityNames.size === 1 && singleEntityName) {
49829
+ const entity = lookupEntityLogged(provider, singleEntityName);
49830
+ entityId = entity?.ID ?? null;
49831
+ recordId = entityId && event.Decisions.length === 1 ? event.Decisions[0].RecordID : null;
49832
+ }
49833
+ const systemUser = await resolveSystemUser(provider);
49834
+ const writerUser = systemUser ?? principals[0];
49835
+ if (!writerUser) {
49836
+ return;
49837
+ }
49838
+ const summary = `Visibility evaluated ${event.NodeCount} node(s) for ${event.PrincipalIDs.length} principal(s) via ${event.Caller}: ${event.AllowedCount} allowed, ${event.RedactedCount} redacted, ${event.HiddenCount} hidden.`;
49839
+ await provider.CreateAuditLogRecord(writerUser, null, VISIBILITY_AUDIT_LOG_TYPE_NAME, "Success", JSON.stringify({
49840
+ caller: event.Caller,
49841
+ principalIds: event.PrincipalIDs,
49842
+ nodeCount: event.NodeCount,
49843
+ allowedCount: event.AllowedCount,
49844
+ redactedCount: event.RedactedCount,
49845
+ hiddenCount: event.HiddenCount,
49846
+ decisions: event.Decisions.slice(0, 200)
49847
+ // Bound audit payload size for large batches
49848
+ }), entityId, recordId, summary, null);
49849
+ } catch (err) {
49850
+ LogError(`ResolveVisibility: failed writing visibility audit log: ${err instanceof Error ? err.message : String(err)}`);
49851
+ }
49852
+ }
49853
+ async function resolveSystemUser(provider) {
49854
+ try {
49855
+ const source = MJGlobal.Instance.ClassFactory.CreateInstance(WellKnownUserSource);
49856
+ return await source?.GetSystemUser(provider) ?? null;
49857
+ } catch (err) {
49858
+ LogError(`ResolveVisibility: failed resolving system user for visibility audit log: ${err instanceof Error ? err.message : String(err)}`);
49859
+ return null;
49860
+ }
49861
+ }
49862
+ function lookupEntityLogged(provider, entityName) {
49863
+ try {
49864
+ return provider.EntityByName(entityName) ?? void 0;
49865
+ } catch (err) {
49866
+ LogError(`ResolveVisibility: EntityByName("${entityName}") failed while writing audit log: ${err instanceof Error ? err.message : String(err)}`);
49867
+ return void 0;
49868
+ }
49869
+ }
49870
+ function getVisibilityAuditSinksList() {
49871
+ const store = GetGlobalObjectStore();
49872
+ if (!Array.isArray(store[VISIBILITY_AUDIT_SINKS_STORE_KEY])) {
49873
+ store[VISIBILITY_AUDIT_SINKS_STORE_KEY] = [];
49874
+ }
49875
+ return store[VISIBILITY_AUDIT_SINKS_STORE_KEY];
49876
+ }
49877
+ function getPendingAuditWritesSet() {
49878
+ const store = GetGlobalObjectStore();
49879
+ if (!(store[VISIBILITY_AUDIT_PENDING_WRITES_KEY] instanceof Set)) {
49880
+ store[VISIBILITY_AUDIT_PENDING_WRITES_KEY] = /* @__PURE__ */ new Set();
49881
+ }
49882
+ return store[VISIBILITY_AUDIT_PENDING_WRITES_KEY];
49883
+ }
49884
+
49885
+ // ../../MJCore/dist/generic/visibility.js
49886
+ var __decorate6 = function(decorators, target, key, desc) {
49887
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
49888
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
49889
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
49890
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
49891
+ };
49892
+ var MAX_VISIBILITY_DEPTH = 6;
49893
+ var BaseVisibilityRule = class BaseVisibilityRule2 {
49894
+ /** When `true`, the rule also applies to IS-A descendant entities of its registered entity name. */
49895
+ get MatchSubtypes() {
49896
+ return false;
49897
+ }
49898
+ /** Default deciding step reported when this rule narrows or hides a node. */
49899
+ get DecidingStep() {
49900
+ return "RecordPermission";
49901
+ }
49902
+ /**
49903
+ * When `true`, this rule authoritatively enforces record-level read visibility (such as
49904
+ * delegated-document fallback on `MJ: Artifacts`) after Step 1 checks entity-level `CanRead`
49905
+ * and any explicit DB RLS filter. When no explicit DB RLS clause applies to any principal,
49906
+ * Step 1 skips its generic `RunView` existence probe so the rule itself decides the batch.
49907
+ */
49908
+ get HandlesBaseRowSecurity() {
49909
+ return false;
49910
+ }
49911
+ /**
49912
+ * When `true`, server `RunView` hooks already enforce this rule for the calling user (e.g.
49913
+ * `GraphConceptReadSecurityHook` on `MJ: Graph Concepts` and `ArtifactReadSecurityHook` on
49914
+ * `MJ: Artifacts`), so `SearchEngine` may skip re-running this rule on self-evident `RunView`
49915
+ * hits for the same user (Finding 390). Defaults to `false` so entities without a `RunView`
49916
+ * read hook (`MJ: AI Agents`, `MJ: AI Skills`, `MJ: Queries`) are always verified.
49917
+ */
49918
+ get EnforcedByRunView() {
49919
+ return false;
49920
+ }
49921
+ };
49922
+ BaseVisibilityRule = __decorate6([
49923
+ RequiresSubclass()
49924
+ ], BaseVisibilityRule);
49925
+ function FormatVisibilityNodeKey(ref, provider) {
49926
+ const entity = safeEntityLookup2(provider, ref.EntityName, ref.EntityID);
49927
+ const entityPart = entity?.ID ? NormalizeUUID(entity.ID) : ref.EntityID ? NormalizeUUID(ref.EntityID) : ref.EntityName.trim().toLowerCase();
49928
+ const recordPart = normalizeRecordIdPart(entity, ref.RecordID);
49929
+ return `${entityPart}|${recordPart}`;
49930
+ }
49931
+ function VisibilityOutcomeSeverity(outcome) {
49932
+ if (outcome === "Hidden")
49933
+ return 2;
49934
+ if (outcome === "Redacted")
49935
+ return 1;
49936
+ return 0;
49937
+ }
49938
+ function IntersectVisibilityOutcomes(a, b) {
49939
+ return VisibilityOutcomeSeverity(a) >= VisibilityOutcomeSeverity(b) ? a : b;
49940
+ }
49941
+ function ResolveVisibilityRuleForEntity(entity, provider) {
49942
+ const visited = /* @__PURE__ */ new Set();
49943
+ let current = entity;
49944
+ let isSubtypeHop = false;
49945
+ while (current && !visited.has(current.ID)) {
49946
+ visited.add(current.ID);
49947
+ const reg = MJGlobal.Instance.ClassFactory.GetRegistration(BaseVisibilityRule, current.Name);
49948
+ if (reg) {
49949
+ const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseVisibilityRule, current.Name);
49950
+ if (instance && (!isSubtypeHop || instance.MatchSubtypes)) {
49951
+ return instance;
49952
+ }
49953
+ }
49954
+ isSubtypeHop = true;
49955
+ current = current.ParentID ? safeEntityByID2(provider, current.ParentID) : void 0;
49956
+ }
49957
+ return null;
49958
+ }
49959
+ async function ResolveVisibility(nodes, principals, options) {
49960
+ const depth = options.Depth ?? 0;
49961
+ const provider = options.Provider;
49962
+ const caller = options.Caller?.trim() || "ResolveVisibility";
49963
+ const principalList = deduplicatePrincipals(principals);
49964
+ const items = normalizeAndDeduplicateNodes(nodes, provider);
49965
+ const decisions = /* @__PURE__ */ new Map();
49966
+ if (items.length === 0) {
49967
+ return decisions;
49968
+ }
49969
+ if (depth > MAX_VISIBILITY_DEPTH) {
49970
+ LogError(`ResolveVisibility: exceeded max recursion depth (${MAX_VISIBILITY_DEPTH}); failing closed for ${items.length} node(s).`);
49971
+ for (const item of items) {
49972
+ decisions.set(item.Key, makeDecision(item, "Hidden", "Error", "Maximum visibility recursion depth exceeded"));
49973
+ }
49974
+ return decisions;
49975
+ }
49976
+ if (principalList.length === 0 || principalList.some((p) => !p || !p.ID || p.IsActive === false)) {
49977
+ for (const item of items) {
49978
+ decisions.set(item.Key, makeDecision(item, "Hidden", "EntityPermission", "Invalid or inactive principal"));
49979
+ }
49980
+ recordOrEmitAudit(depth, caller, principalList, decisions, provider, options);
49981
+ return decisions;
49982
+ }
49983
+ const createRunView = () => options.RunViewFactory ? options.RunViewFactory(provider) : RunView.FromMetadataProvider(provider);
49984
+ const working = /* @__PURE__ */ new Map();
49985
+ const byEntity = /* @__PURE__ */ new Map();
49986
+ for (const item of items) {
49987
+ if (!item.Entity || !item.CanonicalRecordID) {
49988
+ working.set(item.Key, makeDecision(item, "Hidden", "EntityPermission", "Unknown entity or empty record ID"));
49989
+ continue;
49990
+ }
49991
+ working.set(item.Key, makeDecision(item, "Allowed", "Allowed"));
49992
+ const bucket = byEntity.get(item.Entity.Name) ?? { Entity: item.Entity, Items: [] };
49993
+ bucket.Items.push(item);
49994
+ byEntity.set(item.Entity.Name, bucket);
49995
+ }
49996
+ if (!options.SkipBaseRowCheck) {
49997
+ await evaluateEntityAndRowSecurity(byEntity, principalList, provider, createRunView, working);
49998
+ } else {
49999
+ for (const [, bucket] of byEntity) {
50000
+ const firstCanRead = Boolean(bucket.Entity.GetUserPermisions(principalList[0])?.CanRead);
50001
+ const allCanRead = firstCanRead && principalList.every((p) => Boolean(bucket.Entity.GetUserPermisions(p)?.CanRead));
50002
+ if (!allCanRead) {
50003
+ const step = firstCanRead ? "AudienceIntersection" : "EntityPermission";
50004
+ for (const item of bucket.Items) {
50005
+ narrowDecision(working, item, "Hidden", step, `User lacks Read permission on ${bucket.Entity.Name}`);
50006
+ }
50007
+ }
50008
+ }
50009
+ }
50010
+ if (options.CheckFields && options.CheckFields.length > 0) {
50011
+ evaluateFieldLevelSecurity(byEntity, principalList, options.CheckFields, working);
50012
+ }
50013
+ const ruleContext = {
50014
+ Principal: principalList[0],
50015
+ Principals: principalList,
50016
+ Provider: provider,
50017
+ IncludeProposed: options.IncludeProposed === true,
50018
+ Caller: caller,
50019
+ Depth: depth,
50020
+ CreateRunView: createRunView,
50021
+ NodeKey: (ref) => FormatVisibilityNodeKey(ref, provider),
50022
+ ResolveSubNodes: async (refs, overrides) => ResolveVisibility(refs, principalList, {
50023
+ Provider: provider,
50024
+ Caller: caller,
50025
+ IncludeProposed: overrides?.IncludeProposed ?? options.IncludeProposed,
50026
+ SkipBaseRowCheck: overrides?.SkipBaseRowCheck ?? false,
50027
+ SkipAuditLog: true,
50028
+ RunViewFactory: options.RunViewFactory,
50029
+ Depth: depth + 1
50030
+ })
50031
+ };
50032
+ for (const [, bucket] of byEntity) {
50033
+ const surviving = bucket.Items.filter((item) => working.get(item.Key)?.Outcome !== "Hidden");
50034
+ if (surviving.length === 0) {
50035
+ continue;
50036
+ }
50037
+ const contentLevel = GetContentFamilyLevel(bucket.Entity, provider);
50038
+ if (contentLevel) {
50039
+ await EvaluateContentOriginGate(bucket.Entity, contentLevel, surviving, ruleContext, (item, outcome, step, reason) => {
50040
+ const fullItem = surviving.find((s) => s.Key === item.Key);
50041
+ if (fullItem) {
50042
+ narrowDecision(working, fullItem, outcome, step, reason);
50043
+ }
50044
+ });
50045
+ }
50046
+ const postContentSurviving = surviving.filter((item) => working.get(item.Key)?.Outcome !== "Hidden");
50047
+ if (postContentSurviving.length === 0) {
50048
+ continue;
50049
+ }
50050
+ const rule = ResolveVisibilityRuleForEntity(bucket.Entity, provider);
50051
+ if (rule) {
50052
+ await applyVisibilityRule(rule, bucket.Entity, postContentSurviving, ruleContext, working);
50053
+ }
50054
+ }
50055
+ for (const item of items) {
50056
+ decisions.set(item.Key, working.get(item.Key) ?? makeDecision(item, "Hidden", "Error", "Missing visibility decision"));
50057
+ }
50058
+ recordOrEmitAudit(depth, caller, principalList, decisions, provider, options);
50059
+ return decisions;
50060
+ }
50061
+ async function evaluateEntityAndRowSecurity(byEntity, principals, provider, createRunView, working) {
50062
+ const readableBuckets = [];
50063
+ for (const [, bucket] of byEntity) {
50064
+ const firstCanRead = Boolean(bucket.Entity.GetUserPermisions(principals[0])?.CanRead);
50065
+ const allCanRead = firstCanRead && principals.every((p) => Boolean(bucket.Entity.GetUserPermisions(p)?.CanRead));
50066
+ if (!allCanRead) {
50067
+ const step = firstCanRead ? "AudienceIntersection" : "EntityPermission";
50068
+ for (const item of bucket.Items) {
50069
+ narrowDecision(working, item, "Hidden", step, `Read denied on ${bucket.Entity.Name}`);
50070
+ }
50071
+ continue;
50072
+ }
50073
+ const registeredRule = ResolveVisibilityRuleForEntity(bucket.Entity, provider);
50074
+ const hasAnyRlsClause = typeof bucket.Entity.GetEffectiveRowFilterWhereClause === "function" && principals.some((p) => Boolean(bucket.Entity.GetEffectiveRowFilterWhereClause(p, EntityPermissionType.Read, "")));
50075
+ if (registeredRule?.HandlesBaseRowSecurity && !hasAnyRlsClause) {
50076
+ continue;
50077
+ }
50078
+ readableBuckets.push(bucket);
50079
+ }
50080
+ if (readableBuckets.length === 0) {
50081
+ return;
50082
+ }
50083
+ const rv = createRunView();
50084
+ const perPrincipalReadable = await Promise.all(principals.map((principal) => readReadableKeysForPrincipal(rv, readableBuckets, principal)));
50085
+ for (const bucket of readableBuckets) {
50086
+ for (const item of bucket.Items) {
50087
+ const canonicalKey = item.ParsedKey ? canonicalKeyValues(bucket.Entity, item.ParsedKey) : "";
50088
+ if (!canonicalKey) {
50089
+ narrowDecision(working, item, "Hidden", "RowLevelSecurity", `Malformed primary key for ${bucket.Entity.Name}`);
50090
+ continue;
50091
+ }
50092
+ const firstSet = perPrincipalReadable[0].get(bucket.Entity.Name);
50093
+ const firstVisible = Boolean(firstSet?.has(canonicalKey));
50094
+ if (!firstVisible) {
50095
+ narrowDecision(working, item, "Hidden", "RowLevelSecurity", `Row not readable in ${bucket.Entity.Name}`);
50096
+ continue;
50097
+ }
50098
+ for (let i = 1; i < perPrincipalReadable.length; i++) {
50099
+ if (!perPrincipalReadable[i].get(bucket.Entity.Name)?.has(canonicalKey)) {
50100
+ narrowDecision(working, item, "Hidden", "AudienceIntersection", `Row not readable by all audience readers in ${bucket.Entity.Name}`);
50101
+ break;
50102
+ }
50103
+ }
50104
+ }
50105
+ }
50106
+ }
50107
+ async function readReadableKeysForPrincipal(rv, buckets, principal) {
50108
+ const out = /* @__PURE__ */ new Map();
50109
+ const checks = [];
50110
+ for (const bucket of buckets) {
50111
+ const rlsClause = typeof bucket.Entity.GetEffectiveRowFilterWhereClause === "function" ? bucket.Entity.GetEffectiveRowFilterWhereClause(principal, EntityPermissionType.Read, "") || void 0 : void 0;
50112
+ const params = buildReadableKeysParams(bucket.Entity, bucket.Items, rlsClause);
50113
+ if (params) {
50114
+ checks.push({ Entity: bucket.Entity, Params: params });
50115
+ }
50116
+ }
50117
+ if (checks.length === 0) {
50118
+ return out;
50119
+ }
50120
+ let results;
50121
+ try {
50122
+ results = await rv.RunViews(checks.map((c) => c.Params), principal);
50123
+ } catch (err) {
50124
+ const msg = err instanceof Error ? err.message : String(err);
50125
+ LogError(`ResolveVisibility: batched RunViews failed for principal ${principal.ID}: ${msg}`);
50126
+ return out;
50127
+ }
50128
+ checks.forEach((check, idx) => {
50129
+ const res = results[idx];
50130
+ if (!res?.Success) {
50131
+ LogError(`ResolveVisibility: read check for "${check.Entity.Name}" failed for principal ${principal.ID}: ${res?.ErrorMessage ?? "unknown error"}`);
50132
+ return;
50133
+ }
50134
+ const pkFields = check.Entity.PrimaryKeys;
50135
+ const set = /* @__PURE__ */ new Set();
50136
+ for (const row of res.Results ?? []) {
50137
+ if (pkFields.some((pk) => !Object.prototype.hasOwnProperty.call(row, pk.Name) || row[pk.Name] == null)) {
50138
+ continue;
50139
+ }
50140
+ const keyStr = pkFields.map((pk) => NormalizeUUID(String(row[pk.Name]))).join("||");
50141
+ set.add(keyStr);
50142
+ }
50143
+ out.set(check.Entity.Name, set);
50144
+ });
50145
+ return out;
50146
+ }
50147
+ function buildReadableKeysParams(entity, items, rlsClause) {
50148
+ const pkFields = entity.PrimaryKeys;
50149
+ if (!pkFields || pkFields.length === 0) {
50150
+ return null;
50151
+ }
50152
+ const validKeys = items.map((i) => i.ParsedKey).filter((k) => k !== null && k.KeyValuePairs.length === pkFields.length);
50153
+ if (validKeys.length === 0) {
50154
+ return null;
50155
+ }
50156
+ let pkFilter;
50157
+ if (pkFields.length === 1) {
50158
+ const pkName = pkFields[0].Name;
50159
+ const distinctValues = Array.from(new Set(validKeys.map((k) => k.KeyValuePairs[0]?.Value).filter((v) => v != null && String(v).trim().length > 0).map((v) => String(v))));
50160
+ if (distinctValues.length === 0) {
50161
+ return null;
50162
+ }
50163
+ pkFilter = `${pkName} IN (${distinctValues.map((v) => `'${EscapeSQLString(v)}'`).join(",")})`;
50164
+ } else {
50165
+ const tuples = validKeys.map((k) => {
50166
+ const parts = pkFields.map((pk) => {
50167
+ const pair = k.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50168
+ return `${pk.Name}='${EscapeSQLString(String(pair?.Value ?? ""))}'`;
50169
+ });
50170
+ return `(${parts.join(" AND ")})`;
50171
+ });
50172
+ pkFilter = tuples.length === 1 ? tuples[0] : `(${tuples.join(" OR ")})`;
50173
+ }
50174
+ const extraFilter = rlsClause ? `(${pkFilter}) AND (${rlsClause})` : pkFilter;
50175
+ return {
50176
+ EntityName: entity.Name,
50177
+ Fields: pkFields.map((pk) => pk.Name),
50178
+ ExtraFilter: extraFilter,
50179
+ ResultType: "simple",
50180
+ MaxRows: validKeys.length,
50181
+ SkipTotalRowCount: true
50182
+ };
50183
+ }
50184
+ function evaluateFieldLevelSecurity(byEntity, principals, checkFields, working) {
50185
+ for (const [, bucket] of byEntity) {
50186
+ if (typeof bucket.Entity.IsFieldReadableByUser !== "function") {
50187
+ continue;
50188
+ }
50189
+ const hiddenForFirst = [];
50190
+ const hiddenForAudience = [];
50191
+ for (const fieldName of checkFields) {
50192
+ const firstCanRead = bucket.Entity.IsFieldReadableByUser(fieldName, principals[0]);
50193
+ if (!firstCanRead) {
50194
+ hiddenForFirst.push(fieldName);
50195
+ } else if (principals.slice(1).some((p) => !bucket.Entity.IsFieldReadableByUser(fieldName, p))) {
50196
+ hiddenForAudience.push(fieldName);
50197
+ }
50198
+ }
50199
+ const allHidden = [...hiddenForFirst, ...hiddenForAudience];
50200
+ if (allHidden.length === 0) {
50201
+ continue;
50202
+ }
50203
+ const nameFieldLower = bucket.Entity.NameField?.Name?.trim().toLowerCase();
50204
+ const hidesNameField = nameFieldLower != null && allHidden.some((f) => f.trim().toLowerCase() === nameFieldLower);
50205
+ const step = hiddenForFirst.length > 0 ? "FieldLevelSecurity" : "AudienceIntersection";
50206
+ for (const item of bucket.Items) {
50207
+ const existing = working.get(item.Key);
50208
+ if (!existing || existing.Outcome === "Hidden") {
50209
+ continue;
50210
+ }
50211
+ if (hidesNameField) {
50212
+ working.set(item.Key, {
50213
+ ...existing,
50214
+ Outcome: IntersectVisibilityOutcomes(existing.Outcome, "Redacted"),
50215
+ DecidingStep: existing.Outcome === "Allowed" ? step : existing.DecidingStep,
50216
+ HiddenFields: allHidden,
50217
+ Reason: existing.Reason ?? `Field-level security hides ${allHidden.join(", ")}`
50218
+ });
50219
+ } else {
50220
+ working.set(item.Key, { ...existing, HiddenFields: allHidden });
50221
+ }
50222
+ }
50223
+ }
50224
+ }
50225
+ async function applyVisibilityRule(rule, entity, items, ctx, working) {
50226
+ const inputs = items.map((item) => ({
50227
+ Key: item.Key,
50228
+ Ref: item.Ref,
50229
+ Entity: entity,
50230
+ CanonicalRecordID: item.CanonicalRecordID,
50231
+ CurrentOutcome: working.get(item.Key)?.Outcome ?? "Allowed"
50232
+ }));
50233
+ let outcomes;
50234
+ try {
50235
+ outcomes = await rule.Evaluate(inputs, ctx);
50236
+ } catch (err) {
50237
+ const msg = err instanceof Error ? err.message : String(err);
50238
+ LogError(`ResolveVisibility: visibility rule for "${entity.Name}" threw; failing closed: ${msg}`);
50239
+ for (const item of items) {
50240
+ narrowDecision(working, item, "Hidden", "Error", msg);
50241
+ }
50242
+ return;
50243
+ }
50244
+ for (const item of items) {
50245
+ const res = outcomes.get(item.Key);
50246
+ if (!res) {
50247
+ narrowDecision(working, item, "Hidden", rule.DecidingStep, `Rule for ${entity.Name} omitted decision`);
50248
+ continue;
50249
+ }
50250
+ if (res.Outcome === "Allowed") {
50251
+ continue;
50252
+ }
50253
+ narrowDecision(working, item, res.Outcome, res.DecidingStep ?? rule.DecidingStep, res.Reason, res.HiddenFields);
50254
+ }
50255
+ }
50256
+ function recordOrEmitAudit(depth, caller, principals, decisions, provider, options) {
50257
+ if (depth !== 0 || decisions.size === 0) {
50258
+ return;
50259
+ }
50260
+ if (options.AuditCollector) {
50261
+ for (const [key, decision] of decisions) {
50262
+ const existing = options.AuditCollector.get(key);
50263
+ if (!existing || VisibilityOutcomeSeverity(decision.Outcome) > VisibilityOutcomeSeverity(existing.Outcome)) {
50264
+ options.AuditCollector.set(key, decision);
50265
+ }
50266
+ }
50267
+ return;
50268
+ }
50269
+ if (options.SkipAuditLog === true) {
50270
+ return;
50271
+ }
50272
+ EmitVisibilityAuditEvent(caller, principals, decisions, provider);
50273
+ }
50274
+ function deduplicatePrincipals(principals) {
50275
+ const input = Array.isArray(principals) ? principals : [principals];
50276
+ const out = [];
50277
+ const seen = new UUIDSet();
50278
+ for (const p of input) {
50279
+ if (!p) {
50280
+ continue;
50281
+ }
50282
+ if (p.ID) {
50283
+ if (seen.Has(p.ID)) {
50284
+ continue;
50285
+ }
50286
+ seen.Add(p.ID);
50287
+ }
50288
+ out.push(p);
50289
+ }
50290
+ return out;
50291
+ }
50292
+ function normalizeAndDeduplicateNodes(nodes, provider) {
50293
+ const seen = /* @__PURE__ */ new Set();
50294
+ const out = [];
50295
+ for (const ref of nodes) {
50296
+ if (!ref || !ref.EntityName || !ref.RecordID) {
50297
+ continue;
50298
+ }
50299
+ const entity = safeEntityLookup2(provider, ref.EntityName, ref.EntityID);
50300
+ const key = FormatVisibilityNodeKey(ref, provider);
50301
+ if (seen.has(key)) {
50302
+ continue;
50303
+ }
50304
+ seen.add(key);
50305
+ const parsedKey = entity ? parseNodeCompositeKey(entity, ref.RecordID) : null;
50306
+ const canonicalId = entity && parsedKey ? canonicalKeyValues(entity, parsedKey) : NormalizeUUID(ref.RecordID.trim());
50307
+ out.push({
50308
+ Key: key,
50309
+ Ref: entity ? { EntityName: entity.Name, EntityID: entity.ID, RecordID: ref.RecordID } : ref,
50310
+ Entity: entity ?? null,
50311
+ CanonicalRecordID: canonicalId,
50312
+ ParsedKey: parsedKey
50313
+ });
50314
+ }
50315
+ return out;
50316
+ }
50317
+ function getEntityPrimaryKeys(entity) {
50318
+ if (Array.isArray(entity.PrimaryKeys) && entity.PrimaryKeys.length > 0) {
50319
+ return entity.PrimaryKeys;
50320
+ }
50321
+ return entity.FirstPrimaryKey ? [entity.FirstPrimaryKey] : [];
50322
+ }
50323
+ function parseNodeCompositeKey(entity, recordId) {
50324
+ const trimmed = recordId.trim();
50325
+ const pkFields = getEntityPrimaryKeys(entity);
50326
+ if (!trimmed || pkFields.length === 0) {
50327
+ return null;
50328
+ }
50329
+ try {
50330
+ const key = CompositeKey.FromURLSegment(entity, trimmed);
50331
+ if (key.KeyValuePairs.length === pkFields.length && pkFields.every((pk) => {
50332
+ const pair = key.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50333
+ return pair != null && pair.Value != null && String(pair.Value).trim().length > 0;
50334
+ })) {
50335
+ return key;
50336
+ }
50337
+ } catch {
50338
+ }
50339
+ if (pkFields.length === 1 && !trimmed.includes("|")) {
50340
+ return CompositeKey.FromKeyValuePair(pkFields[0].Name, trimmed);
50341
+ }
50342
+ return null;
50343
+ }
50344
+ function normalizeRecordIdPart(entity, recordId) {
50345
+ const trimmed = recordId?.trim() ?? "";
50346
+ if (!entity || !trimmed) {
50347
+ return NormalizeUUID(trimmed);
50348
+ }
50349
+ const parsed = parseNodeCompositeKey(entity, trimmed);
50350
+ if (!parsed) {
50351
+ return NormalizeUUID(trimmed);
50352
+ }
50353
+ return canonicalKeyValues(entity, parsed);
50354
+ }
50355
+ function canonicalKeyValues(entity, key) {
50356
+ return getEntityPrimaryKeys(entity).map((pk) => {
50357
+ const match = key.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50358
+ return NormalizeUUID(String(match?.Value ?? ""));
50359
+ }).join("||");
50360
+ }
50361
+ function safeEntityLookup2(provider, entityName, entityId) {
50362
+ if (!provider) {
50363
+ return void 0;
50364
+ }
50365
+ if (entityId) {
50366
+ const byId = safeEntityByID2(provider, entityId);
50367
+ if (byId)
50368
+ return byId;
50369
+ }
50370
+ try {
50371
+ return provider.EntityByName(entityName) ?? void 0;
50372
+ } catch (err) {
50373
+ LogError(`ResolveVisibility: EntityByName("${entityName}") threw: ${err instanceof Error ? err.message : String(err)}`);
50374
+ return void 0;
50375
+ }
50376
+ }
50377
+ function safeEntityByID2(provider, entityId) {
50378
+ try {
50379
+ return provider.EntityByID(entityId) ?? void 0;
50380
+ } catch (err) {
50381
+ LogError(`ResolveVisibility: EntityByID("${entityId}") threw: ${err instanceof Error ? err.message : String(err)}`);
50382
+ return void 0;
50383
+ }
50384
+ }
50385
+ function makeDecision(item, outcome, step, reason, hiddenFields) {
50386
+ return {
50387
+ Key: item.Key,
50388
+ Ref: item.Ref,
50389
+ Outcome: outcome,
50390
+ DecidingStep: step,
50391
+ ...reason ? { Reason: reason } : {},
50392
+ ...hiddenFields && hiddenFields.length > 0 ? { HiddenFields: hiddenFields } : {}
50393
+ };
50394
+ }
50395
+ function narrowDecision(working, item, outcome, step, reason, hiddenFields) {
50396
+ const existing = working.get(item.Key);
50397
+ if (!existing) {
50398
+ working.set(item.Key, makeDecision(item, outcome, step, reason, hiddenFields));
50399
+ return;
50400
+ }
50401
+ if (VisibilityOutcomeSeverity(outcome) > VisibilityOutcomeSeverity(existing.Outcome)) {
50402
+ const mergedFields = mergeHiddenFields(existing.HiddenFields, hiddenFields);
50403
+ working.set(item.Key, makeDecision(item, outcome, step, reason, mergedFields));
50404
+ } else if (hiddenFields && hiddenFields.length > 0) {
50405
+ working.set(item.Key, { ...existing, HiddenFields: mergeHiddenFields(existing.HiddenFields, hiddenFields) });
50406
+ }
50407
+ }
50408
+ function mergeHiddenFields(a, b) {
50409
+ if (!a?.length && !b?.length)
50410
+ return void 0;
50411
+ return Array.from(/* @__PURE__ */ new Set([...a ?? [], ...b ?? []]));
50412
+ }
50413
+
48933
50414
  // ../../MJCore/dist/index.js
48934
50415
  function SetProvider(provider) {
48935
50416
  Metadata.Provider = provider;
@@ -49154,6 +50635,7 @@ export {
49154
50635
  CompositeKey,
49155
50636
  ExtractAlternateBaseViewFromDisplayState,
49156
50637
  GetEffectiveAlternateBaseViewName,
50638
+ CONTEXT_TOKEN_CONTRACT_VERSION,
49157
50639
  TIME_ZONE_HEADER,
49158
50640
  GetLocalTimeZone,
49159
50641
  ValidateUserViewProperties,
@@ -49166,6 +50648,7 @@ export {
49166
50648
  CompositeFilterSQLCompiler,
49167
50649
  RunView,
49168
50650
  Metadata,
50651
+ EntityAlternateBaseViewInfo,
49169
50652
  EntityPermissionType,
49170
50653
  ReadableFieldsTransportKey,
49171
50654
  EntityFieldTSType,
@@ -49186,11 +50669,11 @@ export {
49186
50669
  IsTransportError,
49187
50670
  FieldSecuritySQLGate,
49188
50671
  FindQueryContextTokens,
50672
+ WellKnownUserSource,
49189
50673
  ProviderBase,
49190
50674
  TransactionItem,
49191
50675
  TransactionResult,
49192
50676
  TransactionGroupBase,
49193
- WellKnownUserSource,
49194
50677
  PermissionConstrainedError,
49195
50678
  BaseEngine,
49196
50679
  ResolveEntityEventRow,
@@ -49211,6 +50694,10 @@ export {
49211
50694
  StartupManager,
49212
50695
  PermissionProviderBase,
49213
50696
  PermissionDeniedError,
50697
+ EmitConsolidatedVisibilityAuditEvent,
50698
+ BaseVisibilityRule,
50699
+ FormatVisibilityNodeKey,
50700
+ ResolveVisibility,
49214
50701
  SetProvider,
49215
50702
  UserViewEngine
49216
50703
  };