@myvitalrx/metadata-runtime 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
3
3
  import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
4
4
  import crypto, { createHash } from 'crypto';
5
- import { createLogger, createPerformanceTimer } from '@myvitalrx/platform-tools/observability';
5
+ import { createLogger, createPerformanceTimer, getContext } from '@myvitalrx/platform-tools/observability';
6
6
  import { AsyncLocalStorage } from 'async_hooks';
7
7
  import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
8
8
 
@@ -87,6 +87,11 @@ var PROJECTION_TYPE = {
87
87
  * Platform file — not a domain Metadata Type.
88
88
  */
89
89
  RELATIONSHIP_INDEX: "relationshipIndex",
90
+ /**
91
+ * Forward relation rows (`typed-relations.json`), including inactive relations.
92
+ * Additive. The bidirectional index stays active-only.
93
+ */
94
+ TYPED_RELATIONS: "typedRelations",
90
95
  /**
91
96
  * @deprecated Removed from publish — capabilities live on manifest.json.
92
97
  * Kept so transitional parsers can ignore leftover objects.
@@ -105,6 +110,7 @@ var PROJECTION_FILE_NAME = {
105
110
  [PROJECTION_TYPE.LANGUAGE]: "Language.json",
106
111
  [PROJECTION_TYPE.COMMON]: "common.json",
107
112
  [PROJECTION_TYPE.RELATIONSHIP_INDEX]: "relationship-index.json",
113
+ [PROJECTION_TYPE.TYPED_RELATIONS]: "typed-relations.json",
108
114
  /** @deprecated No longer published. */
109
115
  [PROJECTION_TYPE.RUNTIME_CONFIG]: "runtime-config.json",
110
116
  [PROJECTION_TYPE.MANIFEST]: "manifest.json"
@@ -530,7 +536,10 @@ monotonicFactory();
530
536
  // ../../libs/metadata/src/services/metadata-change-request.service.ts
531
537
  monotonicFactory();
532
538
  z.object({
533
- /** When true, inactive values are included; default false (ACTIVE only for latest filter). */
539
+ /**
540
+ * When true, a latest INACTIVE version is projected. Default false: the latest
541
+ * version must be ACTIVE, and an older ACTIVE version is not used instead.
542
+ */
534
543
  includeInactive: z.boolean().optional(),
535
544
  /**
536
545
  * When true, every published version of a value is retained under `versions`.
@@ -604,19 +613,80 @@ var ProjectionHelper = class _ProjectionHelper {
604
613
  }
605
614
  }
606
615
  /**
607
- * Filter values to those included in the projection.
608
- * Always excludes DELETED. When includeInactive is false, only ACTIVE.
616
+ * Row filter. Always excludes DELETED. When includeInactive is false, only ACTIVE.
617
+ *
618
+ * Does not apply latest-version rules. Callers that project a value code must use
619
+ * {@link selectProjectedValueVersions} so an older ACTIVE version cannot outrank
620
+ * a newer INACTIVE or DELETED version.
609
621
  */
610
622
  static filterValues(values, includeInactive) {
611
- return values.filter((value) => {
612
- if (value.status === STATUS.DELETED) {
613
- return false;
623
+ return values.filter(
624
+ (value) => _ProjectionHelper.isProjectableStatus(value.status, includeInactive)
625
+ );
626
+ }
627
+ /**
628
+ * Highest version of each type+code. Equal versions keep the first row.
629
+ */
630
+ static latestValueByCode(values) {
631
+ const latest = /* @__PURE__ */ new Map();
632
+ for (const value of values) {
633
+ const key = _ProjectionHelper.relationFromKey(
634
+ value.metadataTypeCode,
635
+ value.valueCode
636
+ );
637
+ const current = latest.get(key);
638
+ if (!current || value.version > current.version) {
639
+ latest.set(key, value);
640
+ }
641
+ }
642
+ return latest;
643
+ }
644
+ /**
645
+ * Versions to write for each value code.
646
+ *
647
+ * The highest version decides. A latest INACTIVE version is omitted when
648
+ * `includeInactive` is false, and a latest DELETED version is always omitted.
649
+ * Older ACTIVE versions of that code are not projected in their place.
650
+ * When `includeAllVersions` is false, only that latest version is kept.
651
+ */
652
+ static selectProjectedValueVersions(values, includeInactive, includeAllVersions) {
653
+ const latestByCode = _ProjectionHelper.latestValueByCode(values);
654
+ const grouped = /* @__PURE__ */ new Map();
655
+ for (const value of values) {
656
+ const key = _ProjectionHelper.relationFromKey(
657
+ value.metadataTypeCode,
658
+ value.valueCode
659
+ );
660
+ const list = grouped.get(key) ?? [];
661
+ list.push(value);
662
+ grouped.set(key, list);
663
+ }
664
+ const selected = [];
665
+ for (const [key, versions] of grouped) {
666
+ const latest = latestByCode.get(key);
667
+ if (!latest || !_ProjectionHelper.isProjectableStatus(latest.status, includeInactive)) {
668
+ continue;
614
669
  }
615
- if (includeInactive) {
616
- return value.status === STATUS.ACTIVE || value.status === STATUS.INACTIVE;
670
+ if (!includeAllVersions) {
671
+ selected.push(latest);
672
+ continue;
617
673
  }
618
- return value.status === STATUS.ACTIVE;
619
- });
674
+ for (const version of versions) {
675
+ if (_ProjectionHelper.isProjectableStatus(version.status, includeInactive)) {
676
+ selected.push(version);
677
+ }
678
+ }
679
+ }
680
+ return selected;
681
+ }
682
+ static isProjectableStatus(status, includeInactive) {
683
+ if (status === STATUS.DELETED) {
684
+ return false;
685
+ }
686
+ if (status === STATUS.INACTIVE) {
687
+ return includeInactive;
688
+ }
689
+ return status === STATUS.ACTIVE;
620
690
  }
621
691
  /**
622
692
  * Filter relations to ACTIVE only.
@@ -786,9 +856,10 @@ var ProjectionHelper = class _ProjectionHelper {
786
856
  * Shared by {@link GenericReadModelGenerator} — type-agnostic transform.
787
857
  */
788
858
  static buildDomainProjectionRecords(input) {
789
- const filtered = _ProjectionHelper.filterValues(
859
+ const filtered = _ProjectionHelper.selectProjectedValueVersions(
790
860
  input.values,
791
- input.includeInactive
861
+ input.includeInactive,
862
+ input.includeAllVersions === true
792
863
  );
793
864
  const entries = filtered.map((value) => {
794
865
  const fromKey = _ProjectionHelper.relationFromKey(
@@ -800,14 +871,53 @@ var ProjectionHelper = class _ProjectionHelper {
800
871
  });
801
872
  const records = _ProjectionHelper.buildRecordsMap(entries);
802
873
  if (input.includeAllVersions === false) {
803
- for (const record of Object.values(records)) {
804
- const latest = record.versions[String(record.latestVersion)];
805
- record.versions = latest ? { [String(record.latestVersion)]: latest } : {};
806
- }
874
+ _ProjectionHelper.keepLatestVersionOnly(records);
807
875
  }
876
+ const inactiveRecords = _ProjectionHelper.buildInactiveRecords(
877
+ input,
878
+ records
879
+ );
808
880
  const metadataCount = _ProjectionHelper.countVersions(records);
809
- const contentHash = _ProjectionHelper.contentHash(records);
810
- return { records, metadataCount, contentHash };
881
+ const contentHash = Object.keys(inactiveRecords).length > 0 ? _ProjectionHelper.contentHash({ records, inactiveRecords }) : _ProjectionHelper.contentHash(records);
882
+ return { records, inactiveRecords, metadataCount, contentHash };
883
+ }
884
+ /**
885
+ * Latest INACTIVE versions that are not already in the active `records` map.
886
+ * Empty when the caller already projected inactive values into `records`.
887
+ */
888
+ static buildInactiveRecords(input, activeRecords) {
889
+ if (input.includeInactive) {
890
+ return {};
891
+ }
892
+ const selected = _ProjectionHelper.selectProjectedValueVersions(
893
+ input.values,
894
+ true,
895
+ input.includeAllVersions === true
896
+ ).filter((value) => value.status === STATUS.INACTIVE);
897
+ const entries = selected.map((value) => {
898
+ const fromKey = _ProjectionHelper.relationFromKey(
899
+ value.metadataTypeCode,
900
+ value.valueCode
901
+ );
902
+ const relations = input.relationsByFrom.get(fromKey) ?? [];
903
+ return _ProjectionHelper.toProjectionEntry(value, relations);
904
+ });
905
+ const inactiveRecords = _ProjectionHelper.buildRecordsMap(entries);
906
+ if (input.includeAllVersions === false) {
907
+ _ProjectionHelper.keepLatestVersionOnly(inactiveRecords);
908
+ }
909
+ for (const code of Object.keys(inactiveRecords)) {
910
+ if (activeRecords[code]) {
911
+ delete inactiveRecords[code];
912
+ }
913
+ }
914
+ return inactiveRecords;
915
+ }
916
+ static keepLatestVersionOnly(records) {
917
+ for (const record of Object.values(records)) {
918
+ const latest = record.versions[String(record.latestVersion)];
919
+ record.versions = latest ? { [String(record.latestVersion)]: latest } : {};
920
+ }
811
921
  }
812
922
  };
813
923
 
@@ -816,7 +926,8 @@ var RESERVED_PROJECTION_NAMES = [
816
926
  "common",
817
927
  "manifest",
818
928
  "runtimeConfig",
819
- "relationshipIndex"
929
+ "relationshipIndex",
930
+ "typedRelations"
820
931
  ];
821
932
  function assertUsableMetadataTypeCode(metadataTypeCode) {
822
933
  const trimmed = metadataTypeCode.trim();
@@ -1131,6 +1242,72 @@ var ProjectionPathBuilder = class {
1131
1242
  }
1132
1243
  }
1133
1244
  };
1245
+
1246
+ // ../../libs/metadata-projection/src/lib/generators/relationship-index/TypedRelationshipCatalog.ts
1247
+ function filterTypedRelations(relations, query) {
1248
+ return relations.filter((relation) => {
1249
+ if (relation.fromMetadataTypeCode !== query.fromType) {
1250
+ return false;
1251
+ }
1252
+ if (relation.fromMetadataValueCode !== query.fromValue) {
1253
+ return false;
1254
+ }
1255
+ if (query.relationType && relation.relationType !== query.relationType) {
1256
+ return false;
1257
+ }
1258
+ if (query.toType && relation.toMetadataTypeCode !== query.toType) {
1259
+ return false;
1260
+ }
1261
+ return true;
1262
+ });
1263
+ }
1264
+ function parseTypedRelationshipFile(parsed, expected) {
1265
+ const fileName = expected.fileName ?? "typed-relations.json";
1266
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1267
+ throw new Error(`${fileName} is not a JSON object`);
1268
+ }
1269
+ const record = parsed;
1270
+ if (record.releaseId !== expected.releaseId) {
1271
+ throw new Error(
1272
+ `${fileName} releaseId ${String(record.releaseId)} does not match ${expected.releaseId}`
1273
+ );
1274
+ }
1275
+ if (record.contentHash !== expected.contentHash) {
1276
+ throw new Error(`Checksum mismatch for ${fileName}`);
1277
+ }
1278
+ if (!Array.isArray(record.relations)) {
1279
+ throw new Error(`${fileName} relations must be an array`);
1280
+ }
1281
+ const relations = [];
1282
+ for (const row of record.relations) {
1283
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
1284
+ throw new Error(`${fileName} contains an invalid relation row`);
1285
+ }
1286
+ const item = row;
1287
+ if (typeof item.relationType !== "string" || typeof item.status !== "string" || typeof item.fromMetadataTypeCode !== "string" || typeof item.fromMetadataValueCode !== "string" || typeof item.toMetadataTypeCode !== "string" || typeof item.toMetadataValueCode !== "string") {
1288
+ throw new Error(`${fileName} contains an invalid relation row`);
1289
+ }
1290
+ const relation = {
1291
+ relationType: item.relationType,
1292
+ status: item.status,
1293
+ fromMetadataTypeCode: item.fromMetadataTypeCode,
1294
+ fromMetadataValueCode: item.fromMetadataValueCode,
1295
+ toMetadataTypeCode: item.toMetadataTypeCode,
1296
+ toMetadataValueCode: item.toMetadataValueCode
1297
+ };
1298
+ if (typeof item.moduleCode === "string") {
1299
+ relation.moduleCode = item.moduleCode;
1300
+ }
1301
+ if (typeof item.featureCode === "string") {
1302
+ relation.featureCode = item.featureCode;
1303
+ }
1304
+ if (typeof item.permissionActionCode === "string") {
1305
+ relation.permissionActionCode = item.permissionActionCode;
1306
+ }
1307
+ relations.push(relation);
1308
+ }
1309
+ return relations;
1310
+ }
1134
1311
  createLogger({ serviceName: "metadata-projection" });
1135
1312
  var metadataPublishedPayloadSchema = z.object({
1136
1313
  changeRequestId: z.string().min(1),
@@ -2110,10 +2287,14 @@ var MetadataDownloader = class {
2110
2287
  });
2111
2288
  try {
2112
2289
  const relationshipIndex = await this.downloadRelationshipIndex(manifest);
2290
+ const typedRelations = await this.downloadTypedRelations(manifest);
2113
2291
  const loadedFiles = relationshipIndex ? [
2114
2292
  manifestFileName,
2115
2293
  PROJECTION_FILE_NAME[PROJECTION_TYPE.RELATIONSHIP_INDEX]
2116
2294
  ] : [manifestFileName];
2295
+ if (typedRelations) {
2296
+ loadedFiles.push(PROJECTION_FILE_NAME[PROJECTION_TYPE.TYPED_RELATIONS]);
2297
+ }
2117
2298
  const localization = /* @__PURE__ */ new Map();
2118
2299
  if (manifest.localization?.files) {
2119
2300
  const localeEntries = Object.entries(manifest.localization.files);
@@ -2153,6 +2334,7 @@ var MetadataDownloader = class {
2153
2334
  manifest,
2154
2335
  domainFiles: /* @__PURE__ */ new Map(),
2155
2336
  relationshipIndex,
2337
+ typedRelations,
2156
2338
  loadedFiles: loadedFiles.sort((a, b) => a.localeCompare(b)),
2157
2339
  localization: localization.size > 0 ? localization : void 0,
2158
2340
  downloadedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -2297,6 +2479,66 @@ var MetadataDownloader = class {
2297
2479
  * Load `relationship-index.json` when listed in the manifest integrity catalog.
2298
2480
  * Missing/corrupt/mismatched artifacts fail closed — never activate an empty map.
2299
2481
  */
2482
+ /**
2483
+ * Download `common.json` for a release (type catalog: display name, value data type,
2484
+ * multi-select). Not part of bootstrap — published catalog APIs request it explicitly.
2485
+ */
2486
+ async downloadCommon(manifest) {
2487
+ const fileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.COMMON];
2488
+ const entry = manifest.files.find((file) => file.fileName === fileName);
2489
+ if (!entry) {
2490
+ throw new ProjectionDownloadError(
2491
+ "common.json is missing from the projection manifest",
2492
+ {
2493
+ retryable: false,
2494
+ metadata: { releaseId: manifest.releaseId, fileName }
2495
+ }
2496
+ );
2497
+ }
2498
+ const body = await this.getObjectBody(
2499
+ this.buildKey(manifest.releaseId, fileName)
2500
+ );
2501
+ return this.parseAndValidateProjectionBody(
2502
+ fileName,
2503
+ entry.contentHash,
2504
+ body,
2505
+ manifest.releaseId
2506
+ );
2507
+ }
2508
+ async downloadTypedRelations(manifest) {
2509
+ const fileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.TYPED_RELATIONS];
2510
+ const entry = manifest.files.find((file) => file.fileName === fileName);
2511
+ if (!entry) {
2512
+ return void 0;
2513
+ }
2514
+ const body = await this.getObjectBody(
2515
+ this.buildKey(manifest.releaseId, fileName)
2516
+ );
2517
+ let parsed;
2518
+ try {
2519
+ parsed = JSON.parse(body);
2520
+ } catch {
2521
+ throw new ProjectionDownloadError(`Corrupted JSON for ${fileName}`, {
2522
+ retryable: false,
2523
+ metadata: { fileName, releaseId: manifest.releaseId }
2524
+ });
2525
+ }
2526
+ try {
2527
+ return parseTypedRelationshipFile(parsed, {
2528
+ releaseId: manifest.releaseId,
2529
+ contentHash: entry.contentHash,
2530
+ fileName
2531
+ });
2532
+ } catch (err) {
2533
+ throw new ProjectionDownloadError(
2534
+ err instanceof Error ? err.message : `Invalid typed relations for ${fileName}`,
2535
+ {
2536
+ retryable: false,
2537
+ metadata: { fileName, releaseId: manifest.releaseId }
2538
+ }
2539
+ );
2540
+ }
2541
+ }
2300
2542
  async downloadRelationshipIndex(manifest) {
2301
2543
  const fileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.RELATIONSHIP_INDEX];
2302
2544
  const entry = manifest.files.find((f) => f.fileName === fileName);
@@ -2453,6 +2695,10 @@ var MetadataCache = class {
2453
2695
  getRelationshipIndex() {
2454
2696
  return this.snapshot?.relationshipIndex;
2455
2697
  }
2698
+ /** Undefined when the active release has no typed relation catalog. */
2699
+ getTypedRelations() {
2700
+ return this.snapshot?.typedRelations;
2701
+ }
2456
2702
  getLocalization(locale) {
2457
2703
  return this.snapshot?.localization?.get(locale);
2458
2704
  }
@@ -2495,6 +2741,7 @@ var MetadataCache = class {
2495
2741
  domainFiles,
2496
2742
  common: bundle.common ? Object.freeze({ ...bundle.common }) : void 0,
2497
2743
  relationshipIndex: bundle.relationshipIndex ? Object.freeze({ ...bundle.relationshipIndex }) : void 0,
2744
+ typedRelations: bundle.typedRelations ? Object.freeze([...bundle.typedRelations]) : void 0,
2498
2745
  manifest: Object.freeze({
2499
2746
  ...bundle.manifest,
2500
2747
  files: Object.freeze(
@@ -2517,6 +2764,38 @@ var MetadataCache = class {
2517
2764
  this.status = CACHE_STATUS.READY;
2518
2765
  return snapshot;
2519
2766
  }
2767
+ /**
2768
+ * Install `common.json` into the current snapshot (same release).
2769
+ * Used by published catalog reads. Does not mutate the prior snapshot.
2770
+ */
2771
+ mergeCommon(common, guard) {
2772
+ if (!this.snapshot) {
2773
+ throw new Error("Cannot merge common.json into an empty metadata cache");
2774
+ }
2775
+ if (!this.guardAllowsWrite(guard)) {
2776
+ return this.snapshot;
2777
+ }
2778
+ if (common.releaseId && common.releaseId !== this.snapshot.releaseId) {
2779
+ return this.snapshot;
2780
+ }
2781
+ const loadedFiles = Object.freeze(
2782
+ [
2783
+ .../* @__PURE__ */ new Set([
2784
+ ...this.snapshot.loadedFiles,
2785
+ PROJECTION_FILE_NAME[PROJECTION_TYPE.COMMON]
2786
+ ])
2787
+ ].sort((a, b) => a.localeCompare(b))
2788
+ );
2789
+ const snapshot = Object.freeze({
2790
+ ...this.snapshot,
2791
+ common: Object.freeze({ ...common }),
2792
+ loadedFiles,
2793
+ loadedAt: (/* @__PURE__ */ new Date()).toISOString()
2794
+ });
2795
+ this.snapshot = snapshot;
2796
+ this.status = CACHE_STATUS.READY;
2797
+ return snapshot;
2798
+ }
2520
2799
  /**
2521
2800
  * Merge additional domain projection files into the current snapshot (same revision).
2522
2801
  * Used by selective on-demand downloads — never mutates the prior snapshot.
@@ -2753,7 +3032,7 @@ var MetadataResolver = class {
2753
3032
  event: RUNTIME_METADATA_EVENTS.PROJECTION_PROVIDER_SUPPORTS_TYPE,
2754
3033
  requestedType,
2755
3034
  supported,
2756
- availableTypes,
3035
+ availableTypes: availableTypes.length,
2757
3036
  cacheStatus: this.cache.getStatus(),
2758
3037
  releaseId: this.cache.getReleaseId()
2759
3038
  });
@@ -3203,25 +3482,52 @@ var ExtensionMetadataProvider = class {
3203
3482
  }
3204
3483
  }
3205
3484
  async waitUntilReady() {
3485
+ const started = Date.now();
3206
3486
  const deadline = Date.now() + this.readyTimeoutMs;
3207
3487
  let lastError;
3488
+ let attempts = 0;
3208
3489
  while (Date.now() < deadline) {
3490
+ attempts += 1;
3209
3491
  try {
3210
3492
  const status = await this.getStatus();
3211
3493
  if (isServingState(status.state) && status.releaseId) {
3494
+ this.logger.info({
3495
+ event: "templates.performance",
3496
+ phase: "metadataExtension.ready",
3497
+ durationMs: Date.now() - started,
3498
+ attempts,
3499
+ state: status.state
3500
+ });
3212
3501
  return status;
3213
3502
  }
3503
+ if (status.lastError) {
3504
+ lastError = new Error(status.lastError);
3505
+ }
3506
+ if (status.state === "FAILED") {
3507
+ break;
3508
+ }
3214
3509
  } catch (err) {
3215
3510
  lastError = err;
3511
+ if (err instanceof MetadataProjectionUnavailableError && err.metadata?.unreachable === true) {
3512
+ break;
3513
+ }
3216
3514
  }
3217
3515
  await sleep(50);
3218
3516
  }
3517
+ const detail = lastError instanceof Error ? lastError.message : lastError ? String(lastError) : "";
3518
+ this.logger.warn({
3519
+ event: "templates.performance",
3520
+ phase: "metadataExtension.ready",
3521
+ durationMs: Date.now() - started,
3522
+ attempts,
3523
+ outcome: "unavailable"
3524
+ });
3219
3525
  throw new MetadataProjectionUnavailableError(
3220
- "Metadata extension did not become ready",
3526
+ detail ? `Metadata extension did not become ready: ${detail}` : "Metadata extension did not become ready",
3221
3527
  {
3222
3528
  retryable: true,
3223
3529
  metadata: {
3224
- lastError: lastError instanceof Error ? lastError.message : String(lastError ?? "")
3530
+ lastError: detail
3225
3531
  }
3226
3532
  }
3227
3533
  );
@@ -3234,6 +3540,7 @@ var ExtensionMetadataProvider = class {
3234
3540
  return {
3235
3541
  state: body.state ?? "UNKNOWN",
3236
3542
  releaseId: body.releaseId ?? null,
3543
+ lastError: body.lastError ?? null,
3237
3544
  loadedAt: body.loadedAt ?? null,
3238
3545
  lastRefreshAttemptAt: body.lastRefreshAttemptAt ?? null,
3239
3546
  lastSuccessfulRefreshAt: body.lastSuccessfulRefreshAt ?? null,
@@ -3315,6 +3622,59 @@ var ExtensionMetadataProvider = class {
3315
3622
  throw err;
3316
3623
  }
3317
3624
  }
3625
+ /**
3626
+ * Every published value for one metadata type.
3627
+ * GET /v1/metadata/{typeCode}. Unknown types are a projection miss (`null`).
3628
+ */
3629
+ async listTypeValues(typeCode, options) {
3630
+ const params = new URLSearchParams();
3631
+ if (options?.locale) {
3632
+ params.set("locale", options.locale);
3633
+ }
3634
+ if (options?.includeInactive) {
3635
+ params.set("includeInactive", "true");
3636
+ }
3637
+ const query = params.toString();
3638
+ const path = `/v1/metadata/${encodeURIComponent(typeCode)}${query ? `?${query}` : ""}`;
3639
+ try {
3640
+ const body = await this.requestJson("GET", path);
3641
+ const values = Object.values(body.items ?? {}).map((item) => this.toMetadataValue(item, options?.locale)).filter((item) => item != null);
3642
+ return {
3643
+ releaseId: body.releaseId ?? null,
3644
+ values,
3645
+ type: parseTypeCatalog(body.type, typeCode)
3646
+ };
3647
+ } catch (err) {
3648
+ if (isNotFound(err)) {
3649
+ return null;
3650
+ }
3651
+ throw err;
3652
+ }
3653
+ }
3654
+ async listRelations(query) {
3655
+ const params = new URLSearchParams();
3656
+ params.set("fromType", query.fromType);
3657
+ params.set("fromValue", query.fromValue);
3658
+ if (query.relationType) {
3659
+ params.set("relationType", query.relationType);
3660
+ }
3661
+ if (query.toType) {
3662
+ params.set("toType", query.toType);
3663
+ }
3664
+ try {
3665
+ const body = await this.requestJson("GET", `/v1/relations?${params.toString()}`);
3666
+ return {
3667
+ releaseId: body.releaseId ?? null,
3668
+ supported: body.supported === true,
3669
+ relations: Array.isArray(body.relations) ? body.relations : []
3670
+ };
3671
+ } catch (err) {
3672
+ if (isNotFound(err)) {
3673
+ return { releaseId: null, supported: false, relations: [] };
3674
+ }
3675
+ throw err;
3676
+ }
3677
+ }
3318
3678
  async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
3319
3679
  const localeQuery = options?.locale ? `?locale=${encodeURIComponent(options.locale)}` : "";
3320
3680
  const path = `/v1/related/${encodeURIComponent(sourceTypeCode)}/${encodeURIComponent(sourceValueCode)}/${encodeURIComponent(targetTypeCode)}${localeQuery}`;
@@ -3406,6 +3766,7 @@ var ExtensionMetadataProvider = class {
3406
3766
  };
3407
3767
  }
3408
3768
  async requestJson(method, path, payload) {
3769
+ const started = Date.now();
3409
3770
  const controller = new AbortController();
3410
3771
  const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
3411
3772
  try {
@@ -3413,6 +3774,7 @@ var ExtensionMetadataProvider = class {
3413
3774
  method,
3414
3775
  headers: {
3415
3776
  accept: "application/json",
3777
+ ...correlationHeaders(),
3416
3778
  ...payload !== void 0 ? { "content-type": "application/json" } : {}
3417
3779
  },
3418
3780
  body: payload !== void 0 ? JSON.stringify(payload) : void 0,
@@ -3459,17 +3821,41 @@ var ExtensionMetadataProvider = class {
3459
3821
  event: "runtimeMetadata.extension.requestFailed",
3460
3822
  path,
3461
3823
  aborted,
3462
- message: err instanceof Error ? err.message : String(err)
3824
+ errorMessage: err instanceof Error ? err.message : String(err)
3463
3825
  });
3464
3826
  throw new MetadataProjectionUnavailableError(
3465
3827
  aborted ? "Metadata extension request timed out" : "Metadata extension is unavailable",
3466
- { retryable: true, metadata: { path } }
3828
+ {
3829
+ retryable: true,
3830
+ metadata: { path, unreachable: !aborted, durationMs: Date.now() - started }
3831
+ }
3467
3832
  );
3468
3833
  } finally {
3469
3834
  clearTimeout(timer);
3470
3835
  }
3471
3836
  }
3472
3837
  };
3838
+ function parseTypeCatalog(raw, fallbackTypeCode) {
3839
+ if (!raw || typeof raw !== "object") {
3840
+ return null;
3841
+ }
3842
+ if (typeof raw.displayName !== "string" || typeof raw.valueDataType !== "string") {
3843
+ return null;
3844
+ }
3845
+ if (typeof raw.multiSelectAllowed !== "boolean") {
3846
+ return null;
3847
+ }
3848
+ const metadataType = typeof raw.metadataType === "string" && raw.metadataType.trim() ? raw.metadataType : fallbackTypeCode;
3849
+ return {
3850
+ metadataType,
3851
+ displayName: raw.displayName,
3852
+ valueDataType: raw.valueDataType,
3853
+ multiSelectAllowed: raw.multiSelectAllowed,
3854
+ status: typeof raw.status === "string" ? raw.status : "",
3855
+ ...typeof raw.required === "boolean" ? { required: raw.required } : {},
3856
+ ...typeof raw.isGlobal === "boolean" ? { isGlobal: raw.isGlobal } : {}
3857
+ };
3858
+ }
3473
3859
  function isNotFound(err) {
3474
3860
  return err.code === "RUNTIME_METADATA_NOT_FOUND";
3475
3861
  }
@@ -3479,6 +3865,13 @@ function isUnavailable(err) {
3479
3865
  function isServingState(state) {
3480
3866
  return state === "READY" || state === "STALE" || state === "DEGRADED";
3481
3867
  }
3868
+ function correlationHeaders() {
3869
+ const correlationId = getContext().correlationId;
3870
+ if (!correlationId || correlationId === "unknown") {
3871
+ return {};
3872
+ }
3873
+ return { "x-correlation-id": correlationId };
3874
+ }
3482
3875
  function sleep(ms) {
3483
3876
  return new Promise((resolve) => setTimeout(resolve, ms));
3484
3877
  }
@@ -3785,6 +4178,21 @@ var S3MetadataProvider = class {
3785
4178
  unavailable: !this.cache.isReady() && parsedRefs.length > 0
3786
4179
  };
3787
4180
  }
4181
+ async listRelations(query) {
4182
+ const relations = this.cache.getTypedRelations();
4183
+ if (!relations) {
4184
+ return {
4185
+ releaseId: this.cache.getReleaseId(),
4186
+ supported: false,
4187
+ relations: []
4188
+ };
4189
+ }
4190
+ return {
4191
+ releaseId: this.cache.getReleaseId(),
4192
+ supported: true,
4193
+ relations: filterTypedRelations(relations, query)
4194
+ };
4195
+ }
3788
4196
  async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
3789
4197
  await this.ensureTypesLoaded([sourceTypeCode, targetTypeCode]);
3790
4198
  const index = this.cache.getRelationshipIndex();
@@ -3819,6 +4227,36 @@ var S3MetadataProvider = class {
3819
4227
  });
3820
4228
  return values;
3821
4229
  }
4230
+ async listTypeValues(typeCode, options) {
4231
+ await this.ensureTypesLoaded([typeCode]);
4232
+ const file = this.cache.getDomainFile(typeCode);
4233
+ if (!file) {
4234
+ return null;
4235
+ }
4236
+ const values = this.resolver.getAll(typeCode).map(
4237
+ (entry) => projectionEntryToMetadataValue(typeCode, entry.code, entry, options?.locale)
4238
+ );
4239
+ if (options?.includeInactive && file.inactiveRecords) {
4240
+ const seen = new Set(values.map((value) => value.valueCode));
4241
+ for (const [valueCode, record] of Object.entries(file.inactiveRecords)) {
4242
+ if (seen.has(valueCode)) {
4243
+ continue;
4244
+ }
4245
+ const entry = latestProjectionEntry(record);
4246
+ if (!entry) {
4247
+ continue;
4248
+ }
4249
+ values.push(
4250
+ projectionEntryToMetadataValue(typeCode, valueCode, entry, options.locale)
4251
+ );
4252
+ }
4253
+ }
4254
+ return {
4255
+ releaseId: this.cache.getReleaseId(),
4256
+ values,
4257
+ type: typeCatalogFromProjection(typeCode, file, this.cache.getCommon())
4258
+ };
4259
+ }
3822
4260
  };
3823
4261
  function relatedValueCodes(index, sourceTypeCode, sourceValueCode, targetTypeCode) {
3824
4262
  if (!index) {
@@ -3828,6 +4266,36 @@ function relatedValueCodes(index, sourceTypeCode, sourceValueCode, targetTypeCod
3828
4266
  const values = index[key]?.[targetTypeCode];
3829
4267
  return values ? [...values] : [];
3830
4268
  }
4269
+ function typeCatalogFromProjection(typeCode, file, common) {
4270
+ const fromCommon = common?.types.find(
4271
+ (type) => type.metadataTypeCode === typeCode
4272
+ );
4273
+ if (fromCommon && typeof fromCommon.displayName === "string" && fromCommon.displayName.trim() && typeof fromCommon.valueDataType === "string" && typeof fromCommon.multiSelectAllowed === "boolean") {
4274
+ return {
4275
+ metadataType: fromCommon.metadataTypeCode,
4276
+ displayName: fromCommon.displayName,
4277
+ valueDataType: fromCommon.valueDataType,
4278
+ multiSelectAllowed: fromCommon.multiSelectAllowed,
4279
+ status: typeof fromCommon.status === "string" ? fromCommon.status : "",
4280
+ ...typeof fromCommon.required === "boolean" ? { required: fromCommon.required } : {},
4281
+ ...typeof fromCommon.isGlobal === "boolean" ? { isGlobal: fromCommon.isGlobal } : {}
4282
+ };
4283
+ }
4284
+ const displayName = file.localizedDisplayName?.["en-US"]?.trim();
4285
+ if (!displayName || typeof file.valueDataType !== "string" || typeof file.multiSelectAllowed !== "boolean") {
4286
+ return null;
4287
+ }
4288
+ return {
4289
+ metadataType: typeCode,
4290
+ displayName,
4291
+ valueDataType: file.valueDataType,
4292
+ multiSelectAllowed: file.multiSelectAllowed,
4293
+ status: ""
4294
+ };
4295
+ }
4296
+ function latestProjectionEntry(record) {
4297
+ return record.versions[String(record.latestVersion)];
4298
+ }
3831
4299
  function relatedValueCodesFromEntry(resolver, sourceTypeCode, sourceValueCode, targetTypeCode) {
3832
4300
  try {
3833
4301
  const entry = resolver.resolve(sourceTypeCode, sourceValueCode);
@@ -3855,6 +4323,8 @@ var RuntimeMetadataService = class {
3855
4323
  * for the lifetime of the Lambda execution context.
3856
4324
  */
3857
4325
  domainLoadInFlight = /* @__PURE__ */ new Map();
4326
+ /** Coalesce concurrent common.json downloads for the current release. */
4327
+ commonLoadInFlight = null;
3858
4328
  /**
3859
4329
  * Types soft-skipped for the current release (no manifest integrity entry).
3860
4330
  * Prevents ensureProjectionTypesLoaded from retrying unsupported types forever.
@@ -4147,6 +4617,65 @@ var RuntimeMetadataService = class {
4147
4617
  await batchPromise;
4148
4618
  }
4149
4619
  }
4620
+ /**
4621
+ * Ensure `common.json` is cached for the active release.
4622
+ * Published catalog reads use it for type display name, value data type, and multi-select.
4623
+ */
4624
+ async ensureCommonLoaded() {
4625
+ if (!this.cache.isReady()) {
4626
+ await this.initialize();
4627
+ }
4628
+ for (let attempt = 0; attempt < 3; attempt += 1) {
4629
+ const releaseId = this.cache.getReleaseId();
4630
+ const cached = this.cache.getCommon();
4631
+ if (cached && cached.releaseId === releaseId) {
4632
+ return cached;
4633
+ }
4634
+ if (!this.commonLoadInFlight) {
4635
+ const generation = this.cache.getGeneration();
4636
+ this.commonLoadInFlight = this.downloadAndMergeCommon(
4637
+ releaseId,
4638
+ generation
4639
+ ).finally(() => {
4640
+ this.commonLoadInFlight = null;
4641
+ });
4642
+ }
4643
+ await this.commonLoadInFlight;
4644
+ }
4645
+ const common = this.cache.getCommon();
4646
+ if (common && common.releaseId === this.cache.getReleaseId()) {
4647
+ return common;
4648
+ }
4649
+ throw new ProjectionDownloadError(
4650
+ "common.json was not installed in the metadata cache",
4651
+ {
4652
+ retryable: true,
4653
+ metadata: { releaseId: this.cache.getReleaseId() }
4654
+ }
4655
+ );
4656
+ }
4657
+ getRelationshipIndex() {
4658
+ return this.cache.getRelationshipIndex();
4659
+ }
4660
+ async downloadAndMergeCommon(expectedReleaseId, expectedGeneration) {
4661
+ const manifest = this.cache.getManifest();
4662
+ if (!manifest) {
4663
+ throw new ProjectionDownloadError("Projection manifest is not loaded", {
4664
+ retryable: true
4665
+ });
4666
+ }
4667
+ if (expectedReleaseId && (manifest.releaseId !== expectedReleaseId || this.cache.getGeneration() !== expectedGeneration)) {
4668
+ return;
4669
+ }
4670
+ const common = await this.downloader.downloadCommon(manifest);
4671
+ if (expectedReleaseId && (this.cache.getReleaseId() !== expectedReleaseId || this.cache.getGeneration() !== expectedGeneration)) {
4672
+ return;
4673
+ }
4674
+ this.cache.mergeCommon(common, {
4675
+ releaseId: manifest.releaseId,
4676
+ generation: expectedGeneration
4677
+ });
4678
+ }
4150
4679
  syncUnsupportedProjectionRelease(releaseId) {
4151
4680
  const id = releaseId ?? null;
4152
4681
  if (this.unsupportedProjectionReleaseId !== id) {
@@ -4357,6 +4886,41 @@ var RuntimeMetadataService = class {
4357
4886
  throw err;
4358
4887
  }
4359
4888
  }
4889
+ async listRelations(query) {
4890
+ try {
4891
+ const provider = await this.activeProvider();
4892
+ const listed = await provider.listRelations(query);
4893
+ if (!listed.supported && this.metadataProviderFallback && provider !== this.metadataProviderFallback) {
4894
+ return this.metadataProviderFallback.listRelations(query);
4895
+ }
4896
+ return listed;
4897
+ } catch (err) {
4898
+ if (await this.tryActivateFallbackFromError(err, "extension-relations")) {
4899
+ const fallback = this.metadataProviderFallback;
4900
+ if (fallback) {
4901
+ return fallback.listRelations(query);
4902
+ }
4903
+ }
4904
+ throw err;
4905
+ }
4906
+ }
4907
+ async listTypeValues(typeCode, options) {
4908
+ try {
4909
+ const provider = await this.activeProvider();
4910
+ const guard = this.currentWriteGuard();
4911
+ const listed = await provider.listTypeValues(typeCode, options);
4912
+ this.hydrateProviderValues(listed?.values ?? [], guard);
4913
+ return listed;
4914
+ } catch (err) {
4915
+ if (await this.tryActivateFallbackFromError(err, "extension-list")) {
4916
+ const fallback = this.metadataProviderFallback;
4917
+ if (fallback) {
4918
+ return fallback.listTypeValues(typeCode, options);
4919
+ }
4920
+ }
4921
+ throw err;
4922
+ }
4923
+ }
4360
4924
  getActiveProviderKind() {
4361
4925
  return this.providerCoordinator.getActiveKind();
4362
4926
  }
@@ -4644,9 +5208,11 @@ var InMemoryMetadataProvider = class {
4644
5208
  forcedState;
4645
5209
  byKey = /* @__PURE__ */ new Map();
4646
5210
  related = /* @__PURE__ */ new Map();
5211
+ relations;
4647
5212
  constructor(options = {}) {
4648
5213
  this.releaseId = options.releaseId ?? "memory";
4649
5214
  this.unavailable = options.unavailable === true;
5215
+ this.relations = options.relations;
4650
5216
  for (const record of options.records ?? []) {
4651
5217
  const key = formatMetadataReference(record.typeCode, record.valueCode);
4652
5218
  this.byKey.set(key, record);
@@ -4768,6 +5334,22 @@ var InMemoryMetadataProvider = class {
4768
5334
  unavailable: false
4769
5335
  };
4770
5336
  }
5337
+ async listRelations(query) {
5338
+ if (this.unavailable) {
5339
+ throw new MetadataProjectionUnavailableError(
5340
+ "In-memory metadata provider is unavailable",
5341
+ { retryable: true }
5342
+ );
5343
+ }
5344
+ if (!this.relations) {
5345
+ return { releaseId: this.releaseId, supported: false, relations: [] };
5346
+ }
5347
+ return {
5348
+ releaseId: this.releaseId,
5349
+ supported: true,
5350
+ relations: filterTypedRelations(this.relations, query)
5351
+ };
5352
+ }
4771
5353
  async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
4772
5354
  if (this.unavailable) {
4773
5355
  throw new MetadataProjectionUnavailableError(
@@ -4786,6 +5368,32 @@ var InMemoryMetadataProvider = class {
4786
5368
  }
4787
5369
  return values;
4788
5370
  }
5371
+ async listTypeValues(typeCode, options) {
5372
+ if (this.unavailable) {
5373
+ throw new MetadataProjectionUnavailableError(
5374
+ "In-memory metadata provider is unavailable",
5375
+ { retryable: true }
5376
+ );
5377
+ }
5378
+ const values = [];
5379
+ for (const record of this.byKey.values()) {
5380
+ if (record.typeCode !== typeCode) {
5381
+ continue;
5382
+ }
5383
+ const value = await this.getValue(record.typeCode, record.valueCode, options);
5384
+ if (value) {
5385
+ values.push(value);
5386
+ }
5387
+ }
5388
+ if (values.length === 0) {
5389
+ return null;
5390
+ }
5391
+ return {
5392
+ releaseId: this.releaseId,
5393
+ values,
5394
+ type: null
5395
+ };
5396
+ }
4789
5397
  };
4790
5398
 
4791
5399
  export { CACHE_STATUS, DEFAULT_EXCLUDED_CODE_FIELDS, DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS, ExtensionMetadataProvider, InMemoryMetadataProvider, InvalidMetadataReferenceError, METADATA_PROJECTIONS_BUCKET_ENV, METADATA_PROVIDER_KIND, ManifestValidationError, MetadataCache, MetadataDownloader, MetadataHealthService, MetadataLoader, MetadataLookupError, MetadataNotReadyError, MetadataProjectionUnavailableError, MetadataRefreshService, MetadataResolver, NON_METADATA_KEYS, PROVIDER_TRANSPORT_STATE, ProjectionDownloadError, ProviderFailoverCoordinator, REFRESH_STATUS, RUNTIME_METADATA_EVENTS, RUNTIME_METADATA_INTEGRATION_TARGETS, RUNTIME_METADATA_TYPE_CODE_ALIASES, RuntimeMetadataError, RuntimeMetadataService, S3MetadataProvider, UnknownMetadataTypeError, WORKFLOW_STEP_RULE_KEYS, canonicalMetadataProjectionsBucketName, collectResponseReferences, collectResponseTypeCodes, createCodeFieldExclusionSet, createRuntimeMetadataFromEnv, defaultExtensionBaseUrl, ensureRuntimeMetadataLoaded, formatMetadataReference, getCandidateTypeCodesForKey, getRuntimeMetadataHealth, getRuntimeMetadataService, hasPotentialMetadata, isCompactMetadataReference, isExtensionEnabled, isExtensionServing, isMetadataProjectionConfigured, isMetadataProjectionsBucketConfigured, isMetadataReference, isMetadataValueObject, isMetadataValueObjectArray, isWorkflowStepRecord, isWorkflowStepRuleField, localizedLabelFromEntry, manifestLocalizationSchema, metadataGroupFromManifest, metadataValueToReference, normalizeRuntimeMetadataTypeCode, onMetadataProjectionCompleted, parseMetadataReference, projectionEntryToMetadataValue, projectionManifestSchema, readMetadataProjectionsBucket, readModelGroupsFromManifest, relatedValueCodes, resetRuntimeMetadataBootstrapState, resolveMetadataProjectionsBucket, resolveRuntimeMetadataConfig, runtimeMetadataConfigSchema, selectMetadataProvider, tryGetRuntimeMetadataService, tryParseMetadataReference, typeCodeFromCodeFieldName };