@myvitalrx/metadata-runtime 1.14.0 → 1.17.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
@@ -1,9 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
3
- import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
4
- import crypto, { createHash } from 'crypto';
5
- import { AsyncLocalStorage } from 'async_hooks';
6
- import { Logger } from '@aws-lambda-powertools/logger';
2
+ import { createHash } from 'crypto';
3
+ import { createLogger, createOperationalLogger, createPerformanceTimer, getContext } from '@api-hub/observability';
7
4
  import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
8
5
 
9
6
  // ../../libs/runtime-metadata/src/lib/constants/RuntimeMetadataConstants.ts
@@ -32,6 +29,10 @@ var RUNTIME_METADATA_EVENTS = {
32
29
  DOWNLOAD_COMPLETE: "runtimeMetadata.download.complete",
33
30
  DOWNLOAD_FAILED: "runtimeMetadata.download.failed",
34
31
  MANIFEST_LOADED: "runtimeMetadata.manifest.loaded",
32
+ /** Runtime cache received a release catalog (extension status or S3 manifest). */
33
+ METADATA_MANIFEST_LOADED: "metadata.manifest.loaded",
34
+ /** supportsType decision against the published type catalog. */
35
+ METADATA_TYPE_CHECK: "metadata.type.check",
35
36
  /** Authoritative keys after manifest parse (metadataTypes + lookupIndex type prefixes). */
36
37
  PROJECTION_MANIFEST_LOADED: "projection.manifest.loaded",
37
38
  /** Per-file download begin. */
@@ -121,6 +122,7 @@ var PROJECTION_FILE_NAME = {
121
122
  [PROJECTION_TYPE.LANGUAGE]: "Language.json",
122
123
  [PROJECTION_TYPE.COMMON]: "common.json",
123
124
  [PROJECTION_TYPE.RELATIONSHIP_INDEX]: "relationship-index.json",
125
+ /** Type-relationship catalog: relation types and published relationship rows. */
124
126
  [PROJECTION_TYPE.TYPED_RELATIONS]: "typed-relations.json",
125
127
  [PROJECTION_TYPE.PERMISSION_REGISTRY]: PERMISSION_REGISTRY_FILE_NAME,
126
128
  /** @deprecated No longer published. */
@@ -137,25 +139,13 @@ var PROJECTION_STATUS = {
137
139
  function lookupIndexKey(typeCode, valueCode) {
138
140
  return `${typeCode}:${valueCode}`;
139
141
  }
142
+
143
+ // ../../libs/metadata/src/constants/index.ts
140
144
  var STATUS = {
141
145
  ACTIVE: "ACTIVE",
142
146
  INACTIVE: "INACTIVE",
143
147
  DELETED: "DELETED"
144
148
  };
145
- var region = process.env.DEFAULT_REGION || process.env.DP_REGION || "us-east-1";
146
- var config = {
147
- region
148
- };
149
- var ddbClient = new DynamoDBClient(config);
150
- DynamoDBDocumentClient.from(ddbClient, {
151
- marshallOptions: {
152
- removeUndefinedValues: true,
153
- convertClassInstanceToMap: true
154
- },
155
- unmarshallOptions: {
156
- wrapNumbers: false
157
- }
158
- });
159
149
 
160
150
  // ../../libs/utils/src/helper/object.helpers.ts
161
151
  function stableStringify(value) {
@@ -190,341 +180,6 @@ function sha256Hex(data) {
190
180
  return createHash("sha256").update(data).digest("hex");
191
181
  }
192
182
 
193
- // ../../libs/observability/src/config/config.ts
194
- var LEVEL_TO_FLOOR = {
195
- DEBUG: 10,
196
- INFO: 20,
197
- WARN: 30,
198
- ERROR: 40
199
- };
200
- function clamp01(n) {
201
- if (Number.isNaN(n) || n < 0) return 0;
202
- if (n > 1) return 1;
203
- return n;
204
- }
205
- function normalizeLogLevel(value) {
206
- const u = (value ?? "").toUpperCase();
207
- if (u === "DEBUG" || u === "WARN" || u === "ERROR" || u === "INFO") {
208
- return u;
209
- }
210
- return "ERROR";
211
- }
212
- function getDefaultInput() {
213
- return {
214
- serviceName: process.env.SERVICE_NAME ?? "unknown-service",
215
- logLevel: normalizeLogLevel(process.env.LOG_LEVEL),
216
- sampling: {
217
- info: Number(process.env.LOG_SAMPLE_INFO ?? 1),
218
- debug: Number(process.env.LOG_SAMPLE_DEBUG ?? 0.01)
219
- },
220
- redactPII: process.env.REDACT_PII !== "false",
221
- enforceLogPolicy: true,
222
- metricsNamespace: process.env.METRICS_NAMESPACE ?? "ApiHub",
223
- logPolicyViolationsToStderr: process.env.LOG_POLICY_STDERR === "true"
224
- };
225
- }
226
- function resolveConfig(input) {
227
- const logLevel = normalizeLogLevel(input.logLevel);
228
- const sampling = input.sampling ?? {};
229
- return {
230
- serviceName: input.serviceName ?? "unknown-service",
231
- logLevel,
232
- logLevelFloor: LEVEL_TO_FLOOR[logLevel],
233
- sampling: {
234
- info: clamp01(sampling.info ?? 1),
235
- debug: clamp01(sampling.debug ?? 0.01)
236
- },
237
- redactPII: input.redactPII ?? true,
238
- enforceLogPolicy: input.enforceLogPolicy ?? true,
239
- metricsNamespace: input.metricsNamespace ?? "ApiHub",
240
- logPolicyViolationsToStderr: input.logPolicyViolationsToStderr ?? false
241
- };
242
- }
243
- var overrideInput = {};
244
- var resolved = null;
245
- function configureObservability(input) {
246
- overrideInput = {
247
- ...overrideInput,
248
- ...input
249
- };
250
- resolved = null;
251
- }
252
- function getConfig() {
253
- if (!resolved) {
254
- const base = getDefaultInput();
255
- const merged = {
256
- ...base,
257
- ...overrideInput,
258
- sampling: {
259
- ...base.sampling,
260
- ...overrideInput.sampling
261
- }
262
- };
263
- resolved = resolveConfig(merged);
264
- }
265
- return resolved;
266
- }
267
- var store = new AsyncLocalStorage();
268
- var getContext = () => {
269
- return store.getStore() ?? { correlationId: "unknown" };
270
- };
271
- var baseLogger;
272
- function getBaseLogger() {
273
- if (!baseLogger) {
274
- baseLogger = new Logger({
275
- serviceName: process.env.SERVICE_NAME || "unknown-service",
276
- logLevel: process.env.LOG_LEVEL || "ERROR"
277
- });
278
- }
279
- return baseLogger;
280
- }
281
-
282
- // ../../libs/observability/src/logger/level-sampling.ts
283
- function shouldSample(level) {
284
- const cfg = getConfig();
285
- if (level === "INFO") {
286
- return Math.random() < cfg.sampling.info;
287
- }
288
- if (level === "DEBUG") {
289
- return Math.random() < cfg.sampling.debug;
290
- }
291
- return true;
292
- }
293
-
294
- // ../../libs/observability/src/core/pii.ts
295
- var KEY_REDACT = /* @__PURE__ */ new Set([
296
- "password",
297
- "email",
298
- "phone",
299
- "token",
300
- "authorization",
301
- "cookie",
302
- "set-cookie"
303
- ]);
304
- var EMAIL_RE = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
305
- var PHONE_RE = /(?:\+?\d{1,3}[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?){2}\d{4}/g;
306
- var JWT_LIKE_RE = /eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g;
307
- var BEARER_RE = /Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi;
308
- var toLowerKey = (value) => value.toLowerCase();
309
- function redactStringPattern(value) {
310
- let out = value;
311
- out = out.replace(EMAIL_RE, "[REDACTED_EMAIL]");
312
- out = out.replace(BEARER_RE, "Bearer [REDACTED]");
313
- out = out.replace(JWT_LIKE_RE, "[REDACTED_TOKEN]");
314
- out = out.replace(PHONE_RE, "[REDACTED_PHONE]");
315
- return out;
316
- }
317
- function redactPiiValue(data, _config) {
318
- if (Array.isArray(data)) {
319
- return data.map((item) => redactPiiValue(item));
320
- }
321
- if (typeof data === "string") {
322
- return redactStringPattern(data);
323
- }
324
- if (typeof data !== "object" || data === null) {
325
- return data;
326
- }
327
- const output = {};
328
- for (const [key, value] of Object.entries(data)) {
329
- if (KEY_REDACT.has(toLowerKey(key))) {
330
- output[key] = "[REDACTED]";
331
- continue;
332
- }
333
- if (typeof value === "string") {
334
- output[key] = redactStringPattern(value);
335
- } else {
336
- output[key] = redactPiiValue(value);
337
- }
338
- }
339
- return output;
340
- }
341
-
342
- // ../../libs/observability/src/logger/controlled-logging.ts
343
- function enforcePolicy(payload) {
344
- if (!payload || typeof payload !== "object") return payload;
345
- const cfg = getConfig();
346
- let cloned = { ...payload };
347
- if ("request" in cloned) cloned.request = "[BLOCKED]";
348
- if ("response" in cloned) cloned.response = "[BLOCKED]";
349
- if (cfg.redactPII) {
350
- cloned = redactPiiValue(cloned);
351
- }
352
- return cloned;
353
- }
354
-
355
- // ../../libs/observability/src/core/utils.ts
356
- var safeStringify = (value) => {
357
- const visited = /* @__PURE__ */ new WeakSet();
358
- return JSON.stringify(value, (_key, current) => {
359
- if (typeof current === "object" && current !== null) {
360
- if (visited.has(current)) {
361
- return "[Circular]";
362
- }
363
- visited.add(current);
364
- }
365
- return current;
366
- });
367
- };
368
- var safeParse = (value) => {
369
- const serialized = safeStringify(value);
370
- return JSON.parse(serialized);
371
- };
372
-
373
- // ../../libs/observability/src/logger/serialize-error.ts
374
- function isErrorLike(error) {
375
- if (error instanceof Error) {
376
- return true;
377
- }
378
- if (typeof error !== "object" || error === null) {
379
- return false;
380
- }
381
- const candidate = error;
382
- return typeof candidate.message === "string";
383
- }
384
- function serializeErrorLike(error) {
385
- return {
386
- name: error.name ?? "Error",
387
- message: error.message,
388
- ...error.stack ? { stack: error.stack } : {},
389
- ...typeof error.code === "string" ? { code: error.code } : {},
390
- ...typeof error.statusCode === "number" ? { statusCode: error.statusCode } : {},
391
- ...error.details !== void 0 ? { details: safeParse(error.details) } : {},
392
- ...error.cause !== void 0 ? { cause: safeParse(error.cause) } : {}
393
- };
394
- }
395
- function serializeError(error) {
396
- if (isErrorLike(error)) {
397
- return serializeErrorLike(error);
398
- }
399
- if (typeof error === "object" && error !== null) {
400
- return {
401
- name: "SerializedUnknownRejection",
402
- message: "Non-Error value logged",
403
- value: safeParse(error)
404
- };
405
- }
406
- return {
407
- name: "UnknownError",
408
- message: String(error)
409
- };
410
- }
411
-
412
- // ../../libs/observability/src/logger/logger.ts
413
- function getLogger(extra) {
414
- const base = getBaseLogger();
415
- const ctx = getContext();
416
- const child = base.createChild();
417
- child.appendKeys({
418
- ...ctx,
419
- ...extra,
420
- correlationId: ctx.correlationId,
421
- awsRequestId: ctx.awsRequestId,
422
- functionName: ctx.functionName
423
- });
424
- return {
425
- debug: (msg, payload) => {
426
- if (shouldSample("DEBUG")) {
427
- child.debug(msg, enforcePolicy(payload));
428
- }
429
- },
430
- info: (msg, payload) => {
431
- if (shouldSample("INFO")) {
432
- child.info(msg, enforcePolicy(payload));
433
- }
434
- },
435
- warn: (msg, payload) => {
436
- child.warn(msg, enforcePolicy(payload));
437
- },
438
- error: (msg, err, payload) => {
439
- child.error(msg, {
440
- ...enforcePolicy(payload),
441
- error: serializeError(err)
442
- // 🔥 ALWAYS structured
443
- });
444
- }
445
- };
446
- }
447
-
448
- // ../../libs/observability/src/logger/structured-logger.ts
449
- function applyLoggerOptions(options) {
450
- if (!options) return;
451
- const serviceName = options.serviceName ?? options.service;
452
- if (serviceName !== void 0 || options.redactPII !== void 0) {
453
- configureObservability({
454
- ...serviceName !== void 0 ? { serviceName } : {},
455
- ...options.redactPII !== void 0 ? { redactPII: options.redactPII } : {}
456
- });
457
- }
458
- }
459
- var StructuredLogger = class {
460
- constructor(persistentKeys = {}) {
461
- this.persistentKeys = persistentKeys;
462
- }
463
- persistentKeys;
464
- getPersistentKeys() {
465
- return { ...this.persistentKeys };
466
- }
467
- info(entry) {
468
- const { event = "log", ...rest } = entry;
469
- getLogger(this.persistentKeys).info(String(event), rest);
470
- }
471
- warn(entry) {
472
- const { event = "log", ...rest } = entry;
473
- getLogger(this.persistentKeys).warn(String(event), rest);
474
- }
475
- error(entry) {
476
- const { event = "log", err, error: err2, ...rest } = entry;
477
- const errVal = err ?? err2;
478
- getLogger(this.persistentKeys).error(String(event), errVal, rest);
479
- }
480
- debug(entry) {
481
- const { event = "log", ...rest } = entry;
482
- getLogger(this.persistentKeys).debug(String(event), rest);
483
- }
484
- http(entry) {
485
- this.info(entry);
486
- }
487
- verbose(entry) {
488
- this.debug(entry);
489
- }
490
- };
491
- function createLogger(options) {
492
- applyLoggerOptions(options);
493
- return new StructuredLogger();
494
- }
495
-
496
- // ../../libs/observability/src/http/performance-timer.ts
497
- function createTimer(operation, correlationId) {
498
- const startTime = Date.now();
499
- return {
500
- end: () => {
501
- const duration = Date.now() - startTime;
502
- getLogger().info("performance_timer", {
503
- operation,
504
- duration,
505
- correlationId
506
- });
507
- }
508
- };
509
- }
510
- function createPerformanceTimer(...args) {
511
- if (typeof args[0] === "string") {
512
- return createTimer(
513
- args[0],
514
- typeof args[1] === "string" ? args[1] : void 0
515
- );
516
- }
517
- if (typeof args[1] === "string") {
518
- return createTimer(
519
- args[1],
520
- typeof args[2] === "string" ? args[2] : void 0
521
- );
522
- }
523
- throw new Error(
524
- "createPerformanceTimer: expected (operation, correlationId?) or (logger, operation, correlationId?)"
525
- );
526
- }
527
-
528
183
  // ../../libs/utils/src/errors/base.error.ts
529
184
  var BaseError = class extends Error {
530
185
  statusCode;
@@ -544,390 +199,10 @@ var BaseError = class extends Error {
544
199
  }
545
200
  };
546
201
 
547
- // ../../libs/utils/src/middleware/withLambdaHandler.ts
548
- createLogger({
549
- service: "api-service",
550
- redactPII: true
551
- });
552
- createLogger({
553
- service: "dynamo-repository",
554
- redactPII: true
555
- });
556
-
557
202
  // ../../libs/metadata/src/models/relation-types.ts
558
- var RELATION_TYPES = [
559
- "PARENT_CHILD",
560
- "VALID_IN",
561
- "SUPPORTED_BY",
562
- "BELONGS_TO_CATEGORY",
563
- "REQUIRES"
564
- ];
565
203
  var RELATION_STATUS = {
566
204
  ACTIVE: "ACTIVE"};
567
205
 
568
- // ../../libs/metadata/src/validators/code-patterns.ts
569
- var METADATA_TYPE_CODE_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
570
- var METADATA_VALUE_CODE_PATTERN = /^[A-Z0-9]+(_[A-Z0-9]+)*$/;
571
-
572
- // ../../libs/metadata/src/validators/relation.ts
573
- new Set(RELATION_TYPES);
574
-
575
- // ../../libs/metadata/src/domain/lifecycle-filter.ts
576
- var LIFECYCLE_QUERY_STATUS = {
577
- ACTIVE: "ACTIVE",
578
- INACTIVE: "INACTIVE",
579
- DELETED: "DELETED",
580
- ALL: "ALL"
581
- };
582
- new Set(Object.values(LIFECYCLE_QUERY_STATUS));
583
- var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
584
- var ENCODING_LEN = 32;
585
- var RANDOM_LEN = 16;
586
- var TIME_LEN = 10;
587
- var TIME_MAX = 281474976710655;
588
- var ULIDErrorCode;
589
- (function(ULIDErrorCode2) {
590
- ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
591
- ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
592
- ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
593
- ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
594
- ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
595
- ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
596
- ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
597
- ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
598
- ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
599
- ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
600
- })(ULIDErrorCode || (ULIDErrorCode = {}));
601
- var ULIDError = class extends Error {
602
- constructor(errorCode, message) {
603
- super(`${message} (${errorCode})`);
604
- this.name = "ULIDError";
605
- this.code = errorCode;
606
- }
607
- };
608
- function randomChar(prng) {
609
- const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
610
- return ENCODING.charAt(randomPosition);
611
- }
612
- function replaceCharAt(str, index, char) {
613
- if (index > str.length - 1) {
614
- return str;
615
- }
616
- return str.substr(0, index) + char + str.substr(index + 1);
617
- }
618
- function incrementBase32(str) {
619
- let done = void 0, index = str.length, char, charIndex, output = str;
620
- const maxCharIndex = ENCODING_LEN - 1;
621
- while (!done && index-- >= 0) {
622
- char = output[index];
623
- charIndex = ENCODING.indexOf(char);
624
- if (charIndex === -1) {
625
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
626
- }
627
- if (charIndex === maxCharIndex) {
628
- output = replaceCharAt(output, index, ENCODING[0]);
629
- continue;
630
- }
631
- done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
632
- }
633
- if (typeof done === "string") {
634
- return done;
635
- }
636
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
637
- }
638
- function detectPRNG(root) {
639
- const rootLookup = detectRoot();
640
- const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
641
- if (typeof globalCrypto?.getRandomValues === "function") {
642
- return () => {
643
- const buffer = new Uint8Array(1);
644
- globalCrypto.getRandomValues(buffer);
645
- return buffer[0] / 256;
646
- };
647
- } else if (typeof globalCrypto?.randomBytes === "function") {
648
- return () => globalCrypto.randomBytes(1).readUInt8() / 256;
649
- } else if (crypto?.randomBytes) {
650
- return () => crypto.randomBytes(1).readUInt8() / 256;
651
- }
652
- throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
653
- }
654
- function detectRoot() {
655
- if (inWebWorker())
656
- return self;
657
- if (typeof window !== "undefined") {
658
- return window;
659
- }
660
- if (typeof global !== "undefined") {
661
- return global;
662
- }
663
- if (typeof globalThis !== "undefined") {
664
- return globalThis;
665
- }
666
- return null;
667
- }
668
- function encodeRandom(len, prng) {
669
- let str = "";
670
- for (; len > 0; len--) {
671
- str = randomChar(prng) + str;
672
- }
673
- return str;
674
- }
675
- function encodeTime(now, len = TIME_LEN) {
676
- if (isNaN(now)) {
677
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
678
- } else if (now > TIME_MAX) {
679
- throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
680
- } else if (now < 0) {
681
- throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
682
- } else if (Number.isInteger(now) === false) {
683
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
684
- }
685
- let mod, str = "";
686
- for (let currentLen = len; currentLen > 0; currentLen--) {
687
- mod = now % ENCODING_LEN;
688
- str = ENCODING.charAt(mod) + str;
689
- now = (now - mod) / ENCODING_LEN;
690
- }
691
- return str;
692
- }
693
- function inWebWorker() {
694
- return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
695
- }
696
- function monotonicFactory(prng) {
697
- const currentPRNG = detectPRNG();
698
- let lastTime = 0, lastRandom;
699
- return function _ulid(seedTime) {
700
- const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
701
- if (seed <= lastTime) {
702
- const incrementedRandom = lastRandom = incrementBase32(lastRandom);
703
- return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
704
- }
705
- lastTime = seed;
706
- const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
707
- return encodeTime(seed, TIME_LEN) + newRandom;
708
- };
709
- }
710
-
711
- // ../../libs/metadata/src/repositories/dynamodb/metadata.repository.impl.ts
712
- monotonicFactory();
713
- monotonicFactory();
714
- var RELATION_TYPE_ZOD_ENUM = RELATION_TYPES;
715
- var contextSchema = z.object({
716
- module: z.string().min(1),
717
- category: z.string().min(1),
718
- condition: z.string().min(1),
719
- country: z.string().min(1)
720
- });
721
- z.object({
722
- metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode"),
723
- displayName: z.string().min(1).max(100),
724
- description: z.string().optional(),
725
- valueDataType: z.enum(["Enum", "Numeric", "Boolean", "Text"]),
726
- multiSelectAllowed: z.boolean(),
727
- applicableModules: z.array(z.string()).optional(),
728
- attributeSchema: z.record(z.string(), z.unknown()).optional(),
729
- status: z.enum(["ACTIVE", "INACTIVE"]),
730
- supportsRelations: z.boolean().optional(),
731
- relationFieldLabel: z.string().max(150).nullable().optional(),
732
- targetMetadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN).nullable().optional(),
733
- selectionMode: z.enum(["SINGLE", "MULTI"]).nullable().optional(),
734
- relationRequired: z.boolean().nullable().optional(),
735
- relationType: z.enum(RELATION_TYPE_ZOD_ENUM).nullable().optional(),
736
- createdBy: z.string().optional(),
737
- lastModifiedBy: z.string().optional()
738
- });
739
- z.object({
740
- status: z.enum(["ACTIVE", "INACTIVE"]),
741
- lastModifiedBy: z.string().optional()
742
- });
743
- var applicabilityObjectSchema = z.object({
744
- module: z.array(z.string()),
745
- category: z.array(z.string()),
746
- condition: z.array(z.string()),
747
- country: z.array(z.string()),
748
- language: z.array(z.string()).optional()
749
- });
750
- z.object({
751
- valueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid valueCode").optional(),
752
- metadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid metadataValueCode").optional(),
753
- label: z.string().min(1).max(150),
754
- description: z.string().max(2e3).optional(),
755
- sortOrder: z.number().int().min(0).optional(),
756
- status: z.enum(["ACTIVE", "INACTIVE"]),
757
- isGlobal: z.boolean(),
758
- attributes: z.record(z.string(), z.unknown()).optional(),
759
- valueAttributes: z.record(z.string(), z.unknown()).optional(),
760
- applicability: applicabilityObjectSchema.optional(),
761
- applicableModules: z.array(z.string()).optional(),
762
- applicableCategories: z.array(z.string()).optional(),
763
- applicableConditions: z.array(z.string()).optional(),
764
- applicableCountries: z.array(z.string()).optional(),
765
- applicableLanguages: z.array(z.string()).optional(),
766
- relationships: z.array(
767
- z.object({
768
- targetMetadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid targetMetadataValueCode")
769
- })
770
- ).optional()
771
- }).refine((b) => !!(b.valueCode || b.metadataValueCode), { message: "valueCode or metadataValueCode is required" });
772
- z.object({
773
- metadataTypeCode: z.string().min(1),
774
- metadataValueCode: z.string().min(1),
775
- context: contextSchema
776
- });
777
- var paginationSchema = z.object({
778
- limit: z.coerce.number().int().min(1).max(100).optional().default(50),
779
- nextToken: z.string().optional()
780
- });
781
- paginationSchema.extend({
782
- module: z.string().optional(),
783
- category: z.string().optional(),
784
- condition: z.string().optional(),
785
- country: z.string().optional(),
786
- language: z.string().optional()
787
- });
788
- z.object({
789
- dimension: z.enum(["module", "category", "condition", "country", "language"], {
790
- message: "dimension must be module, category, condition, country, or language"
791
- })
792
- });
793
- z.object({
794
- limit: z.coerce.number().int().min(1).max(100).optional().default(50),
795
- nextToken: z.string().optional()
796
- });
797
- z.object({
798
- metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode")
799
- });
800
- z.object({
801
- metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode"),
802
- metadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid metadataValueCode")
803
- });
804
-
805
- // ../../libs/metadata/src/validators/validate-inputs.ts
806
- new Set(RELATION_TYPES);
807
-
808
- // ../../libs/metadata/src/mappers/metadata-request.mapper.ts
809
- createLogger({
810
- service: "metadata-registry-service",
811
- redactPII: true
812
- });
813
-
814
- // ../../libs/metadata/src/change-policy/types/policy-group.codes.ts
815
- var POLICY_GROUP = {
816
- IDENTITY_IMMUTABLE: "IDENTITY_IMMUTABLE",
817
- DISPLAY_ONLY: "DISPLAY_ONLY",
818
- AVAILABILITY_STATUS: "AVAILABILITY_STATUS",
819
- APPLICABILITY_SCOPE: "APPLICABILITY_SCOPE",
820
- STRUCTURED_BEHAVIOR: "STRUCTURED_BEHAVIOR",
821
- CLINICAL_INTERPRETATION: "CLINICAL_INTERPRETATION",
822
- EXPANDABLE_OPTION: "EXPANDABLE_OPTION",
823
- FIXED_TEMPLATE_VALUE: "FIXED_TEMPLATE_VALUE",
824
- RUNTIME_PINNED: "RUNTIME_PINNED"
825
- };
826
- var POLICY_GROUP_CODES = Object.values(POLICY_GROUP);
827
- var VERSION_IMPACT = {
828
- DESCRIPTIVE: "Descriptive",
829
- ADDITIVE: "Additive",
830
- BREAKING: "Breaking"
831
- };
832
- var VERSION_IMPACT_CODES = Object.values(VERSION_IMPACT);
833
- var RUNTIME_IMPACT = {
834
- NONE: "None",
835
- DISPLAY_ONLY: "DisplayOnly",
836
- REVIEW_REQUIRED: "ReviewRequired",
837
- MIGRATION_REQUIRED: "MigrationRequired"
838
- };
839
- var RUNTIME_IMPACT_CODES = Object.values(RUNTIME_IMPACT);
840
- var MERGE_BEHAVIOR = {
841
- SILENT_DISPLAY_REFRESH: "SilentDisplayRefresh",
842
- ADD_ONLY: "AddOnly",
843
- PRESERVE_ORG_OVERRIDE: "PreserveOrgOverride",
844
- MANUAL_REVIEW: "ManualReview",
845
- BLOCK: "Block"
846
- };
847
- var MERGE_BEHAVIOR_CODES = Object.values(MERGE_BEHAVIOR);
848
- var CHANGE_POLICY_OPERATION = {
849
- ADD: "Add",
850
- UPDATE: "Update",
851
- INACTIVATE: "Inactivate",
852
- RETIRE: "Retire",
853
- PUBLISH: "Publish"
854
- };
855
- var CHANGE_POLICY_OPERATION_CODES = Object.values(CHANGE_POLICY_OPERATION);
856
- var APPLICABILITY_CHANGE_KIND = {
857
- EXPAND: "Expand",
858
- RESTRICT: "Restrict",
859
- ANY: "Any"
860
- };
861
- var APPLICABILITY_CHANGE_KIND_CODES = Object.values(APPLICABILITY_CHANGE_KIND);
862
- var changePolicyRuleSchema = z.object({
863
- ruleId: z.string().min(1),
864
- objectPath: z.string().min(1),
865
- operation: z.enum(CHANGE_POLICY_OPERATION_CODES),
866
- changeKind: z.enum(APPLICABILITY_CHANGE_KIND_CODES).optional(),
867
- policyGroup: z.enum(POLICY_GROUP_CODES),
868
- versionImpact: z.enum(VERSION_IMPACT_CODES),
869
- requiresMetadataVersion: z.boolean(),
870
- requiresTemplateAdoption: z.boolean(),
871
- requiresOrgCapabilityReevaluation: z.boolean(),
872
- runtimeImpact: z.enum(RUNTIME_IMPACT_CODES),
873
- canAutoApplyToPublishedCarePlan: z.boolean(),
874
- canAutoApplyToActiveRuntime: z.boolean(),
875
- mergeBehavior: z.enum(MERGE_BEHAVIOR_CODES),
876
- uxDiffRequired: z.boolean(),
877
- notes: z.string().optional()
878
- });
879
- z.object({
880
- version: z.string().min(1),
881
- rules: z.array(changePolicyRuleSchema).min(1)
882
- });
883
-
884
- // ../../libs/metadata/src/services/metadata-value-retire.service.ts
885
- monotonicFactory();
886
-
887
- // ../../libs/metadata/src/services/metadata-change-request.service.ts
888
- monotonicFactory();
889
- z.object({
890
- /**
891
- * When true, a latest INACTIVE version is projected. Default false: the latest
892
- * version must be ACTIVE, and an older ACTIVE version is not used instead.
893
- */
894
- includeInactive: z.boolean().optional(),
895
- /**
896
- * When true, every published version of a value is retained under `versions`.
897
- * Default false: runtime projection keeps only the latest version.
898
- * Historical versions remain in the registry/audit model.
899
- */
900
- includeAllVersions: z.boolean().optional(),
901
- /** Numeric schema version stamped for transitional validators. */
902
- schemaVersion: z.number().int().positive().optional(),
903
- /** Wire projectionVersion string (e.g. `1.0`). */
904
- projectionVersion: z.string().min(1).optional(),
905
- /**
906
- * Optional storage key prefix hint for adapters (not used by pure build).
907
- * Callers may also pass prefix directly to {@link S3ProjectionStorage}.
908
- */
909
- storagePrefix: z.string().min(1).optional(),
910
- /**
911
- * Maximum unresolved non-authorization relationships that may be omitted
912
- * from one release. Above this count, publication fails.
913
- * The worker parses `PROJECTION_MAX_EXCLUDED_RELATIONSHIPS`.
914
- */
915
- maxExcludedRelationships: z.number().int().nonnegative().optional(),
916
- /**
917
- * Maximum percentage of the relationship collection that may be omitted.
918
- * Above this share, publication fails so an incomplete snapshot is not
919
- * treated as a successful release. Integer 0–100.
920
- */
921
- maxExcludedRelationshipPercent: z.number().int().min(0).max(100).optional(),
922
- /**
923
- * When true, unresolved Role, Module, Feature, and PermissionAction
924
- * relationships are excluded under the same thresholds. Default false:
925
- * those relationships still fail the release.
926
- * The worker parses `PROJECTION_ALLOW_UNRESOLVED_AUTHORIZATION_RELATIONS`.
927
- */
928
- allowUnresolvedAuthorizationRelations: z.boolean().optional()
929
- });
930
-
931
206
  // ../../libs/metadata-projection/src/lib/errors/ProjectionError.ts
932
207
  var ProjectionError = class extends BaseError {
933
208
  constructor(message, statusCode = 400, code = "PROJECTION_ERROR", details, options) {
@@ -935,7 +210,6 @@ var ProjectionError = class extends BaseError {
935
210
  this.name = "ProjectionError";
936
211
  }
937
212
  };
938
- new AsyncLocalStorage();
939
213
 
940
214
  // ../../libs/metadata-projection/src/lib/serializer/ProjectionSerializer.ts
941
215
  var ProjectionSerializer = class _ProjectionSerializer {
@@ -1341,139 +615,6 @@ var StorageError = class extends BaseError {
1341
615
  this.name = "StorageError";
1342
616
  }
1343
617
  };
1344
- var statusSchema = z.enum([STATUS.ACTIVE, STATUS.INACTIVE, STATUS.DELETED]);
1345
- var applicabilitySchema = z.object({
1346
- module: z.array(z.string()),
1347
- category: z.array(z.string()),
1348
- condition: z.array(z.string()),
1349
- country: z.array(z.string()),
1350
- language: z.array(z.string()).optional()
1351
- });
1352
- var metadataTypeRecordSchema = z.object({
1353
- metadataTypeCode: z.string().min(1),
1354
- version: z.number().int().nonnegative(),
1355
- displayName: z.string().min(1),
1356
- description: z.string().optional(),
1357
- valueDataType: z.string().min(1),
1358
- multiSelectAllowed: z.boolean(),
1359
- applicableModules: z.array(z.string()),
1360
- supportsRelations: z.boolean(),
1361
- relationFieldLabel: z.string().nullable(),
1362
- targetMetadataTypeCode: z.string().nullable(),
1363
- selectionMode: z.enum(["SINGLE", "MULTI"]).nullable(),
1364
- relationRequired: z.boolean().nullable(),
1365
- relationType: z.string().nullable(),
1366
- valueApplicabilityConfig: z.object({
1367
- moduleScoped: z.boolean().optional(),
1368
- categoryDependent: z.boolean().optional(),
1369
- conditionDependent: z.boolean().optional(),
1370
- countryDependent: z.boolean().optional(),
1371
- languageDependent: z.boolean().optional()
1372
- }).optional(),
1373
- attributeSchema: z.record(z.string(), z.unknown()).optional(),
1374
- status: statusSchema,
1375
- createdAt: z.string().min(1),
1376
- lastModifiedAt: z.string().min(1),
1377
- createdBy: z.string().optional(),
1378
- lastModifiedBy: z.string().optional()
1379
- });
1380
- var metadataValueRecordSchema = z.object({
1381
- metadataTypeCode: z.string().min(1),
1382
- valueCode: z.string().min(1),
1383
- version: z.number().int().nonnegative(),
1384
- label: z.string().min(1),
1385
- description: z.string().optional(),
1386
- sortOrder: z.number().int(),
1387
- status: statusSchema,
1388
- isGlobal: z.boolean(),
1389
- attributes: z.record(z.string(), z.unknown()),
1390
- applicability: applicabilitySchema,
1391
- applSkKeys: z.array(z.string()),
1392
- createdAt: z.string().min(1),
1393
- lastModifiedAt: z.string().min(1),
1394
- createdBy: z.string().optional(),
1395
- lastModifiedBy: z.string().optional(),
1396
- deletedAt: z.string().optional(),
1397
- deletedBy: z.string().optional(),
1398
- deleteReason: z.string().optional(),
1399
- previousStatus: statusSchema.optional()
1400
- });
1401
- var metadataRelationRecordSchema = z.object({
1402
- id: z.string().min(1),
1403
- relationType: z.string().min(1),
1404
- fromMetadataTypeCode: z.string().min(1),
1405
- fromMetadataValueCode: z.string().min(1),
1406
- toMetadataTypeCode: z.string().min(1),
1407
- toMetadataValueCode: z.string().min(1),
1408
- status: z.enum(["ACTIVE", "INACTIVE"]),
1409
- createdAt: z.string().min(1),
1410
- createdBy: z.string().optional(),
1411
- updatedAt: z.string().optional(),
1412
- updatedBy: z.string().optional()
1413
- });
1414
- z.object({
1415
- environment: z.string().min(1),
1416
- releaseId: z.string().min(1).optional(),
1417
- revision: z.string().min(1).optional(),
1418
- generatedAt: z.string().min(1).optional(),
1419
- types: z.array(metadataTypeRecordSchema),
1420
- values: z.array(metadataValueRecordSchema),
1421
- relations: z.array(metadataRelationRecordSchema).optional()
1422
- });
1423
- var projectionTypeSchema = z.string().min(1);
1424
- var artifactSchema = z.object({
1425
- fileName: z.string().min(1),
1426
- projectionType: projectionTypeSchema,
1427
- contentType: z.literal("application/json"),
1428
- body: z.string().min(1),
1429
- contentHash: z.string().min(1),
1430
- parsed: z.unknown()
1431
- });
1432
- var metadataTypeEntrySchema = z.object({
1433
- typeCode: z.string().min(1),
1434
- projectionFile: z.string().min(1)
1435
- });
1436
- var lookupIndexEntrySchema = z.object({
1437
- typeCode: z.string().min(1),
1438
- valueCode: z.string().min(1),
1439
- projectionFile: z.string().min(1)
1440
- });
1441
- var manifestSchema = z.object({
1442
- releaseId: z.string().min(1),
1443
- environment: z.string().min(1),
1444
- generatedAt: z.string().min(1),
1445
- projectionVersion: z.string().min(1),
1446
- metadataCount: z.number().int().nonnegative(),
1447
- artifactCount: z.number().int().nonnegative(),
1448
- contentHash: z.string().min(1),
1449
- artifacts: z.array(z.string().min(1)),
1450
- files: z.array(
1451
- z.object({
1452
- fileName: z.string().min(1),
1453
- projectionType: projectionTypeSchema,
1454
- contentHash: z.string().min(1),
1455
- itemCount: z.number().int().nonnegative()
1456
- })
1457
- ),
1458
- metadataTypes: z.record(z.string(), metadataTypeEntrySchema),
1459
- lookupIndex: z.record(z.string(), lookupIndexEntrySchema),
1460
- lifecycle: z.object({
1461
- values: z.literal("activeAndInactive"),
1462
- relations: z.literal("activeAndInactive")
1463
- }).optional(),
1464
- revision: z.string().min(1),
1465
- schemaVersion: z.number().int().positive()
1466
- });
1467
- z.object({
1468
- releaseId: z.string().min(1),
1469
- environment: z.string().min(1),
1470
- generatedAt: z.string().min(1),
1471
- projectionVersion: z.string().min(1),
1472
- revision: z.string().min(1),
1473
- metadataCount: z.number().int().nonnegative(),
1474
- manifest: manifestSchema,
1475
- artifacts: z.array(artifactSchema).min(1)
1476
- });
1477
618
 
1478
619
  // ../../libs/metadata-projection/src/lib/validators/RelationshipIndexValidator.ts
1479
620
  var RELATIONSHIP_KEY_PATTERN = /^[^:\s]+:.+$/;
@@ -1920,15 +1061,15 @@ function typedRelationIndexFor(relations, index) {
1920
1061
  return built;
1921
1062
  }
1922
1063
  function filterTypedRelations(relations, query, index) {
1923
- const resolved2 = typedRelationIndexFor(relations, index);
1064
+ const resolved = typedRelationIndexFor(relations, index);
1924
1065
  const filter = query.status ?? METADATA_STATUS_FILTER.ACTIVE;
1925
- if (!resolved2.complete) {
1066
+ if (!resolved.complete) {
1926
1067
  return relations.filter(
1927
1068
  (relation) => matchesForward(relation, query) && statusMatchesRelation(relation, filter)
1928
1069
  );
1929
1070
  }
1930
1071
  const bucket = typedRelationsForEndpoint(
1931
- resolved2,
1072
+ resolved,
1932
1073
  "OUTGOING",
1933
1074
  typedRelationEndpointKey(query.fromType, query.fromValue),
1934
1075
  filter
@@ -2023,9 +1164,6 @@ function parseTypedRelationshipFile(parsed, expected) {
2023
1164
  return relations;
2024
1165
  }
2025
1166
 
2026
- // ../../libs/metadata-projection/src/lib/release/validateReleaseForActivation.ts
2027
- createLogger({ serviceName: "metadata-projection" });
2028
-
2029
1167
  // ../../libs/metadata-projection/src/lib/runtime-query/publishedValueListing.ts
2030
1168
  var PUBLISHED_VALUE_LIST_LIMITS = {
2031
1169
  MAX_PAGE_SIZE: 500,
@@ -2454,6 +1592,10 @@ function queryPublishedRelationships(query) {
2454
1592
  message: "Typed relationship catalog contains a row that cannot be queried"
2455
1593
  };
2456
1594
  }
1595
+ const unpublished = unpublishedRelationType(query.relations, relationType);
1596
+ if (unpublished) {
1597
+ return { ok: false, ...unpublished };
1598
+ }
2457
1599
  const sourceKey = typedRelationEndpointKey(sourceTypeCode, sourceValueCode);
2458
1600
  const bucket = typedRelationsForEndpoint(index, direction, sourceKey, status.filter);
2459
1601
  const seen = /* @__PURE__ */ new Set();
@@ -2522,11 +1664,11 @@ function relationshipKey(relation) {
2522
1664
  ].join("\0");
2523
1665
  }
2524
1666
  function resolveRelationshipStatus(status) {
2525
- const resolved2 = resolveMetadataStatusFilter({ status });
2526
- if (!resolved2.ok) {
2527
- return resolved2;
1667
+ const resolved = resolveMetadataStatusFilter({ status });
1668
+ if (!resolved.ok) {
1669
+ return resolved;
2528
1670
  }
2529
- return { ok: true, filter: resolved2.filter };
1671
+ return { ok: true, filter: resolved.filter };
2530
1672
  }
2531
1673
  function lifecycleUnsupported(message) {
2532
1674
  return { ok: false, code: METADATA_LIFECYCLE_UNSUPPORTED, message };
@@ -2537,6 +1679,34 @@ function optionalCode(value) {
2537
1679
  }
2538
1680
  return value.trim();
2539
1681
  }
1682
+ var publishedRelationTypeCache = /* @__PURE__ */ new WeakMap();
1683
+ function publishedRelationTypes(relations) {
1684
+ const cached = publishedRelationTypeCache.get(relations);
1685
+ if (cached) {
1686
+ return cached;
1687
+ }
1688
+ const types = /* @__PURE__ */ new Set();
1689
+ for (const relation of relations) {
1690
+ if (typeof relation.relationType === "string" && relation.relationType.trim()) {
1691
+ types.add(relation.relationType);
1692
+ }
1693
+ }
1694
+ publishedRelationTypeCache.set(relations, types);
1695
+ return types;
1696
+ }
1697
+ function unpublishedRelationType(relations, relationType) {
1698
+ const type = relationType?.trim();
1699
+ if (!type) {
1700
+ return void 0;
1701
+ }
1702
+ if (publishedRelationTypes(relations).has(type)) {
1703
+ return void 0;
1704
+ }
1705
+ return {
1706
+ code: METADATA_RELATION_SEMANTICS_UNSUPPORTED,
1707
+ message: `Relationship type ${type} is not published in typed-relations.json`
1708
+ };
1709
+ }
2540
1710
  function resolvePublishedRelationshipQuery(input) {
2541
1711
  const validated = validateRelationshipQuery(input);
2542
1712
  if (validated) {
@@ -2664,27 +1834,6 @@ function validateRelationshipQuery(query) {
2664
1834
  }
2665
1835
  return void 0;
2666
1836
  }
2667
- var metadataPublishedPayloadSchema = z.object({
2668
- changeRequestId: z.string().min(1),
2669
- changeRevision: z.string().min(1).optional(),
2670
- metadataTypeCode: z.string().min(1),
2671
- metadataValueCode: z.string().min(1).optional(),
2672
- entityType: z.enum(["METADATA_TYPE", "METADATA_VALUE"]),
2673
- operation: z.enum(["Add", "Update"]),
2674
- publishStrategy: z.enum(["IN_PLACE", "NEW_VERSION"]),
2675
- version: z.number().int().positive(),
2676
- publishedAt: z.string().min(1)
2677
- });
2678
- Object.assign(
2679
- metadataPublishedPayloadSchema,
2680
- {
2681
- __meta: {
2682
- eventType: "MetadataPublished.v1",
2683
- eventVersion: "1.0.0",
2684
- source: "metadata-registry"
2685
- }
2686
- }
2687
- );
2688
1837
 
2689
1838
  // ../../libs/runtime-metadata/src/lib/config/RuntimeMetadataConfig.ts
2690
1839
  var runtimeMetadataConfigSchema = z.object({
@@ -2921,9 +2070,45 @@ function isMetadataValueObjectArray(val) {
2921
2070
  return val.every(isMetadataValueObject);
2922
2071
  }
2923
2072
 
2073
+ // ../../libs/runtime-metadata/src/lib/utils/linkedEntityMetadataType.ts
2074
+ var APPLIES_TO_LINKED_ENTITY_METADATA_TYPE = {
2075
+ METRIC: "MetricCode",
2076
+ SYMPTOM_QUESTION: "QuestionCode",
2077
+ DEVICE: "DeviceCode",
2078
+ ENGAGEMENT_EVENT: "EngagementEventCode"
2079
+ };
2080
+ function linkedEntityMetadataTypeFromAppliesTo(appliesToType) {
2081
+ const code = appliesToType?.trim().toUpperCase() ?? "";
2082
+ if (!code) {
2083
+ return void 0;
2084
+ }
2085
+ return APPLIES_TO_LINKED_ENTITY_METADATA_TYPE[code];
2086
+ }
2087
+ function readAppliesToTypeValue(parent) {
2088
+ if (!parent) {
2089
+ return void 0;
2090
+ }
2091
+ const raw = parent["AppliesToType"] ?? parent["appliesToType"] ?? parent["APPLIES_TO_TYPE"];
2092
+ if (typeof raw === "string" && raw.trim()) {
2093
+ return raw.trim();
2094
+ }
2095
+ if (isMetadataValueObject(raw) && raw.value.trim()) {
2096
+ return raw.value.trim();
2097
+ }
2098
+ if (isMetadataReference(raw) && raw.valueCode.trim()) {
2099
+ return raw.valueCode.trim();
2100
+ }
2101
+ return void 0;
2102
+ }
2103
+ function isLinkedEntityCodeField(field) {
2104
+ const normalized = field.trim();
2105
+ return normalized === "LinkedEntityCode" || normalized === "linkedEntityCode" || normalized === "LINKED_ENTITY_CODE" || normalized === "LinkedEntity" || normalized === "linkedEntity";
2106
+ }
2107
+
2924
2108
  // ../../libs/runtime-metadata/src/lib/utils/normalizeRuntimeMetadataTypeCode.ts
2925
2109
  var RUNTIME_METADATA_TYPE_CODE_ALIASES = {
2926
- Speciality: "Specialty"
2110
+ Speciality: "Specialty",
2111
+ OrganizationType: "OrganisationType"
2927
2112
  };
2928
2113
  function normalizeRuntimeMetadataTypeCode(metadataTypeCode) {
2929
2114
  const trimmed = metadataTypeCode?.trim() ?? "";
@@ -2986,6 +2171,11 @@ var NON_METADATA_KEYS = /* @__PURE__ */ new Set([
2986
2171
  "orgTemplateId",
2987
2172
  "platformTemplateId",
2988
2173
  "templateName",
2174
+ "templateType",
2175
+ "templateLevel",
2176
+ "metadataMode",
2177
+ "MetadataMode",
2178
+ "metadataType",
2989
2179
  "monitoringName",
2990
2180
  "subtitle",
2991
2181
  "requirement",
@@ -3032,6 +2222,33 @@ function isWorkflowStepRecord(node) {
3032
2222
  function isWorkflowStepRuleField(key, parent) {
3033
2223
  return WORKFLOW_STEP_RULE_KEYS.has(key) && isWorkflowStepRecord(parent);
3034
2224
  }
2225
+ function isPlainRuleObject(value) {
2226
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2227
+ }
2228
+ function isTemplateRuleNode(value) {
2229
+ if (!isPlainRuleObject(value)) {
2230
+ return false;
2231
+ }
2232
+ const enable = value["enable"];
2233
+ const orgedit = value["orgedit"];
2234
+ const metadataMode = value["metadataMode"];
2235
+ const hasFlags = typeof enable === "boolean" && typeof orgedit === "boolean";
2236
+ const hasMode = typeof metadataMode === "string" && metadataMode.trim().length > 0;
2237
+ return hasFlags || hasMode && ("min" in value || "max" in value);
2238
+ }
2239
+ function isTemplateRulesMap(value) {
2240
+ if (!isPlainRuleObject(value)) {
2241
+ return false;
2242
+ }
2243
+ const entries = Object.values(value);
2244
+ if (entries.length === 0) {
2245
+ return false;
2246
+ }
2247
+ return entries.every((entry) => entry == null || isTemplateRuleNode(entry));
2248
+ }
2249
+ function isTemplateRuleConfiguration(key, value) {
2250
+ return key === "rules" || isTemplateRuleNode(value) || isTemplateRulesMap(value);
2251
+ }
3035
2252
  var DEFAULT_EXCLUDED = new Set(DEFAULT_EXCLUDED_CODE_FIELDS);
3036
2253
  function typeCodeFromCodeFieldName(fieldName, excluded = DEFAULT_EXCLUDED) {
3037
2254
  if (typeof fieldName !== "string" || fieldName.length <= 4) {
@@ -3040,7 +2257,7 @@ function typeCodeFromCodeFieldName(fieldName, excluded = DEFAULT_EXCLUDED) {
3040
2257
  if (!fieldName.endsWith("Code")) {
3041
2258
  return void 0;
3042
2259
  }
3043
- if (fieldName.includes("__Code")) {
2260
+ if (fieldName.length > 6 && fieldName.toLowerCase().endsWith("__code")) {
3044
2261
  return void 0;
3045
2262
  }
3046
2263
  if (excluded.has(fieldName)) {
@@ -3063,10 +2280,15 @@ function createCodeFieldExclusionSet(extra) {
3063
2280
  }
3064
2281
 
3065
2282
  // ../../libs/runtime-metadata/src/lib/utils/collectResponseTypeCodes.ts
2283
+ var METADATA_TRAVERSAL_MAX_DEPTH = 32;
2284
+ var METADATA_TRAVERSAL_MAX_NODES = 8e3;
2285
+ var LINKED_ENTITY_CONCRETE_TYPES = [
2286
+ ...new Set(Object.values(APPLIES_TO_LINKED_ENTITY_METADATA_TYPE))
2287
+ ];
3066
2288
  function collectResponseTypeCodes(value, options) {
3067
2289
  const collected = /* @__PURE__ */ new Set();
3068
- const knownSet = options?.knownTypes ? options.knownTypes instanceof Set ? options.knownTypes : new Set(options.knownTypes) : void 0;
3069
- walk(value, collected, void 0, /* @__PURE__ */ new WeakSet(), exclusionSet(options), knownSet, "", options?.diagnostics);
2290
+ const state = createWalkState(options, collected, void 0);
2291
+ walk(value, state, 0);
3070
2292
  if (options?.diagnostics) {
3071
2293
  options.diagnostics.totalUniqueTypesDiscovered = collected.size;
3072
2294
  }
@@ -3074,8 +2296,8 @@ function collectResponseTypeCodes(value, options) {
3074
2296
  }
3075
2297
  function collectResponseReferences(value, options) {
3076
2298
  const collected = /* @__PURE__ */ new Map();
3077
- const knownSet = options?.knownTypes ? options.knownTypes instanceof Set ? options.knownTypes : new Set(options.knownTypes) : void 0;
3078
- walk(value, void 0, collected, /* @__PURE__ */ new WeakSet(), exclusionSet(options), knownSet, "", options?.diagnostics);
2299
+ const state = createWalkState(options, void 0, collected);
2300
+ walk(value, state, 0);
3079
2301
  if (options?.diagnostics) {
3080
2302
  options.diagnostics.totalUniqueTypeValuesDiscovered = collected.size;
3081
2303
  }
@@ -3087,6 +2309,20 @@ function collectResponseReferences(value, options) {
3087
2309
  function exclusionSet(options) {
3088
2310
  return createCodeFieldExclusionSet(options?.excludedCodeFields);
3089
2311
  }
2312
+ function createWalkState(options, typeCodes, references) {
2313
+ const knownSet = options?.knownTypes ? options.knownTypes instanceof Set ? options.knownTypes : new Set(options.knownTypes) : void 0;
2314
+ const isKnownType = options?.isKnownType;
2315
+ const probe = isKnownType ? (typeCode) => isKnownType(typeCode) : knownSet ? (typeCode) => knownSet.has(typeCode) : () => void 0;
2316
+ return {
2317
+ typeCodes,
2318
+ references,
2319
+ visited: /* @__PURE__ */ new WeakSet(),
2320
+ excludedCodeFields: exclusionSet(options),
2321
+ probe,
2322
+ hasCatalog: isKnownType != null || knownSet != null,
2323
+ nodes: 0
2324
+ };
2325
+ }
3090
2326
  function pushUnique(candidates, value) {
3091
2327
  const trimmed = value?.trim() ?? "";
3092
2328
  if (!trimmed || candidates.includes(trimmed)) {
@@ -3101,6 +2337,29 @@ function pascalCaseToken(token) {
3101
2337
  const lower = token.toLowerCase();
3102
2338
  return lower.charAt(0).toUpperCase() + lower.slice(1);
3103
2339
  }
2340
+ var FIELD_KEY_METADATA_TYPE_ALIASES = {
2341
+ DefaultPriority: "Priority",
2342
+ Speciality: "Specialty",
2343
+ SPECIALITY: "Specialty",
2344
+ speciality: "Specialty",
2345
+ AllowedDevice: "Device",
2346
+ AllowedDevices: "Device",
2347
+ /** Template device dropdown may publish as Device or DeviceCode. */
2348
+ allowedDevice: "Device",
2349
+ allowedDevices: "Device"
2350
+ };
2351
+ var RELATED_METADATA_TYPE_CANDIDATES = {
2352
+ goalDuration: ["DurationType"],
2353
+ GoalDuration: ["DurationType"],
2354
+ GOAL_DURATION: ["GoalDuration", "DurationType"],
2355
+ defaultDurationType: ["DurationType"],
2356
+ DefaultDurationType: ["DurationType"],
2357
+ DEFAULT_DURATION_TYPE: ["DurationType"],
2358
+ measurementType: ["GoalMeasurementType"],
2359
+ MeasurementType: ["GoalMeasurementType"],
2360
+ goalMeasurementType: ["MeasurementType"],
2361
+ GoalMeasurementType: ["MeasurementType"]
2362
+ };
3104
2363
  function getCandidateTypeCodesForKey(key) {
3105
2364
  const candidates = [];
3106
2365
  const capitalized = key.charAt(0).toUpperCase() + key.slice(1);
@@ -3108,7 +2367,13 @@ function getCandidateTypeCodesForKey(key) {
3108
2367
  pushUnique(candidates, pascalCaseToken(key));
3109
2368
  }
3110
2369
  pushUnique(candidates, capitalized);
2370
+ pushUnique(candidates, normalizeRuntimeMetadataTypeCode(capitalized));
3111
2371
  pushUnique(candidates, normalizeRuntimeMetadataTypeCode(key));
2372
+ const fieldAlias = FIELD_KEY_METADATA_TYPE_ALIASES[key] ?? FIELD_KEY_METADATA_TYPE_ALIASES[capitalized];
2373
+ if (fieldAlias) {
2374
+ pushUnique(candidates, fieldAlias);
2375
+ pushUnique(candidates, normalizeRuntimeMetadataTypeCode(fieldAlias));
2376
+ }
3112
2377
  if (/code$/i.test(key) && key.length > 4) {
3113
2378
  const base = key.slice(0, -4);
3114
2379
  pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
@@ -3119,13 +2384,26 @@ function getCandidateTypeCodesForKey(key) {
3119
2384
  }
3120
2385
  if (capitalized === "AllowedDevice" || capitalized === "AllowedDevices") {
3121
2386
  pushUnique(candidates, "Device");
2387
+ pushUnique(candidates, "DeviceCode");
3122
2388
  }
3123
2389
  if (capitalized === "LinkedEntityCode" || capitalized === "LinkedEntity") {
3124
2390
  pushUnique(candidates, "MetricCode");
3125
2391
  pushUnique(candidates, "QuestionCode");
2392
+ pushUnique(candidates, "DeviceCode");
2393
+ pushUnique(candidates, "EngagementEventCode");
2394
+ }
2395
+ const related = RELATED_METADATA_TYPE_CANDIDATES[key] ?? RELATED_METADATA_TYPE_CANDIDATES[capitalized];
2396
+ if (related) {
2397
+ for (const typeCode of related) {
2398
+ pushUnique(candidates, typeCode);
2399
+ pushUnique(candidates, normalizeRuntimeMetadataTypeCode(typeCode));
2400
+ }
3126
2401
  }
3127
2402
  const pluralKey = isAllCapsToken(key) ? key.toLowerCase() : key;
3128
- if (pluralKey.endsWith("ies") && pluralKey.length > 3) {
2403
+ if (/types$/i.test(pluralKey) && pluralKey.length > 5) {
2404
+ const base = pluralKey.slice(0, -1);
2405
+ pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
2406
+ } else if (pluralKey.endsWith("ies") && pluralKey.length > 3) {
3129
2407
  const base = pluralKey.slice(0, -3) + "y";
3130
2408
  pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
3131
2409
  } else if (pluralKey.endsWith("es") && pluralKey.length > 2) {
@@ -3135,104 +2413,133 @@ function getCandidateTypeCodesForKey(key) {
3135
2413
  const base = pluralKey.slice(0, -1);
3136
2414
  pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
3137
2415
  }
3138
- return candidates;
2416
+ return candidates;
2417
+ }
2418
+ var getCandidatesForKey = getCandidateTypeCodesForKey;
2419
+ function resolveFieldTypeCodes(field, parent, state, sample) {
2420
+ if (isLinkedEntityCodeField(field)) {
2421
+ const fromApplies = linkedEntityMetadataTypeFromAppliesTo(
2422
+ readAppliesToTypeValue(parent)
2423
+ );
2424
+ if (fromApplies && state.probe(fromApplies) !== false) {
2425
+ return [fromApplies];
2426
+ }
2427
+ if (!fromApplies && state.hasCatalog) {
2428
+ const concrete = LINKED_ENTITY_CONCRETE_TYPES.filter(
2429
+ (typeCode) => state.probe(typeCode) === true
2430
+ );
2431
+ if (concrete.length > 0) {
2432
+ return concrete;
2433
+ }
2434
+ }
2435
+ }
2436
+ const candidates = getCandidatesForKey(field);
2437
+ if (state.hasCatalog) {
2438
+ return candidates.filter((candidate) => state.probe(candidate) === true);
2439
+ }
2440
+ if ("labelKey" in sample || /code$/i.test(field)) {
2441
+ return candidates[0] ? [candidates[0]] : [];
2442
+ }
2443
+ return [];
3139
2444
  }
3140
- var getCandidatesForKey = getCandidateTypeCodesForKey;
3141
- function walk(value, typeCodes, references, visited, excludedCodeFields, knownSet, currentPath = "", diagnostics) {
2445
+ function walk(value, state, depth) {
3142
2446
  if (value === null || value === void 0) {
3143
2447
  return;
3144
2448
  }
3145
2449
  if (typeof value !== "object") {
3146
2450
  return;
3147
2451
  }
3148
- if (visited.has(value)) {
2452
+ if (depth > METADATA_TRAVERSAL_MAX_DEPTH || state.nodes >= METADATA_TRAVERSAL_MAX_NODES) {
2453
+ return;
2454
+ }
2455
+ if (state.visited.has(value)) {
3149
2456
  return;
3150
2457
  }
3151
- visited.add(value);
2458
+ state.visited.add(value);
2459
+ state.nodes += 1;
3152
2460
  if (Array.isArray(value)) {
3153
2461
  for (const item of value) {
3154
- walk(item, typeCodes, references, visited, excludedCodeFields, knownSet);
2462
+ walk(item, state, depth + 1);
3155
2463
  }
3156
2464
  return;
3157
2465
  }
3158
2466
  if (isMetadataReference(value)) {
3159
- addReference(value.typeCode, value.valueCode, typeCodes, references);
2467
+ addReference(value.typeCode, value.valueCode, state.typeCodes, state.references);
3160
2468
  }
3161
2469
  const record = value;
3162
2470
  if (record["ref"] === "META" && typeof record["typeCode"] === "string") {
3163
2471
  const valCode = typeof record["valueCode"] === "string" ? record["valueCode"] : "";
3164
- addReference(record["typeCode"], valCode, typeCodes, references);
2472
+ addReference(record["typeCode"], valCode, state.typeCodes, state.references);
3165
2473
  }
3166
2474
  for (const [field, child] of Object.entries(record)) {
3167
- if (excludedCodeFields.has(field)) {
2475
+ if (state.excludedCodeFields.has(field)) {
3168
2476
  continue;
3169
2477
  }
3170
- if (field.includes("__Code")) {
2478
+ if (field.length > 6 && field.toLowerCase().endsWith("__code")) {
3171
2479
  continue;
3172
2480
  }
3173
2481
  if (NON_METADATA_KEYS.has(field)) {
3174
- walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
2482
+ walk(child, state, depth + 1);
3175
2483
  continue;
3176
2484
  }
3177
2485
  if (isWorkflowStepRuleField(field, record)) {
3178
2486
  if (typeof child === "object" && child !== null) {
3179
- walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
2487
+ walk(child, state, depth + 1);
3180
2488
  }
3181
2489
  continue;
3182
2490
  }
3183
- if (isMetadataValueObject(child)) {
3184
- const candidates = getCandidatesForKey(field);
3185
- let matchedType;
3186
- if (knownSet) {
3187
- matchedType = candidates.find((c) => knownSet.has(c));
3188
- } else if ("labelKey" in child || field.endsWith("Code")) {
3189
- matchedType = candidates[0];
3190
- }
3191
- if (matchedType) {
3192
- addReference(matchedType, child.value, typeCodes, references);
3193
- continue;
3194
- }
2491
+ if (isTemplateRuleConfiguration(field, child)) {
2492
+ continue;
3195
2493
  }
3196
- if (isMetadataValueObjectArray(child)) {
3197
- const candidates = getCandidatesForKey(field);
3198
- let matchedType;
3199
- if (knownSet) {
3200
- matchedType = candidates.find((c) => knownSet.has(c));
3201
- } else if (child.some((item) => "labelKey" in item) || field.endsWith("Code")) {
3202
- matchedType = candidates[0];
2494
+ if (isMetadataValueObject(child)) {
2495
+ for (const matchedType of resolveFieldTypeCodes(field, record, state, child)) {
2496
+ addReference(matchedType, child.value, state.typeCodes, state.references);
3203
2497
  }
3204
- if (matchedType) {
2498
+ } else if (isMetadataValueObjectArray(child)) {
2499
+ const matchedTypes = resolveFieldTypeCodes(field, record, state, child[0]);
2500
+ if (matchedTypes.length > 0) {
3205
2501
  for (const item of child) {
3206
- addReference(matchedType, item.value, typeCodes, references);
2502
+ for (const matchedType of matchedTypes) {
2503
+ addReference(matchedType, item.value, state.typeCodes, state.references);
2504
+ }
3207
2505
  }
3208
- continue;
3209
2506
  }
3210
2507
  }
3211
2508
  collectStringCodeField(
3212
2509
  field,
3213
2510
  child,
3214
- typeCodes,
3215
- references,
3216
- excludedCodeFields
2511
+ state.typeCodes,
2512
+ state.references,
2513
+ state.excludedCodeFields
3217
2514
  );
3218
- if (knownSet) {
3219
- const candidates = getCandidatesForKey(field);
3220
- for (const cand of candidates) {
3221
- if (knownSet.has(cand)) {
3222
- if (typeof child === "string" && child.trim().length > 0) {
3223
- addReference(cand, child, typeCodes, references);
3224
- break;
3225
- }
3226
- if (Array.isArray(child) && child.length > 0 && child.every((c) => typeof c === "string")) {
3227
- for (const item of child) {
3228
- addReference(cand, item, typeCodes, references);
3229
- }
3230
- break;
2515
+ if (state.hasCatalog) {
2516
+ if (typeof child === "string" && child.trim().length > 0) {
2517
+ for (const matchedType of resolveFieldTypeCodes(
2518
+ field,
2519
+ record,
2520
+ state,
2521
+ { value: child.trim() }
2522
+ )) {
2523
+ addReference(matchedType, child, state.typeCodes, state.references);
2524
+ }
2525
+ } else if (Array.isArray(child) && child.length > 0 && child.every((item) => typeof item === "string" && item.trim().length > 0)) {
2526
+ const sample = String(child[0]).trim();
2527
+ const matchedTypes = resolveFieldTypeCodes(field, record, state, {
2528
+ value: sample
2529
+ });
2530
+ for (const item of child) {
2531
+ for (const matchedType of matchedTypes) {
2532
+ addReference(
2533
+ matchedType,
2534
+ String(item),
2535
+ state.typeCodes,
2536
+ state.references
2537
+ );
3231
2538
  }
3232
2539
  }
3233
2540
  }
3234
2541
  }
3235
- walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
2542
+ walk(child, state, depth + 1);
3236
2543
  }
3237
2544
  }
3238
2545
  function collectStringCodeField(field, child, typeCodes, references, excludedCodeFields) {
@@ -3360,7 +2667,7 @@ function readModelGroupsFromManifest(manifest) {
3360
2667
  metadata: metadataGroupFromManifest(manifest)
3361
2668
  };
3362
2669
  }
3363
- var projectionTypeSchema2 = z.string().min(1);
2670
+ var projectionTypeSchema = z.string().min(1);
3364
2671
  var manifestLocalizationSchema = z.object({
3365
2672
  defaultLocale: z.string().min(1),
3366
2673
  supportedLocales: z.array(z.string().min(1)),
@@ -3378,7 +2685,7 @@ var projectionManifestSchema = z.object({
3378
2685
  files: z.array(
3379
2686
  z.object({
3380
2687
  fileName: z.string().min(1),
3381
- projectionType: projectionTypeSchema2,
2688
+ projectionType: projectionTypeSchema,
3382
2689
  contentHash: z.string().min(1),
3383
2690
  itemCount: z.number().int().nonnegative()
3384
2691
  })
@@ -3449,8 +2756,8 @@ var MetadataLoader = class {
3449
2756
  )
3450
2757
  )
3451
2758
  ].sort();
3452
- this.logger.info({
3453
- event: RUNTIME_METADATA_EVENTS.MANIFEST_LOADED,
2759
+ const logs = createOperationalLogger(this.logger);
2760
+ logs.info(RUNTIME_METADATA_EVENTS.MANIFEST_LOADED, {
3454
2761
  releaseId: manifest.releaseId,
3455
2762
  revision: manifest.revision,
3456
2763
  contentHash: manifest.contentHash,
@@ -3458,18 +2765,12 @@ var MetadataLoader = class {
3458
2765
  metadataTypeCount: metadataTypes.length,
3459
2766
  lookupIndexSize: Object.keys(manifest.lookupIndex).length
3460
2767
  });
3461
- this.logger.info({
3462
- event: RUNTIME_METADATA_EVENTS.PROJECTION_MANIFEST_LOADED,
2768
+ logs.debug(RUNTIME_METADATA_EVENTS.PROJECTION_MANIFEST_LOADED, () => ({
3463
2769
  releaseId: manifest.releaseId,
3464
- metadataTypes,
3465
- lookupIndex: lookupIndexTypes,
3466
- lookupIndexSize: Object.keys(manifest.lookupIndex).length,
3467
- files: manifest.files.map((f) => ({
3468
- fileName: f.fileName,
3469
- projectionType: f.projectionType
3470
- })),
2770
+ metadataTypeCount: metadataTypes.length,
2771
+ lookupIndexTypeCount: lookupIndexTypes.length,
3471
2772
  consistent: metadataTypes.length === lookupIndexTypes.length && metadataTypes.every((t) => lookupIndexTypes.includes(t))
3472
- });
2773
+ }));
3473
2774
  return manifest;
3474
2775
  }
3475
2776
  /**
@@ -3678,11 +2979,10 @@ var MetadataDownloader = class {
3678
2979
  const timer = createPerformanceTimer("runtimeMetadata.downloadBootstrap");
3679
2980
  const releaseId = manifest.releaseId;
3680
2981
  const manifestFileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.MANIFEST];
3681
- this.logger.info({
3682
- event: RUNTIME_METADATA_EVENTS.DOWNLOAD_START,
2982
+ const logs = createOperationalLogger(this.logger);
2983
+ const started = Date.now();
2984
+ logs.debug(RUNTIME_METADATA_EVENTS.DOWNLOAD_START, {
3683
2985
  releaseId,
3684
- revision: releaseId,
3685
- fileCount: 0,
3686
2986
  mode: "bootstrap"
3687
2987
  });
3688
2988
  try {
@@ -3716,13 +3016,12 @@ var MetadataDownloader = class {
3716
3016
  loadedFiles.push(relativePath);
3717
3017
  }
3718
3018
  } catch (locErr) {
3719
- this.logger.warn({
3720
- event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED,
3019
+ logs.warn(RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED, {
3721
3020
  releaseId,
3722
3021
  locale,
3723
3022
  relativePath,
3724
3023
  reason: "localizationFileDownloadFailed",
3725
- err: locErr instanceof Error ? locErr.message : String(locErr)
3024
+ message: locErr instanceof Error ? locErr.message : String(locErr)
3726
3025
  });
3727
3026
  }
3728
3027
  })
@@ -3739,21 +3038,21 @@ var MetadataDownloader = class {
3739
3038
  localization: localization.size > 0 ? localization : void 0,
3740
3039
  downloadedAt: (/* @__PURE__ */ new Date()).toISOString()
3741
3040
  };
3742
- this.logger.info({
3743
- event: RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE,
3041
+ logs.info(RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE, {
3744
3042
  releaseId,
3745
- loadedFiles: bundle.loadedFiles,
3746
- mode: "bootstrap"
3043
+ loadedFileCount: bundle.loadedFiles.length,
3044
+ mode: "bootstrap",
3045
+ durationMs: Date.now() - started
3747
3046
  });
3748
3047
  timer.end();
3749
3048
  return bundle;
3750
3049
  } catch (err) {
3751
3050
  timer.end();
3752
- this.logger.error({
3753
- event: RUNTIME_METADATA_EVENTS.DOWNLOAD_FAILED,
3051
+ logs.error(RUNTIME_METADATA_EVENTS.DOWNLOAD_FAILED, {
3754
3052
  err: err instanceof Error ? err : void 0,
3755
3053
  releaseId,
3756
- mode: "bootstrap"
3054
+ mode: "bootstrap",
3055
+ durationMs: Date.now() - started
3757
3056
  });
3758
3057
  if (err instanceof ProjectionDownloadError || err instanceof RuntimeMetadataError) {
3759
3058
  throw err;
@@ -3786,21 +3085,19 @@ var MetadataDownloader = class {
3786
3085
  const integrityByFileName = new Map(
3787
3086
  manifest.files.map((f) => [f.fileName, f])
3788
3087
  );
3789
- this.logger.info({
3790
- event: RUNTIME_METADATA_EVENTS.DOWNLOAD_START,
3088
+ const logs = createOperationalLogger(this.logger);
3089
+ const started = Date.now();
3090
+ logs.debug(RUNTIME_METADATA_EVENTS.DOWNLOAD_START, {
3791
3091
  releaseId,
3792
- revision: releaseId,
3793
3092
  fileCount: uniqueTypeCodes.length,
3794
- mode: "selective",
3795
- metadataTypes: uniqueTypeCodes
3093
+ mode: "selective"
3796
3094
  });
3797
3095
  const results = await Promise.all(
3798
3096
  uniqueTypeCodes.map(async (metadataTypeCode) => {
3799
3097
  const fileName = projectionFileName(metadataTypeCode);
3800
3098
  const entry = integrityByFileName.get(fileName);
3801
3099
  if (!entry) {
3802
- this.logger.warn({
3803
- event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED,
3100
+ logs.warn(RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED, {
3804
3101
  metadataTypeCode,
3805
3102
  projectionFile: fileName,
3806
3103
  releaseId,
@@ -3809,14 +3106,6 @@ var MetadataDownloader = class {
3809
3106
  });
3810
3107
  return null;
3811
3108
  }
3812
- this.logger.info({
3813
- event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_LOADING,
3814
- releaseId,
3815
- metadataType: metadataTypeCode,
3816
- projectionFile: fileName,
3817
- projectionType: entry.projectionType,
3818
- mode: "selective"
3819
- });
3820
3109
  const body = await this.getObjectBody(
3821
3110
  this.buildKey(releaseId, fileName)
3822
3111
  );
@@ -3844,31 +3133,14 @@ var MetadataDownloader = class {
3844
3133
  );
3845
3134
  loadedFiles.push(fileName);
3846
3135
  domainFiles.set(metadataTypeCode, file);
3847
- const recordCount = typeof file.records === "object" && file.records ? Object.keys(file.records).length : 0;
3848
- this.logger.info({
3849
- event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_LOADED,
3850
- releaseId,
3851
- metadataType: metadataTypeCode,
3852
- projectionFile: fileName,
3853
- recordCount,
3854
- fileEnvelopeMetadataType: file.metadataType,
3855
- mode: "selective"
3856
- });
3857
- this.logger.info({
3858
- event: RUNTIME_METADATA_EVENTS.PROJECTION_CACHE_REGISTER,
3859
- releaseId,
3860
- metadataType: metadataTypeCode,
3861
- cacheSize: domainFiles.size,
3862
- projectionFile: fileName,
3863
- mode: "selective"
3864
- });
3865
3136
  }
3866
3137
  const sortedLoadedFiles = loadedFiles.sort((a, b) => a.localeCompare(b));
3867
- this.logger.info({
3868
- event: RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE,
3138
+ logs.info(RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE, {
3869
3139
  releaseId,
3870
- loadedFiles: sortedLoadedFiles,
3871
- mode: "selective"
3140
+ loadedFileCount: sortedLoadedFiles.length,
3141
+ requested: uniqueTypeCodes.length,
3142
+ mode: "selective",
3143
+ durationMs: Date.now() - started
3872
3144
  });
3873
3145
  return {
3874
3146
  domainFiles,
@@ -4113,7 +3385,15 @@ var MetadataCache = class {
4113
3385
  this.status = status;
4114
3386
  }
4115
3387
  isReady() {
4116
- return this.snapshot !== null && this.status !== CACHE_STATUS.EMPTY;
3388
+ if (this.snapshot === null || this.status === CACHE_STATUS.EMPTY) {
3389
+ return false;
3390
+ }
3391
+ const metadataTypes = this.snapshot.manifest?.metadataTypes;
3392
+ return metadataTypes != null && Object.keys(metadataTypes).length > 0;
3393
+ }
3394
+ hasCatalog() {
3395
+ const metadataTypes = this.snapshot?.manifest?.metadataTypes;
3396
+ return metadataTypes != null && Object.keys(metadataTypes).length > 0;
4117
3397
  }
4118
3398
  getSnapshot() {
4119
3399
  return this.snapshot;
@@ -4216,7 +3496,8 @@ var MetadataCache = class {
4216
3496
  ) : void 0
4217
3497
  });
4218
3498
  this.snapshot = snapshot;
4219
- this.status = CACHE_STATUS.READY;
3499
+ const typeCount = Object.keys(snapshot.manifest.metadataTypes).length;
3500
+ this.status = typeCount > 0 ? CACHE_STATUS.READY : CACHE_STATUS.EMPTY;
4220
3501
  return snapshot;
4221
3502
  }
4222
3503
  /**
@@ -4291,7 +3572,8 @@ var MetadataCache = class {
4291
3572
  /**
4292
3573
  * Merge individual resolved entries into domain record maps (same release).
4293
3574
  * Used after an extension batch lookup so {@link MetadataResolver.resolve}
4294
- * remains synchronous.
3575
+ * remains synchronous. Also updates lookupIndex and default-locale labels so
3576
+ * cache-only helpers work from extension-provided data.
4295
3577
  */
4296
3578
  hydrateEntries(entries, guard) {
4297
3579
  if (!this.snapshot) {
@@ -4304,6 +3586,19 @@ var MetadataCache = class {
4304
3586
  return this.snapshot;
4305
3587
  }
4306
3588
  const byType = /* @__PURE__ */ new Map();
3589
+ const lookupIndex = { ...this.snapshot.manifest.lookupIndex };
3590
+ const defaultLocale = this.snapshot.manifest.localization?.defaultLocale ?? "en-US";
3591
+ const localization = new Map(
3592
+ [...this.snapshot.localization?.entries() ?? []].map(([locale, map]) => [
3593
+ locale,
3594
+ new Map(map)
3595
+ ])
3596
+ );
3597
+ let localeMap = localization.get(defaultLocale);
3598
+ if (!localeMap) {
3599
+ localeMap = /* @__PURE__ */ new Map();
3600
+ localization.set(defaultLocale, localeMap);
3601
+ }
4307
3602
  for (const item of entries) {
4308
3603
  let typeMap = byType.get(item.typeCode);
4309
3604
  if (!typeMap) {
@@ -4311,6 +3606,16 @@ var MetadataCache = class {
4311
3606
  byType.set(item.typeCode, typeMap);
4312
3607
  }
4313
3608
  typeMap.set(item.valueCode, item.entry);
3609
+ const key = lookupIndexKey(item.typeCode, item.valueCode);
3610
+ lookupIndex[key] = {
3611
+ typeCode: item.typeCode,
3612
+ valueCode: item.valueCode,
3613
+ projectionFile: projectionFileName(item.typeCode)
3614
+ };
3615
+ const label = item.localizedLabel?.trim() || item.entry.label?.trim() || item.entry.displayName?.trim();
3616
+ if (label) {
3617
+ localeMap.set(`${item.typeCode}.${item.valueCode}`, label);
3618
+ }
4314
3619
  }
4315
3620
  const mergedDomain = new Map(this.snapshot.domainFiles);
4316
3621
  const additionalFiles = [];
@@ -4343,10 +3648,81 @@ var MetadataCache = class {
4343
3648
  .../* @__PURE__ */ new Set([...this.snapshot.loadedFiles, ...additionalFiles])
4344
3649
  ].sort((a, b) => a.localeCompare(b))
4345
3650
  );
3651
+ const existingLocalization = this.snapshot.manifest.localization;
3652
+ const supportedLocales = [
3653
+ .../* @__PURE__ */ new Set([
3654
+ ...existingLocalization?.supportedLocales ?? [],
3655
+ ...localization.keys()
3656
+ ])
3657
+ ].sort((a, b) => a.localeCompare(b));
4346
3658
  const snapshot = Object.freeze({
4347
3659
  ...this.snapshot,
4348
3660
  domainFiles: mergedDomain,
4349
- loadedFiles
3661
+ loadedFiles,
3662
+ manifest: Object.freeze({
3663
+ ...this.snapshot.manifest,
3664
+ lookupIndex: Object.freeze({ ...lookupIndex }),
3665
+ localization: Object.freeze({
3666
+ defaultLocale,
3667
+ supportedLocales,
3668
+ files: Object.freeze({
3669
+ ...existingLocalization?.files ?? {},
3670
+ ...Object.fromEntries(
3671
+ supportedLocales.map((locale) => [
3672
+ locale,
3673
+ existingLocalization?.files?.[locale] ?? `localization/${locale}.json`
3674
+ ])
3675
+ )
3676
+ })
3677
+ })
3678
+ }),
3679
+ localization: Object.freeze(
3680
+ new Map(
3681
+ [...localization.entries()].map(([locale, map]) => [
3682
+ locale,
3683
+ Object.freeze(new Map(map))
3684
+ ])
3685
+ )
3686
+ )
3687
+ });
3688
+ this.snapshot = snapshot;
3689
+ this.status = CACHE_STATUS.READY;
3690
+ return snapshot;
3691
+ }
3692
+ /**
3693
+ * Merge type-catalog fields (e.g. valueDataType) into the synthetic extension
3694
+ * manifest so synchronous helpers can read them after listTypeValues.
3695
+ */
3696
+ mergeTypeCatalog(types, guard) {
3697
+ if (!this.snapshot) {
3698
+ throw new Error("Cannot merge type catalog into an empty metadata cache");
3699
+ }
3700
+ if (Object.keys(types).length === 0) {
3701
+ return this.snapshot;
3702
+ }
3703
+ if (!this.guardAllowsWrite(guard)) {
3704
+ return this.snapshot;
3705
+ }
3706
+ const metadataTypes = { ...this.snapshot.manifest.metadataTypes };
3707
+ for (const [typeCode, entry] of Object.entries(types)) {
3708
+ const existing = metadataTypes[typeCode];
3709
+ metadataTypes[typeCode] = {
3710
+ ...existing ?? {},
3711
+ ...entry,
3712
+ typeCode: entry.typeCode || typeCode,
3713
+ projectionFile: entry.projectionFile || existing?.projectionFile || `${typeCode}.json`,
3714
+ localizedDisplayName: {
3715
+ ...existing?.localizedDisplayName ?? {},
3716
+ ...entry.localizedDisplayName ?? {}
3717
+ }
3718
+ };
3719
+ }
3720
+ const snapshot = Object.freeze({
3721
+ ...this.snapshot,
3722
+ manifest: Object.freeze({
3723
+ ...this.snapshot.manifest,
3724
+ metadataTypes: Object.freeze(metadataTypes)
3725
+ })
4350
3726
  });
4351
3727
  this.snapshot = snapshot;
4352
3728
  this.status = CACHE_STATUS.READY;
@@ -4367,8 +3743,6 @@ var MetadataCache = class {
4367
3743
  return guard.generation === this.generation && guard.releaseId === this.snapshot.releaseId;
4368
3744
  }
4369
3745
  };
4370
-
4371
- // ../../libs/runtime-metadata/src/lib/resolver/MetadataResolver.ts
4372
3746
  var MetadataResolver = class {
4373
3747
  cache;
4374
3748
  logger;
@@ -4403,9 +3777,7 @@ var MetadataResolver = class {
4403
3777
  * Falls back to default locale if requested locale does not have the key.
4404
3778
  */
4405
3779
  resolveLocalization(typeCode, valueCode, locale) {
4406
- if (!this.cache.isReady()) {
4407
- return void 0;
4408
- }
3780
+ this.assertReady();
4409
3781
  const targetLocale = locale?.trim() || this.cache.getManifest()?.localization?.defaultLocale || "en-US";
4410
3782
  const locMap = this.cache.getLocalizationMap(targetLocale);
4411
3783
  const key = `${typeCode}.${valueCode}`;
@@ -4419,15 +3791,22 @@ var MetadataResolver = class {
4419
3791
  return defaultMap.get(key);
4420
3792
  }
4421
3793
  }
3794
+ const file = this.cache.getDomainFile(typeCode);
3795
+ const record = file?.records[valueCode];
3796
+ const entry = record?.versions[String(record.latestVersion)];
3797
+ if (entry) {
3798
+ const fromEntry = entry.localizedLabels?.[targetLocale] || entry.localizedLabels?.[defaultLocale] || entry.label || entry.displayName;
3799
+ if (fromEntry?.trim()) {
3800
+ return fromEntry.trim();
3801
+ }
3802
+ }
4422
3803
  return void 0;
4423
3804
  }
4424
3805
  /**
4425
3806
  * Look up localized display name for a MetadataType from manifest or domain file.
4426
3807
  */
4427
3808
  getTypeLocalizedDisplayName(typeCode, locale) {
4428
- if (!this.cache.isReady()) {
4429
- return void 0;
4430
- }
3809
+ this.assertReady();
4431
3810
  const targetType = this.resolveMetadataTypeCode(typeCode);
4432
3811
  if (!targetType) {
4433
3812
  return void 0;
@@ -4452,9 +3831,7 @@ var MetadataResolver = class {
4452
3831
  * Value data type for a MetadataType (e.g. STRING, INTEGER).
4453
3832
  */
4454
3833
  getValueDataType(typeCode) {
4455
- if (!this.cache.isReady()) {
4456
- return void 0;
4457
- }
3834
+ this.assertReady();
4458
3835
  const targetType = this.resolveMetadataTypeCode(typeCode);
4459
3836
  if (!targetType) {
4460
3837
  return void 0;
@@ -4462,7 +3839,16 @@ var MetadataResolver = class {
4462
3839
  const manifest = this.cache.getManifest();
4463
3840
  const manifestType = manifest?.metadataTypes[targetType];
4464
3841
  const file = this.cache.getDomainFile(targetType);
4465
- return manifestType?.valueDataType ?? file?.valueDataType;
3842
+ const valueDataType = manifestType?.valueDataType ?? file?.valueDataType;
3843
+ if (valueDataType != null && valueDataType !== "") {
3844
+ return valueDataType;
3845
+ }
3846
+ if (!file) {
3847
+ throw new MetadataNotReadyError(
3848
+ `Metadata type catalog is not loaded for ${targetType}`
3849
+ );
3850
+ }
3851
+ return void 0;
4466
3852
  }
4467
3853
  /**
4468
3854
  * Whether the given MetadataTypeCode is listed in the loaded manifest.
@@ -4470,30 +3856,17 @@ var MetadataResolver = class {
4470
3856
  */
4471
3857
  supportsType(typeCode) {
4472
3858
  const requestedType = typeCode?.trim() ?? "";
4473
- if (!this.cache.isReady()) {
4474
- this.logger.info({
4475
- event: RUNTIME_METADATA_EVENTS.PROJECTION_PROVIDER_SUPPORTS_TYPE,
4476
- requestedType,
4477
- supported: false,
4478
- availableTypes: [],
4479
- reason: "cacheNotReady",
4480
- cacheStatus: this.cache.getStatus()
4481
- });
3859
+ const normalizedType = normalizeRuntimeMetadataTypeCode(requestedType);
3860
+ const metadataTypes = this.cache.getManifest()?.metadataTypes;
3861
+ const availableTypeCount = metadataTypes ? Object.keys(metadataTypes).length : 0;
3862
+ const cacheReady = this.cache.isReady();
3863
+ const catalogAvailable = cacheReady && availableTypeCount > 0;
3864
+ if (!catalogAvailable) {
4482
3865
  return false;
4483
3866
  }
4484
- const supported = this.resolveMetadataTypeCode(requestedType) !== void 0;
4485
- const availableTypes = Object.keys(
4486
- this.cache.getManifest()?.metadataTypes ?? {}
4487
- ).sort();
4488
- this.logger.info({
4489
- event: RUNTIME_METADATA_EVENTS.PROJECTION_PROVIDER_SUPPORTS_TYPE,
4490
- requestedType,
4491
- supported,
4492
- availableTypes: availableTypes.length,
4493
- cacheStatus: this.cache.getStatus(),
4494
- releaseId: this.cache.getReleaseId()
4495
- });
4496
- return supported;
3867
+ return Boolean(
3868
+ normalizedType && metadataTypes && normalizedType in metadataTypes
3869
+ );
4497
3870
  }
4498
3871
  /** MetadataTypeCodes available for resolve (from manifest.metadataTypes). */
4499
3872
  listMetadataTypes() {
@@ -4558,17 +3931,13 @@ var MetadataResolver = class {
4558
3931
  requireSupportedType(metadataType) {
4559
3932
  const metadataTypeCode = this.resolveMetadataTypeCode(metadataType);
4560
3933
  if (!metadataTypeCode) {
4561
- const availableTypes = Object.keys(
4562
- this.cache.getManifest()?.metadataTypes ?? {}
4563
- ).sort();
4564
3934
  const trimmed = metadataType?.trim() ?? "";
4565
- this.logger.warn({
4566
- event: RUNTIME_METADATA_EVENTS.LOOKUP_MISS,
3935
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.LOOKUP_MISS, () => ({
4567
3936
  metadataType,
4568
3937
  metadataTypeCode: trimmed,
4569
- availableTypes,
3938
+ availableTypeCount: Object.keys(this.cache.getManifest()?.metadataTypes ?? {}).length,
4570
3939
  message: "Unknown metadata type"
4571
- });
3940
+ }));
4572
3941
  throw new UnknownMetadataTypeError(metadataType);
4573
3942
  }
4574
3943
  return metadataTypeCode;
@@ -4589,8 +3958,7 @@ var MetadataResolver = class {
4589
3958
  requireEntry(metadataTypeCode, code, version) {
4590
3959
  const entry = this.lookupEntry(metadataTypeCode, code, version);
4591
3960
  if (!entry) {
4592
- this.logger.warn({
4593
- event: RUNTIME_METADATA_EVENTS.LOOKUP_MISS,
3961
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.LOOKUP_MISS, {
4594
3962
  projectionType: metadataTypeCode,
4595
3963
  code,
4596
3964
  version: version ?? null
@@ -4634,8 +4002,6 @@ var MetadataResolver = class {
4634
4002
  }
4635
4003
  }
4636
4004
  };
4637
-
4638
- // ../../libs/runtime-metadata/src/lib/refresh/MetadataRefreshService.ts
4639
4005
  var MetadataRefreshService = class {
4640
4006
  cache;
4641
4007
  downloader;
@@ -4667,8 +4033,9 @@ var MetadataRefreshService = class {
4667
4033
  */
4668
4034
  async initialize(revision) {
4669
4035
  const target = revision?.trim() || this.configuredRevision || await this.downloader.discoverLatestRevision();
4670
- this.logger.info({
4671
- event: RUNTIME_METADATA_EVENTS.INIT_START,
4036
+ const logs = createOperationalLogger(this.logger);
4037
+ const started = Date.now();
4038
+ logs.debug(RUNTIME_METADATA_EVENTS.INIT_START, {
4672
4039
  revision: target
4673
4040
  });
4674
4041
  try {
@@ -4676,35 +4043,33 @@ var MetadataRefreshService = class {
4676
4043
  this.cache.replace(bundle);
4677
4044
  this.refreshStatus = REFRESH_STATUS.SUCCEEDED;
4678
4045
  this.lastRefreshError = null;
4679
- const loadedTypes = Object.keys(bundle.manifest.metadataTypes).sort();
4680
- const domainFileTypes = [...bundle.domainFiles.keys()].sort();
4681
- this.logger.info({
4682
- event: RUNTIME_METADATA_EVENTS.INIT_COMPLETE,
4046
+ const loadedTypes = Object.keys(bundle.manifest.metadataTypes);
4047
+ const lookupIndexTypes = new Set(
4048
+ Object.keys(bundle.manifest.lookupIndex).map(
4049
+ (key) => key.split(":")[0] ?? key
4050
+ )
4051
+ );
4052
+ logs.info(RUNTIME_METADATA_EVENTS.INIT_COMPLETE, {
4053
+ releaseId: bundle.releaseId,
4683
4054
  revision: bundle.releaseId,
4684
4055
  contentHash: bundle.manifest.contentHash,
4685
- loadedFiles: bundle.loadedFiles,
4686
- mode: "bootstrap"
4056
+ mode: "bootstrap",
4057
+ durationMs: Date.now() - started,
4058
+ loadedFileCount: bundle.loadedFiles.length,
4059
+ metadataTypeCount: loadedTypes.length,
4060
+ domainFileCount: bundle.domainFiles.size,
4061
+ lookupIndexTypeCount: lookupIndexTypes.size
4687
4062
  });
4688
- this.logger.info({
4689
- event: RUNTIME_METADATA_EVENTS.RUNTIME_METADATA_INITIALIZED,
4063
+ logs.debug(RUNTIME_METADATA_EVENTS.RUNTIME_METADATA_INITIALIZED, () => ({
4690
4064
  releaseId: bundle.releaseId,
4691
- loadedTypes,
4692
- domainFileTypes,
4693
- lookupIndexTypes: [
4694
- ...new Set(
4695
- Object.keys(bundle.manifest.lookupIndex).map(
4696
- (key) => key.split(":")[0] ?? key
4697
- )
4698
- )
4699
- ].sort(),
4700
- hasMetric: loadedTypes.includes("MetricCode"),
4701
- metadataTypesMetricEntry: bundle.manifest.metadataTypes["MetricCode"] ?? null
4702
- });
4065
+ loadedTypes: [...loadedTypes].sort(),
4066
+ domainFileTypes: [...bundle.domainFiles.keys()].sort(),
4067
+ lookupIndexTypeCount: lookupIndexTypes.size
4068
+ }));
4703
4069
  } catch (err) {
4704
4070
  this.refreshStatus = REFRESH_STATUS.FAILED;
4705
4071
  this.lastRefreshError = err instanceof Error ? err.message : String(err);
4706
- this.logger.error({
4707
- event: RUNTIME_METADATA_EVENTS.INIT_FAILED,
4072
+ createOperationalLogger(this.logger).error(RUNTIME_METADATA_EVENTS.INIT_FAILED, {
4708
4073
  err: err instanceof Error ? err : void 0,
4709
4074
  revision: target,
4710
4075
  message: this.lastRefreshError
@@ -4726,8 +4091,9 @@ var MetadataRefreshService = class {
4726
4091
  async checkAndRefresh(preferredRevision) {
4727
4092
  const current = this.cache.getManifest();
4728
4093
  const target = preferredRevision?.trim() || this.configuredRevision || await this.downloader.discoverLatestRevision();
4729
- this.logger.info({
4730
- event: RUNTIME_METADATA_EVENTS.PERIODIC_CHECK,
4094
+ const logs = createOperationalLogger(this.logger);
4095
+ const started = Date.now();
4096
+ logs.debug(RUNTIME_METADATA_EVENTS.PERIODIC_CHECK, {
4731
4097
  revision: target,
4732
4098
  currentRevision: current?.revision ?? null
4733
4099
  });
@@ -4735,11 +4101,10 @@ var MetadataRefreshService = class {
4735
4101
  const nextManifest = await this.downloader.downloadManifest(target);
4736
4102
  const comparison = this.loader.compare(current, nextManifest);
4737
4103
  if (!comparison.changed) {
4738
- this.logger.info({
4739
- event: RUNTIME_METADATA_EVENTS.REFRESH_SKIPPED,
4104
+ logs.debug(RUNTIME_METADATA_EVENTS.REFRESH_SKIPPED, {
4740
4105
  reason: "unchanged",
4741
4106
  revision: target,
4742
- contentHash: nextManifest.contentHash
4107
+ releaseId: nextManifest.releaseId
4743
4108
  });
4744
4109
  return false;
4745
4110
  }
@@ -4750,14 +4115,15 @@ var MetadataRefreshService = class {
4750
4115
  if (this.cache.isReady()) {
4751
4116
  this.cache.setStatus(CACHE_STATUS.DEGRADED);
4752
4117
  }
4753
- this.logger.error({
4754
- event: RUNTIME_METADATA_EVENTS.REFRESH_FAILED,
4118
+ createOperationalLogger(this.logger).error(RUNTIME_METADATA_EVENTS.REFRESH_FAILED, {
4755
4119
  err: err instanceof Error ? err : void 0,
4756
4120
  revision: target,
4757
4121
  message: this.lastRefreshError,
4758
- retainedCache: this.cache.isReady()
4122
+ retainedCache: this.cache.isReady(),
4123
+ durationMs: Date.now() - started,
4124
+ outcome: "error"
4759
4125
  });
4760
- return false;
4126
+ throw err;
4761
4127
  }
4762
4128
  }
4763
4129
  startPeriodicCheck(intervalMs) {
@@ -4766,7 +4132,7 @@ var MetadataRefreshService = class {
4766
4132
  return;
4767
4133
  }
4768
4134
  this.periodicTimer = setInterval(() => {
4769
- void this.checkAndRefresh();
4135
+ void this.checkAndRefresh().catch(() => void 0);
4770
4136
  }, intervalMs);
4771
4137
  if (typeof this.periodicTimer.unref === "function") {
4772
4138
  this.periodicTimer.unref();
@@ -4795,8 +4161,9 @@ var MetadataRefreshService = class {
4795
4161
  if (this.cache.isReady()) {
4796
4162
  this.cache.setStatus(CACHE_STATUS.REFRESHING);
4797
4163
  }
4798
- this.logger.info({
4799
- event: RUNTIME_METADATA_EVENTS.REFRESH_START,
4164
+ const logs = createOperationalLogger(this.logger);
4165
+ const started = Date.now();
4166
+ logs.debug(RUNTIME_METADATA_EVENTS.REFRESH_START, {
4800
4167
  revision: revision ?? "current",
4801
4168
  reason
4802
4169
  });
@@ -4821,16 +4188,25 @@ var MetadataRefreshService = class {
4821
4188
  this.cache.replace(bundle);
4822
4189
  this.refreshStatus = REFRESH_STATUS.SUCCEEDED;
4823
4190
  this.lastRefreshError = null;
4824
- this.logger.info({
4825
- event: RUNTIME_METADATA_EVENTS.REFRESH_COMPLETE,
4191
+ const durationMs = Date.now() - started;
4192
+ logs.info(RUNTIME_METADATA_EVENTS.REFRESH_COMPLETE, {
4826
4193
  revision: bundle.releaseId,
4827
4194
  oldReleaseId: previousReleaseId,
4828
4195
  newReleaseId: bundle.releaseId,
4829
- contentHash: bundle.manifest.contentHash,
4196
+ releaseId: bundle.releaseId,
4830
4197
  reason,
4831
4198
  mode: previousTypes.length > 0 ? "snapshot" : "bootstrap",
4832
- retainedDomainTypes: previousTypes
4199
+ retainedDomainCount: previousTypes.length,
4200
+ durationMs
4833
4201
  });
4202
+ if (durationMs >= logs.policy.slowRefreshMs) {
4203
+ logs.warn("runtimeMetadata.refresh.slow", {
4204
+ releaseId: bundle.releaseId,
4205
+ durationMs,
4206
+ thresholdMs: logs.policy.slowRefreshMs,
4207
+ reason
4208
+ });
4209
+ }
4834
4210
  return true;
4835
4211
  } catch (err) {
4836
4212
  this.refreshStatus = REFRESH_STATUS.FAILED;
@@ -4840,15 +4216,16 @@ var MetadataRefreshService = class {
4840
4216
  } else if (previousStatus !== CACHE_STATUS.REFRESHING) {
4841
4217
  this.cache.setStatus(previousStatus);
4842
4218
  }
4843
- this.logger.error({
4844
- event: RUNTIME_METADATA_EVENTS.REFRESH_FAILED,
4219
+ logs.error(RUNTIME_METADATA_EVENTS.REFRESH_FAILED, {
4845
4220
  err: err instanceof Error ? err : void 0,
4846
4221
  revision: revision ?? "current",
4847
4222
  reason,
4848
4223
  message: this.lastRefreshError,
4849
- retainedCache: this.cache.isReady()
4224
+ retainedCache: this.cache.isReady(),
4225
+ durationMs: Date.now() - started,
4226
+ outcome: "error"
4850
4227
  });
4851
- return false;
4228
+ throw err;
4852
4229
  }
4853
4230
  }
4854
4231
  };
@@ -4894,7 +4271,8 @@ var MetadataHealthService = class {
4894
4271
  var METADATA_EXTENSION_DEFAULTS = {
4895
4272
  HOST: "127.0.0.1",
4896
4273
  PORT: 12701,
4897
- FALLBACK: "s3",
4274
+ /** Consumers use the metadata extension exclusively; never silent S3 failover. */
4275
+ FALLBACK: "none",
4898
4276
  RECOVERY_INTERVAL_MS: 2e3,
4899
4277
  STARTUP_TIMEOUT_MS: 8e3,
4900
4278
  INVOKE_REFRESH_MS: 3e4,
@@ -4963,6 +4341,7 @@ var METADATA_RELATION_DIRECTION = {
4963
4341
  INCOMING: "INCOMING"
4964
4342
  };
4965
4343
  var METADATA_ATTRIBUTE_FILTER_KEY = PUBLISHED_VALUE_ATTRIBUTE_FILTER_KEY;
4344
+ var RELATIONSHIP_QUERY_BATCH_LIMIT = 100;
4966
4345
  function supportsMetadataDiscovery(provider) {
4967
4346
  const candidate = provider;
4968
4347
  return typeof candidate.listValuesByType === "function" && typeof candidate.getRelationships === "function" && typeof candidate.listValuesByTypes === "function";
@@ -4971,11 +4350,11 @@ function isFreshProjectionState(state) {
4971
4350
  return state?.trim().toLowerCase() === "ready";
4972
4351
  }
4973
4352
  function assertMetadataReadPolicy(policy, state, releaseId) {
4974
- const resolved2 = policy ?? METADATA_READ_POLICY.ALLOW_STALE;
4975
- if (resolved2 !== METADATA_READ_POLICY.ALLOW_STALE && resolved2 !== METADATA_READ_POLICY.REQUIRE_FRESH) {
4353
+ const resolved = policy ?? METADATA_READ_POLICY.ALLOW_STALE;
4354
+ if (resolved !== METADATA_READ_POLICY.ALLOW_STALE && resolved !== METADATA_READ_POLICY.REQUIRE_FRESH) {
4976
4355
  throw new MetadataDiscoveryError("Unsupported metadata read policy");
4977
4356
  }
4978
- if (resolved2 === METADATA_READ_POLICY.REQUIRE_FRESH && !isFreshProjectionState(state)) {
4357
+ if (resolved === METADATA_READ_POLICY.REQUIRE_FRESH && !isFreshProjectionState(state)) {
4979
4358
  throw new MetadataFreshnessError(state, releaseId);
4980
4359
  }
4981
4360
  }
@@ -5028,6 +4407,12 @@ var ExtensionMetadataProvider = class {
5028
4407
  requestTimeoutMs;
5029
4408
  logger;
5030
4409
  lifecycleSupport;
4410
+ /** Last release observed in READY state. Not a time-based cache. */
4411
+ verifiedFreshReleaseId = null;
4412
+ readinessCheckCount = 0;
4413
+ relationshipRequestCount = 0;
4414
+ pendingRelationships = [];
4415
+ relationshipFlushScheduled = false;
5031
4416
  fetchImpl;
5032
4417
  constructor(options) {
5033
4418
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
@@ -5054,12 +4439,12 @@ var ExtensionMetadataProvider = class {
5054
4439
  try {
5055
4440
  const status = await this.getStatus();
5056
4441
  if (isServingState(status.state) && status.releaseId) {
5057
- this.logger.info({
5058
- event: "templates.performance",
5059
- phase: "metadataExtension.ready",
4442
+ createOperationalLogger(this.logger).debug("metadataExtension.ready", {
5060
4443
  durationMs: Date.now() - started,
5061
4444
  attempts,
5062
- state: status.state
4445
+ state: status.state,
4446
+ releaseId: status.releaseId,
4447
+ ...correlationLogFields()
5063
4448
  });
5064
4449
  return status;
5065
4450
  }
@@ -5081,14 +4466,14 @@ var ExtensionMetadataProvider = class {
5081
4466
  const unreachable = lastError instanceof MetadataProjectionUnavailableError && lastError.metadata?.unreachable === true;
5082
4467
  const timedOut = detail.includes("timed out");
5083
4468
  const reason = timedOut ? "Metadata extension readiness timed out" : unreachable ? "Metadata extension connection was refused" : "Metadata extension did not become ready";
5084
- this.logger.warn({
5085
- event: "templates.performance",
5086
- phase: "metadataExtension.ready",
4469
+ createOperationalLogger(this.logger).warn("metadataExtension.ready", {
5087
4470
  durationMs: Date.now() - started,
5088
4471
  attempts,
5089
4472
  outcome: "unavailable",
5090
4473
  unreachable,
5091
- timedOut
4474
+ timedOut,
4475
+ timeoutMs: this.readyTimeoutMs,
4476
+ ...correlationLogFields()
5092
4477
  });
5093
4478
  throw new MetadataProjectionUnavailableError(
5094
4479
  detail ? `${reason}: ${detail}` : reason,
@@ -5104,13 +4489,21 @@ var ExtensionMetadataProvider = class {
5104
4489
  );
5105
4490
  }
5106
4491
  async getStatus() {
4492
+ this.readinessCheckCount += 1;
5107
4493
  const body = await this.requestJson(
5108
4494
  "GET",
5109
4495
  "/v1/status"
5110
4496
  );
4497
+ const state = body.state ?? "UNKNOWN";
4498
+ const releaseId = body.releaseId ?? null;
4499
+ if (isFreshProjectionState(state) && releaseId) {
4500
+ this.verifiedFreshReleaseId = releaseId;
4501
+ } else {
4502
+ this.verifiedFreshReleaseId = null;
4503
+ }
5111
4504
  return {
5112
- state: body.state ?? "UNKNOWN",
5113
- releaseId: body.releaseId ?? null,
4505
+ state,
4506
+ releaseId,
5114
4507
  lastError: body.lastError ?? null,
5115
4508
  loadedAt: body.loadedAt ?? null,
5116
4509
  lastRefreshAttemptAt: body.lastRefreshAttemptAt ?? null,
@@ -5247,7 +4640,7 @@ var ExtensionMetadataProvider = class {
5247
4640
  }
5248
4641
  }
5249
4642
  async listValuesByType(typeCode, options) {
5250
- await this.assertDiscoveryPolicy(options?.readPolicy);
4643
+ await this.assertDiscoveryPolicy(options?.readPolicy, options?.releaseId);
5251
4644
  const filter = await this.assertQueryLifecycle("values", { status: options?.status });
5252
4645
  const body = await this.requestJson("GET", `/v1/metadata/types/${encodeURIComponent(typeCode)}/values${discoveryQuery(options)}`);
5253
4646
  const items = Array.isArray(body.items) ? body.items : [];
@@ -5258,7 +4651,7 @@ var ExtensionMetadataProvider = class {
5258
4651
  };
5259
4652
  }
5260
4653
  async listValuesByTypes(typeCodes, options) {
5261
- await this.assertDiscoveryPolicy(options?.readPolicy);
4654
+ await this.assertDiscoveryPolicy(options?.readPolicy, options?.releaseId);
5262
4655
  const filter = await this.assertQueryLifecycle("values", { status: options?.status });
5263
4656
  const body = await this.requestJson(
5264
4657
  "POST",
@@ -5277,20 +4670,31 @@ var ExtensionMetadataProvider = class {
5277
4670
  };
5278
4671
  }
5279
4672
  async getRelationships(query) {
5280
- await this.assertDiscoveryPolicy(query.readPolicy);
5281
- const filter = await this.assertQueryLifecycle("relations", { status: query.status });
5282
- const body = await this.requestJson(
5283
- "POST",
5284
- "/v1/metadata/relationships/query",
5285
- query
5286
- );
4673
+ return new Promise((resolve, reject) => {
4674
+ this.pendingRelationships.push({ query, resolve, reject });
4675
+ this.scheduleRelationshipFlush();
4676
+ });
4677
+ }
4678
+ /**
4679
+ * One or more extension requests, chunked at {@link RELATIONSHIP_QUERY_BATCH_LIMIT}.
4680
+ * A single query uses the single-query route. Several queries use the batch route.
4681
+ */
4682
+ async queryRelationships(queries) {
4683
+ if (queries.length === 0) {
4684
+ return [];
4685
+ }
4686
+ const outcomes = await this.executeRelationshipGroup(queries);
4687
+ return outcomes.map((outcome) => {
4688
+ if (!outcome.ok) {
4689
+ throw outcome.error;
4690
+ }
4691
+ return outcome.result;
4692
+ });
4693
+ }
4694
+ getPerformanceCounters() {
5287
4695
  return {
5288
- releaseId: body.releaseId ?? null,
5289
- supported: body.supported === true,
5290
- relationships: lifecycleRows(
5291
- Array.isArray(body.relationships) ? body.relationships : [],
5292
- filter
5293
- )
4696
+ readinessCheckCount: this.readinessCheckCount,
4697
+ relationshipRequestCount: this.relationshipRequestCount
5294
4698
  };
5295
4699
  }
5296
4700
  async listRelations(query) {
@@ -5395,21 +4799,24 @@ var ExtensionMetadataProvider = class {
5395
4799
  try {
5396
4800
  const body = await this.requestJson("GET", path);
5397
4801
  return body.value;
5398
- } catch {
5399
- return void 0;
4802
+ } catch (err) {
4803
+ if (isNotFound(err)) return void 0;
4804
+ throw err;
5400
4805
  }
5401
4806
  }
5402
4807
  async getLocalizationMap(locale) {
5403
4808
  const path = `/v1/localization/${encodeURIComponent(locale)}`;
5404
4809
  try {
5405
4810
  const body = await this.requestJson("GET", path);
5406
- return body.items;
5407
- } catch {
5408
- return void 0;
4811
+ return body.items ?? {};
4812
+ } catch (err) {
4813
+ if (isNotFound(err)) return void 0;
4814
+ throw err;
5409
4815
  }
5410
4816
  }
5411
4817
  async requestRefresh(releaseId) {
5412
4818
  this.lifecycleSupport = void 0;
4819
+ this.verifiedFreshReleaseId = null;
5413
4820
  const body = await this.requestJson(
5414
4821
  "POST",
5415
4822
  "/v1/refresh",
@@ -5418,15 +4825,15 @@ var ExtensionMetadataProvider = class {
5418
4825
  return body.changed === true;
5419
4826
  }
5420
4827
  async assertQueryLifecycle(kind, options) {
5421
- const resolved2 = resolveMetadataStatusFilter({
4828
+ const resolved = resolveMetadataStatusFilter({
5422
4829
  status: options?.status,
5423
4830
  includeInactive: options?.includeInactive
5424
4831
  });
5425
- if (!resolved2.ok) {
5426
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
4832
+ if (!resolved.ok) {
4833
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
5427
4834
  }
5428
- if (!resolved2.enforceCapability) {
5429
- return resolved2.filter;
4835
+ if (!resolved.enforceCapability) {
4836
+ return resolved.filter;
5430
4837
  }
5431
4838
  if (!this.lifecycleSupport) {
5432
4839
  const status = await this.getStatus();
@@ -5441,53 +4848,271 @@ var ExtensionMetadataProvider = class {
5441
4848
  METADATA_LIFECYCLE_UNSUPPORTED
5442
4849
  );
5443
4850
  }
5444
- return resolved2.filter;
4851
+ return resolved.filter;
4852
+ }
4853
+ toMetadataValue(item, locale) {
4854
+ if (!item?.typeCode || !item.valueCode) {
4855
+ return null;
4856
+ }
4857
+ if (item.entry) {
4858
+ return projectionEntryToMetadataValue(
4859
+ item.typeCode,
4860
+ item.valueCode,
4861
+ item.entry,
4862
+ locale
4863
+ );
4864
+ }
4865
+ return {
4866
+ typeCode: item.typeCode,
4867
+ valueCode: item.valueCode,
4868
+ localizedLabel: item.localizedLabel,
4869
+ status: item.status,
4870
+ version: item.version,
4871
+ entry: {
4872
+ code: item.valueCode,
4873
+ displayName: item.localizedLabel,
4874
+ label: item.localizedLabel,
4875
+ status: item.status,
4876
+ version: item.version,
4877
+ sortOrder: 0,
4878
+ isGlobal: true,
4879
+ attributes: {},
4880
+ applicability: {
4881
+ module: [],
4882
+ category: [],
4883
+ condition: [],
4884
+ country: []
4885
+ }
4886
+ }
4887
+ };
4888
+ }
4889
+ async assertDiscoveryPolicy(readPolicy, releaseId) {
4890
+ if (readPolicy !== "REQUIRE_FRESH") {
4891
+ return;
4892
+ }
4893
+ if (releaseId && this.verifiedFreshReleaseId === releaseId) {
4894
+ return;
4895
+ }
4896
+ const status = await this.getStatus();
4897
+ assertMetadataReadPolicy(readPolicy, status.state, status.releaseId);
4898
+ assertReleasePin(releaseId, status.releaseId);
4899
+ }
4900
+ scheduleRelationshipFlush() {
4901
+ if (this.relationshipFlushScheduled) {
4902
+ return;
4903
+ }
4904
+ this.relationshipFlushScheduled = true;
4905
+ queueMicrotask(() => {
4906
+ this.relationshipFlushScheduled = false;
4907
+ const pending = this.pendingRelationships;
4908
+ this.pendingRelationships = [];
4909
+ void this.flushRelationships(pending);
4910
+ });
4911
+ }
4912
+ async flushRelationships(pending) {
4913
+ if (pending.length === 0) {
4914
+ return;
4915
+ }
4916
+ const groups = /* @__PURE__ */ new Map();
4917
+ for (const item of pending) {
4918
+ const key = `${item.query.readPolicy ?? ""}\0${item.query.releaseId ?? ""}`;
4919
+ const group = groups.get(key) ?? [];
4920
+ group.push(item);
4921
+ groups.set(key, group);
4922
+ }
4923
+ await Promise.all(
4924
+ [...groups.values()].map((group) => this.flushRelationshipGroup(group))
4925
+ );
4926
+ }
4927
+ async flushRelationshipGroup(group) {
4928
+ try {
4929
+ const outcomes = await this.executeRelationshipGroup(group.map((item) => item.query));
4930
+ group.forEach((item, index) => {
4931
+ const outcome = outcomes[index];
4932
+ if (!outcome?.ok) {
4933
+ item.reject(
4934
+ outcome?.error ?? new MetadataDiscoveryError("Metadata relationship batch returned no result")
4935
+ );
4936
+ return;
4937
+ }
4938
+ item.resolve(outcome.result);
4939
+ });
4940
+ } catch (error) {
4941
+ if (error instanceof MetadataFreshnessError || error instanceof MetadataReleaseMismatchError) {
4942
+ this.verifiedFreshReleaseId = null;
4943
+ }
4944
+ for (const item of group) {
4945
+ item.reject(error);
4946
+ }
4947
+ }
4948
+ }
4949
+ async executeRelationshipGroup(queries) {
4950
+ const prepared = [];
4951
+ for (const query of queries) {
4952
+ try {
4953
+ prepared.push({
4954
+ filter: await this.assertQueryLifecycle("relations", { status: query.status })
4955
+ });
4956
+ } catch (error) {
4957
+ prepared.push({ error });
4958
+ }
4959
+ }
4960
+ const runnableIndexes = prepared.flatMap(
4961
+ (item, index) => "filter" in item ? [index] : []
4962
+ );
4963
+ const outcomes = prepared.map(
4964
+ (item) => "error" in item ? { ok: false, error: item.error } : {
4965
+ ok: false,
4966
+ error: new MetadataDiscoveryError("Metadata relationship batch returned no result")
4967
+ }
4968
+ );
4969
+ try {
4970
+ if (runnableIndexes.length === 0) {
4971
+ return outcomes;
4972
+ }
4973
+ const runnable = runnableIndexes.map((index) => queries[index]);
4974
+ const raw = await this.fetchRelationships(runnable);
4975
+ runnableIndexes.forEach((queryIndex, rawIndex) => {
4976
+ const fetched = raw[rawIndex];
4977
+ const filter = prepared[queryIndex];
4978
+ if (!fetched || !filter || !("filter" in filter)) {
4979
+ outcomes[queryIndex] = {
4980
+ ok: false,
4981
+ error: new MetadataDiscoveryError("Metadata relationship batch returned no result")
4982
+ };
4983
+ return;
4984
+ }
4985
+ if (fetched.error) {
4986
+ outcomes[queryIndex] = { ok: false, error: fetched.error };
4987
+ return;
4988
+ }
4989
+ try {
4990
+ outcomes[queryIndex] = {
4991
+ ok: true,
4992
+ result: {
4993
+ releaseId: fetched.releaseId,
4994
+ supported: fetched.supported,
4995
+ relationships: lifecycleRows(fetched.relationships, filter.filter)
4996
+ }
4997
+ };
4998
+ } catch (error) {
4999
+ outcomes[queryIndex] = { ok: false, error };
5000
+ }
5001
+ });
5002
+ return outcomes;
5003
+ } catch (error) {
5004
+ if (error instanceof MetadataFreshnessError || error instanceof MetadataReleaseMismatchError) {
5005
+ this.verifiedFreshReleaseId = null;
5006
+ }
5007
+ for (const queryIndex of runnableIndexes) {
5008
+ outcomes[queryIndex] = { ok: false, error };
5009
+ }
5010
+ return outcomes;
5011
+ }
5012
+ }
5013
+ async fetchRelationships(queries) {
5014
+ if (queries.length === 0) {
5015
+ return [];
5016
+ }
5017
+ if (queries.length === 1) {
5018
+ return [await this.settleSingleRelationship(queries[0])];
5019
+ }
5020
+ const fetched = [];
5021
+ for (let offset = 0; offset < queries.length; offset += RELATIONSHIP_QUERY_BATCH_LIMIT) {
5022
+ const chunk = queries.slice(offset, offset + RELATIONSHIP_QUERY_BATCH_LIMIT);
5023
+ if (chunk.length === 1) {
5024
+ fetched.push(await this.settleSingleRelationship(chunk[0]));
5025
+ continue;
5026
+ }
5027
+ fetched.push(...await this.postRelationshipBatch(chunk));
5028
+ }
5029
+ return fetched;
5030
+ }
5031
+ async settleSingleRelationship(query) {
5032
+ try {
5033
+ return await this.postSingleRelationship(query);
5034
+ } catch (error) {
5035
+ if (error instanceof MetadataFreshnessError || error instanceof MetadataReleaseMismatchError || error instanceof MetadataProjectionUnavailableError || error instanceof MetadataExtensionContractError) {
5036
+ throw error;
5037
+ }
5038
+ return {
5039
+ releaseId: null,
5040
+ supported: false,
5041
+ relationships: [],
5042
+ error
5043
+ };
5044
+ }
5445
5045
  }
5446
- toMetadataValue(item, locale) {
5447
- if (!item?.typeCode || !item.valueCode) {
5448
- return null;
5449
- }
5450
- if (item.entry) {
5451
- return projectionEntryToMetadataValue(
5452
- item.typeCode,
5453
- item.valueCode,
5454
- item.entry,
5455
- locale
5456
- );
5457
- }
5046
+ async postSingleRelationship(query) {
5047
+ this.relationshipRequestCount += 1;
5048
+ const body = await this.requestJson(
5049
+ "POST",
5050
+ "/v1/metadata/relationships/query",
5051
+ query
5052
+ );
5458
5053
  return {
5459
- typeCode: item.typeCode,
5460
- valueCode: item.valueCode,
5461
- localizedLabel: item.localizedLabel,
5462
- status: item.status,
5463
- version: item.version,
5464
- entry: {
5465
- code: item.valueCode,
5466
- displayName: item.localizedLabel,
5467
- label: item.localizedLabel,
5468
- status: item.status,
5469
- version: item.version,
5470
- sortOrder: 0,
5471
- isGlobal: true,
5472
- attributes: {},
5473
- applicability: {
5474
- module: [],
5475
- category: [],
5476
- condition: [],
5477
- country: []
5478
- }
5479
- }
5054
+ releaseId: body.releaseId ?? null,
5055
+ supported: body.supported === true,
5056
+ relationships: Array.isArray(body.relationships) ? body.relationships : []
5480
5057
  };
5481
5058
  }
5482
- async assertDiscoveryPolicy(readPolicy) {
5483
- if (readPolicy !== "REQUIRE_FRESH") {
5484
- return;
5059
+ async postRelationshipBatch(queries) {
5060
+ const readPolicy = queries.some((query) => query.readPolicy === "REQUIRE_FRESH") ? "REQUIRE_FRESH" : queries[0]?.readPolicy;
5061
+ const releaseId = queries.find((query) => query.releaseId)?.releaseId;
5062
+ this.relationshipRequestCount += 1;
5063
+ const body = await this.requestJson("POST", "/v1/metadata/relationships/batch", {
5064
+ releaseId,
5065
+ readPolicy,
5066
+ queries: queries.map((query) => ({
5067
+ sourceTypeCode: query.sourceTypeCode,
5068
+ sourceValueCode: query.sourceValueCode,
5069
+ targetTypeCode: query.targetTypeCode,
5070
+ relationType: query.relationType,
5071
+ direction: query.direction,
5072
+ status: query.status,
5073
+ releaseId: query.releaseId
5074
+ }))
5075
+ });
5076
+ const results = Array.isArray(body.results) ? body.results : [];
5077
+ if (results.length !== queries.length) {
5078
+ throw new MetadataDiscoveryError(
5079
+ "Metadata relationship batch did not return one result per query"
5080
+ );
5485
5081
  }
5486
- const status = await this.getStatus();
5487
- assertMetadataReadPolicy(readPolicy, status.state, status.releaseId);
5082
+ return results.map((item, index) => {
5083
+ if (item.errorCode === "METADATA_RELEASE_MISMATCH") {
5084
+ return {
5085
+ releaseId: body.releaseId ?? null,
5086
+ supported: false,
5087
+ relationships: [],
5088
+ error: new MetadataReleaseMismatchError(
5089
+ queries[index]?.releaseId ?? "",
5090
+ body.releaseId ?? null
5091
+ )
5092
+ };
5093
+ }
5094
+ if (item.errorCode) {
5095
+ return {
5096
+ releaseId: body.releaseId ?? null,
5097
+ supported: false,
5098
+ relationships: [],
5099
+ error: new MetadataDiscoveryError(
5100
+ item.message ?? "Metadata relationship query failed",
5101
+ item.errorCode
5102
+ )
5103
+ };
5104
+ }
5105
+ return {
5106
+ releaseId: body.releaseId ?? null,
5107
+ supported: item.supported === true,
5108
+ relationships: Array.isArray(item.relationships) ? item.relationships : []
5109
+ };
5110
+ });
5488
5111
  }
5489
5112
  async requestJson(method, path, payload) {
5490
- const started = Date.now();
5113
+ const started = performance.now();
5114
+ const endpoint = extensionEndpoint(this.baseUrl);
5115
+ const batchCount = requestBatchCount(payload);
5491
5116
  const controller = new AbortController();
5492
5117
  const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
5493
5118
  try {
@@ -5519,12 +5144,14 @@ var ExtensionMetadataProvider = class {
5519
5144
  );
5520
5145
  }
5521
5146
  if (code === "METADATA_FRESHNESS_NOT_SATISFIED") {
5147
+ this.verifiedFreshReleaseId = null;
5522
5148
  throw new MetadataFreshnessError(
5523
5149
  errorBody.state ?? "UNKNOWN",
5524
5150
  errorBody.releaseId ?? null
5525
5151
  );
5526
5152
  }
5527
5153
  if (code === "METADATA_RELEASE_MISMATCH") {
5154
+ this.verifiedFreshReleaseId = null;
5528
5155
  throw new MetadataReleaseMismatchError(
5529
5156
  errorBody.requestedReleaseId ?? "",
5530
5157
  errorBody.actualReleaseId ?? errorBody.releaseId ?? null
@@ -5547,15 +5174,56 @@ var ExtensionMetadataProvider = class {
5547
5174
  err.code = "RUNTIME_METADATA_NOT_FOUND";
5548
5175
  throw err;
5549
5176
  }
5177
+ const durationMs = Math.round(performance.now() - started);
5178
+ createOperationalLogger(this.logger).warn(
5179
+ "runtimeMetadata.extension.requestFailed",
5180
+ {
5181
+ operation: "requestJson",
5182
+ method,
5183
+ path,
5184
+ host: endpoint.host,
5185
+ port: endpoint.port,
5186
+ durationMs,
5187
+ timeoutMs: this.requestTimeoutMs,
5188
+ ...batchCount !== void 0 ? { batchCount } : {},
5189
+ upstreamStatus: response.status,
5190
+ errorCode: code,
5191
+ ...correlationLogFields()
5192
+ }
5193
+ );
5550
5194
  if (response.status === 503 || code === "METADATA_PROJECTION_UNAVAILABLE") {
5551
5195
  throw new MetadataProjectionUnavailableError(
5552
5196
  errorBody.message ?? "Metadata projection is unavailable",
5553
- { retryable: true, metadata: { code, path } }
5197
+ {
5198
+ retryable: true,
5199
+ metadata: {
5200
+ code,
5201
+ path,
5202
+ host: endpoint.host,
5203
+ port: endpoint.port,
5204
+ durationMs,
5205
+ timeoutMs: this.requestTimeoutMs,
5206
+ upstreamStatus: response.status,
5207
+ ...batchCount !== void 0 ? { batchCount } : {}
5208
+ }
5209
+ }
5554
5210
  );
5555
5211
  }
5556
5212
  throw new MetadataProjectionUnavailableError(
5557
5213
  errorBody.message ?? `Extension request failed: ${response.status}`,
5558
- { retryable: response.status >= 500, metadata: { code, path } }
5214
+ {
5215
+ retryable: response.status >= 500,
5216
+ metadata: {
5217
+ code,
5218
+ path,
5219
+ host: endpoint.host,
5220
+ port: endpoint.port,
5221
+ durationMs,
5222
+ timeoutMs: this.requestTimeoutMs,
5223
+ upstreamStatus: response.status,
5224
+ ...batchCount !== void 0 ? { batchCount } : {}
5225
+ }
5226
+ }
5559
5227
  );
5560
5228
  }
5561
5229
  return parsed;
@@ -5567,17 +5235,40 @@ var ExtensionMetadataProvider = class {
5567
5235
  throw err;
5568
5236
  }
5569
5237
  const aborted = err.name === "AbortError";
5570
- this.logger.warn({
5571
- event: "runtimeMetadata.extension.requestFailed",
5238
+ const durationMs = Math.round(performance.now() - started);
5239
+ const network = networkErrorFields(err);
5240
+ createOperationalLogger(this.logger).warn("runtimeMetadata.extension.requestFailed", {
5241
+ operation: "requestJson",
5242
+ method,
5572
5243
  path,
5244
+ host: endpoint.host,
5245
+ port: endpoint.port,
5573
5246
  aborted,
5574
- errorMessage: err instanceof Error ? err.message : String(err)
5247
+ durationMs,
5248
+ timeoutMs: this.requestTimeoutMs,
5249
+ ...batchCount !== void 0 ? { batchCount } : {},
5250
+ errorName: network.errorName,
5251
+ errorCode: network.errorCode,
5252
+ causeName: network.causeName,
5253
+ causeCode: network.causeCode,
5254
+ causeMessage: network.causeMessage,
5255
+ message: err instanceof Error ? err.message : String(err),
5256
+ ...correlationLogFields()
5575
5257
  });
5576
5258
  throw new MetadataProjectionUnavailableError(
5577
5259
  aborted ? "Metadata extension request timed out" : "Metadata extension is unavailable",
5578
5260
  {
5579
5261
  retryable: true,
5580
- metadata: { path, unreachable: !aborted, durationMs: Date.now() - started }
5262
+ metadata: {
5263
+ path,
5264
+ unreachable: !aborted,
5265
+ durationMs,
5266
+ host: endpoint.host,
5267
+ port: endpoint.port,
5268
+ timeoutMs: this.requestTimeoutMs,
5269
+ ...batchCount !== void 0 ? { batchCount } : {},
5270
+ ...network
5271
+ }
5581
5272
  }
5582
5273
  );
5583
5274
  } finally {
@@ -5609,6 +5300,45 @@ function parseTypeCatalog(raw, fallbackTypeCode) {
5609
5300
  function isUnsupportedExtensionRoute(status, body) {
5610
5301
  return status === 404 && (body.code === "METADATA_EXTENSION_ROUTE_UNSUPPORTED" || body.message === "Unknown extension route");
5611
5302
  }
5303
+ function extensionEndpoint(baseUrl) {
5304
+ try {
5305
+ const url = new URL(baseUrl);
5306
+ const port = url.port || (url.protocol === "https:" ? "443" : url.protocol === "http:" ? "80" : "");
5307
+ return { host: url.hostname || "unknown", port: port || "unknown" };
5308
+ } catch {
5309
+ return { host: "unknown", port: "unknown" };
5310
+ }
5311
+ }
5312
+ function requestBatchCount(payload) {
5313
+ if (!payload || typeof payload !== "object") {
5314
+ return void 0;
5315
+ }
5316
+ const body = payload;
5317
+ if (Array.isArray(body.sourceValues)) {
5318
+ return body.sourceValues.length;
5319
+ }
5320
+ if (Array.isArray(body.queries)) {
5321
+ return body.queries.length;
5322
+ }
5323
+ if (Array.isArray(body.values)) {
5324
+ return body.values.length;
5325
+ }
5326
+ if (Array.isArray(body.refs)) {
5327
+ return body.refs.length;
5328
+ }
5329
+ return void 0;
5330
+ }
5331
+ function networkErrorFields(err) {
5332
+ const error = err;
5333
+ const cause = error?.cause;
5334
+ return {
5335
+ ...typeof error?.name === "string" ? { errorName: error.name } : {},
5336
+ ...typeof error?.code === "string" ? { errorCode: error.code } : {},
5337
+ ...typeof cause?.name === "string" ? { causeName: cause.name } : {},
5338
+ ...typeof cause?.code === "string" ? { causeCode: cause.code } : {},
5339
+ ...typeof cause?.message === "string" ? { causeMessage: cause.message } : {}
5340
+ };
5341
+ }
5612
5342
  function isNotFound(err) {
5613
5343
  return err.code === "RUNTIME_METADATA_NOT_FOUND";
5614
5344
  }
@@ -5618,12 +5348,16 @@ function isUnavailable(err) {
5618
5348
  function isServingState(state) {
5619
5349
  return state === "READY" || state === "STALE" || state === "DEGRADED";
5620
5350
  }
5621
- function correlationHeaders() {
5351
+ function correlationLogFields() {
5622
5352
  const correlationId = getContext().correlationId;
5623
5353
  if (!correlationId || correlationId === "unknown") {
5624
5354
  return {};
5625
5355
  }
5626
- return { "x-correlation-id": correlationId };
5356
+ return { correlationId };
5357
+ }
5358
+ function correlationHeaders() {
5359
+ const fields = correlationLogFields();
5360
+ return fields.correlationId ? { "x-correlation-id": fields.correlationId } : {};
5627
5361
  }
5628
5362
  function discoveryQuery(options) {
5629
5363
  const params = new URLSearchParams();
@@ -5911,11 +5645,12 @@ var ProviderFailoverCoordinator = class {
5911
5645
  }
5912
5646
  this.state = PROVIDER_TRANSPORT_STATE.EXTENSION_UNAVAILABLE;
5913
5647
  this.lastProbeAt = this.now();
5914
- this.logger.warn({
5915
- event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
5648
+ const correlationId = getContext().correlationId;
5649
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK, {
5916
5650
  reason,
5917
5651
  fallback: METADATA_PROVIDER_KIND.S3,
5918
- recoverable: true
5652
+ recoverable: true,
5653
+ ...correlationId && correlationId !== "unknown" ? { correlationId } : {}
5919
5654
  });
5920
5655
  await this.onFallbackActivated?.(reason);
5921
5656
  }
@@ -5926,8 +5661,7 @@ var ProviderFailoverCoordinator = class {
5926
5661
  const status = await this.extension.getStatus();
5927
5662
  if (isExtensionServing(status)) {
5928
5663
  this.state = PROVIDER_TRANSPORT_STATE.EXTENSION_READY;
5929
- this.logger.info({
5930
- event: RUNTIME_METADATA_EVENTS.PROVIDER_RECOVERED,
5664
+ createOperationalLogger(this.logger).info(RUNTIME_METADATA_EVENTS.PROVIDER_RECOVERED, {
5931
5665
  releaseId: status.releaseId,
5932
5666
  extensionState: status.state
5933
5667
  });
@@ -5942,8 +5676,6 @@ var ProviderFailoverCoordinator = class {
5942
5676
  function isExtensionServing(status) {
5943
5677
  return SERVING_STATES.has(status.state) && Boolean(status.releaseId);
5944
5678
  }
5945
-
5946
- // ../../libs/runtime-metadata/src/lib/provider/S3MetadataProvider.ts
5947
5679
  var S3MetadataProvider = class {
5948
5680
  cache;
5949
5681
  resolver;
@@ -5979,9 +5711,9 @@ var S3MetadataProvider = class {
5979
5711
  };
5980
5712
  }
5981
5713
  async getValue(typeCode, valueCode, options) {
5982
- const resolved2 = this.valueFilter(options);
5714
+ const resolved = this.valueFilter(options);
5983
5715
  await this.ensureTypesLoaded([typeCode]);
5984
- if (resolved2.filter === METADATA_STATUS_FILTER.ACTIVE) {
5716
+ if (resolved.filter === METADATA_STATUS_FILTER.ACTIVE) {
5985
5717
  try {
5986
5718
  const entry2 = this.resolver.resolve(typeCode, valueCode, options?.version);
5987
5719
  return projectionEntryToMetadataValue(
@@ -6000,7 +5732,7 @@ var S3MetadataProvider = class {
6000
5732
  const entry = findPublishedEntry(
6001
5733
  this.cache.getDomainFile(typeCode),
6002
5734
  valueCode,
6003
- resolved2.filter
5735
+ resolved.filter
6004
5736
  );
6005
5737
  return entry ? projectionEntryToMetadataValue(typeCode, valueCode, entry, options?.locale) : null;
6006
5738
  }
@@ -6049,13 +5781,13 @@ var S3MetadataProvider = class {
6049
5781
  };
6050
5782
  }
6051
5783
  async listRelations(query) {
6052
- const resolved2 = resolveMetadataStatusFilter({ status: query.status });
6053
- if (!resolved2.ok) {
6054
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
5784
+ const resolved = resolveMetadataStatusFilter({ status: query.status });
5785
+ if (!resolved.ok) {
5786
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
6055
5787
  }
6056
5788
  const relations = this.cache.getTypedRelations();
6057
5789
  if (!relations) {
6058
- if (resolved2.filter !== METADATA_STATUS_FILTER.ACTIVE) {
5790
+ if (resolved.filter !== METADATA_STATUS_FILTER.ACTIVE) {
6059
5791
  throw new MetadataDiscoveryError(
6060
5792
  "INACTIVE and ALL relationship queries require typed-relations.json",
6061
5793
  METADATA_LIFECYCLE_UNSUPPORTED
@@ -6072,7 +5804,7 @@ var S3MetadataProvider = class {
6072
5804
  supported: true,
6073
5805
  relations: filterTypedRelations(relations, {
6074
5806
  ...query,
6075
- status: resolved2.filter
5807
+ status: resolved.filter
6076
5808
  })
6077
5809
  };
6078
5810
  }
@@ -6084,10 +5816,8 @@ var S3MetadataProvider = class {
6084
5816
  options
6085
5817
  );
6086
5818
  const values = groups[0]?.values ?? [];
6087
- this.logger.info({
6088
- event: "runtimeMetadata.related.lookup",
5819
+ createOperationalLogger(this.logger).debug("runtimeMetadata.related.lookup", {
6089
5820
  sourceTypeCode,
6090
- sourceValueCode,
6091
5821
  targetTypeCode,
6092
5822
  count: values.length
6093
5823
  });
@@ -6106,53 +5836,30 @@ var S3MetadataProvider = class {
6106
5836
  if (sourceValueCodes.length === 0) {
6107
5837
  return [];
6108
5838
  }
6109
- const resolved2 = this.valueFilter(options);
5839
+ const resolved = this.valueFilter(options);
6110
5840
  await this.ensureTypesLoaded([sourceTypeCode, targetTypeCode]);
6111
- if (resolved2.filter !== METADATA_STATUS_FILTER.ACTIVE) {
5841
+ if (resolved.filter !== METADATA_STATUS_FILTER.ACTIVE) {
6112
5842
  return this.relatedGroupsForStatus(
6113
5843
  sourceTypeCode,
6114
5844
  sourceValueCodes,
6115
5845
  targetTypeCode,
6116
- resolved2.filter,
6117
- resolved2.enforceCapability,
5846
+ resolved.filter,
5847
+ resolved.enforceCapability,
6118
5848
  options
6119
5849
  );
6120
5850
  }
6121
- const index = this.cache.getRelationshipIndex();
6122
- const groups = [];
6123
- for (const sourceValueCode of sourceValueCodes) {
6124
- const codes = relatedValueCodes(
6125
- index,
6126
- sourceTypeCode,
6127
- sourceValueCode,
6128
- targetTypeCode
6129
- );
6130
- if (codes.length === 0) {
6131
- codes.push(
6132
- ...relatedValueCodesFromEntry(
6133
- this.resolver,
6134
- sourceTypeCode,
6135
- sourceValueCode,
6136
- targetTypeCode
6137
- )
6138
- );
6139
- }
6140
- const values = [];
6141
- for (const valueCode of codes) {
6142
- const value = await this.getValue(targetTypeCode, valueCode, options);
6143
- if (value) {
6144
- values.push(value);
6145
- }
6146
- }
6147
- groups.push({ sourceValueCode, values });
6148
- }
6149
- this.logger.info({
6150
- event: "runtimeMetadata.related.batch",
5851
+ const groups = await this.relatedGroupsFromAdjacency(
5852
+ sourceTypeCode,
5853
+ sourceValueCodes,
5854
+ targetTypeCode,
5855
+ options
5856
+ );
5857
+ createOperationalLogger(this.logger).debug("runtimeMetadata.related.batch", () => ({
6151
5858
  sourceTypeCode,
6152
5859
  targetTypeCode,
6153
5860
  sources: sourceValueCodes.length,
6154
5861
  count: groups.reduce((sum, group) => sum + group.values.length, 0)
6155
- });
5862
+ }));
6156
5863
  return groups;
6157
5864
  }
6158
5865
  async listTypeValues(typeCode, options) {
@@ -6161,8 +5868,8 @@ var S3MetadataProvider = class {
6161
5868
  if (!file) {
6162
5869
  return null;
6163
5870
  }
6164
- const resolved2 = this.valueFilter(options);
6165
- const values = entriesForStatus(file, resolved2.filter).map(
5871
+ const resolved = this.valueFilter(options);
5872
+ const values = entriesForStatus(file, resolved.filter).map(
6166
5873
  (entry) => projectionEntryToMetadataValue(typeCode, entry.code, entry, options?.locale)
6167
5874
  );
6168
5875
  return {
@@ -6223,9 +5930,9 @@ var S3MetadataProvider = class {
6223
5930
  const releaseId = await this.prepareDiscoveryRead(query.readPolicy, query.releaseId);
6224
5931
  const relations = this.cache.getTypedRelations();
6225
5932
  const relationshipIndex = this.cache.getRelationshipIndex();
6226
- const resolved2 = resolveMetadataStatusFilter({ status: query.status });
6227
- if (!resolved2.ok) {
6228
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
5933
+ const resolved = resolveMetadataStatusFilter({ status: query.status });
5934
+ if (!resolved.ok) {
5935
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
6229
5936
  }
6230
5937
  const listed = resolvePublishedRelationshipQuery({
6231
5938
  typedSupported: relations !== void 0,
@@ -6237,7 +5944,7 @@ var S3MetadataProvider = class {
6237
5944
  targetTypeCode: query.targetTypeCode,
6238
5945
  relationType: query.relationType,
6239
5946
  direction: query.direction,
6240
- status: resolved2.filter
5947
+ status: resolved.filter
6241
5948
  });
6242
5949
  if (!listed.ok) {
6243
5950
  throwPublishedListFailure(listed);
@@ -6281,13 +5988,13 @@ var S3MetadataProvider = class {
6281
5988
  "METADATA_TYPE_INCOMPLETE"
6282
5989
  );
6283
5990
  }
6284
- const resolved2 = resolveMetadataStatusFilter({ status: options?.status });
6285
- if (!resolved2.ok) {
6286
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
5991
+ const resolved = resolveMetadataStatusFilter({ status: options?.status });
5992
+ if (!resolved.ok) {
5993
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
6287
5994
  }
6288
- if (resolved2.enforceCapability) {
5995
+ if (resolved.enforceCapability) {
6289
5996
  const blocked = lifecycleQueryFailure(
6290
- resolved2.filter,
5997
+ resolved.filter,
6291
5998
  inactiveValuesPublished(this.cache.getManifest()?.lifecycle)
6292
5999
  );
6293
6000
  if (blocked) {
@@ -6300,7 +6007,7 @@ var S3MetadataProvider = class {
6300
6007
  }
6301
6008
  const listed = listPublishedValues(extracted.entries, {
6302
6009
  releaseId,
6303
- status: projectionStatusLiterals(resolved2.filter),
6010
+ status: projectionStatusLiterals(resolved.filter),
6304
6011
  limit: options?.limit,
6305
6012
  cursor: options?.cursor,
6306
6013
  sortBy: options?.sortBy,
@@ -6330,23 +6037,23 @@ var S3MetadataProvider = class {
6330
6037
  );
6331
6038
  }
6332
6039
  valueFilter(options) {
6333
- const resolved2 = resolveMetadataStatusFilter({
6040
+ const resolved = resolveMetadataStatusFilter({
6334
6041
  status: options?.status,
6335
6042
  includeInactive: options?.includeInactive
6336
6043
  });
6337
- if (!resolved2.ok) {
6338
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
6044
+ if (!resolved.ok) {
6045
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
6339
6046
  }
6340
- if (resolved2.enforceCapability) {
6047
+ if (resolved.enforceCapability) {
6341
6048
  const blocked = lifecycleQueryFailure(
6342
- resolved2.filter,
6049
+ resolved.filter,
6343
6050
  inactiveValuesPublished(this.cache.getManifest()?.lifecycle)
6344
6051
  );
6345
6052
  if (blocked) {
6346
6053
  throw new MetadataDiscoveryError(blocked.message, blocked.code);
6347
6054
  }
6348
6055
  }
6349
- return resolved2;
6056
+ return resolved;
6350
6057
  }
6351
6058
  async relatedGroupsForStatus(sourceTypeCode, sourceValueCodes, targetTypeCode, filter, enforceCapability, options) {
6352
6059
  const relations = this.cache.getTypedRelations();
@@ -6408,16 +6115,6 @@ var S3MetadataProvider = class {
6408
6115
  sourceValueCode,
6409
6116
  targetTypeCode
6410
6117
  );
6411
- if (codes.length === 0) {
6412
- codes.push(
6413
- ...relatedValueCodesFromEntry(
6414
- this.resolver,
6415
- sourceTypeCode,
6416
- sourceValueCode,
6417
- targetTypeCode
6418
- )
6419
- );
6420
- }
6421
6118
  const values = [];
6422
6119
  for (const valueCode of codes) {
6423
6120
  const value = await this.getValue(targetTypeCode, valueCode, {
@@ -6468,14 +6165,6 @@ function typeCatalogFromProjection(typeCode, file, common) {
6468
6165
  status: ""
6469
6166
  };
6470
6167
  }
6471
- function relatedValueCodesFromEntry(resolver, sourceTypeCode, sourceValueCode, targetTypeCode) {
6472
- try {
6473
- const entry = resolver.resolve(sourceTypeCode, sourceValueCode);
6474
- return (entry.relationships ?? []).filter((rel) => rel.targetMetadataTypeCode === targetTypeCode).map((rel) => rel.targetValueCode);
6475
- } catch {
6476
- return [];
6477
- }
6478
- }
6479
6168
 
6480
6169
  // ../../libs/runtime-metadata/src/lib/services/RuntimeMetadataService.ts
6481
6170
  var RuntimeMetadataService = class {
@@ -6578,8 +6267,7 @@ var RuntimeMetadataService = class {
6578
6267
  );
6579
6268
  }
6580
6269
  });
6581
- this.logger.info({
6582
- event: RUNTIME_METADATA_EVENTS.PROVIDER_SELECTED,
6270
+ createOperationalLogger(this.logger).info(RUNTIME_METADATA_EVENTS.PROVIDER_SELECTED, {
6583
6271
  kind: this.metadataProviderKind,
6584
6272
  hasFallback: Boolean(this.metadataProviderFallback)
6585
6273
  });
@@ -6599,34 +6287,51 @@ var RuntimeMetadataService = class {
6599
6287
  await this.initializeInFlight;
6600
6288
  }
6601
6289
  async initializeInternal(revision) {
6290
+ const started = Date.now();
6291
+ const logs = createOperationalLogger(this.logger);
6602
6292
  if (this.usesExtensionTransport()) {
6603
- this.logger.info({
6604
- event: RUNTIME_METADATA_EVENTS.INIT_START,
6293
+ logs.debug(RUNTIME_METADATA_EVENTS.INIT_START, {
6605
6294
  transport: "extension"
6606
6295
  });
6607
- const ready = await this.initializeFromExtension();
6608
- if (ready) {
6609
- this.logger.info({
6610
- event: RUNTIME_METADATA_EVENTS.INIT_COMPLETE,
6296
+ const outcome = await this.initializeFromExtension();
6297
+ if (outcome === "ready") {
6298
+ const durationMs = Date.now() - started;
6299
+ logs.info(RUNTIME_METADATA_EVENTS.INIT_COMPLETE, {
6611
6300
  transport: "extension",
6612
- releaseId: this.cache.getReleaseId()
6301
+ releaseId: this.cache.getReleaseId(),
6302
+ durationMs,
6303
+ ...correlationFields()
6613
6304
  });
6305
+ if (durationMs >= logs.policy.slowInitMs) {
6306
+ logs.warn("runtimeMetadata.init.slow", {
6307
+ transport: "extension",
6308
+ releaseId: this.cache.getReleaseId(),
6309
+ durationMs,
6310
+ thresholdMs: logs.policy.slowInitMs,
6311
+ ...correlationFields()
6312
+ });
6313
+ }
6614
6314
  return;
6615
6315
  }
6616
6316
  if (!this.metadataProviderFallback) {
6617
- this.logger.warn({
6618
- event: RUNTIME_METADATA_EVENTS.INIT_FAILED,
6317
+ const catalogEmpty = outcome === "catalog-empty";
6318
+ logs.error(RUNTIME_METADATA_EVENTS.INIT_FAILED, {
6619
6319
  transport: "extension",
6620
- reason: "fallback-disabled"
6320
+ reason: catalogEmpty ? "extension-catalog-empty" : "fallback-disabled",
6321
+ durationMs: Date.now() - started,
6322
+ ...correlationFields()
6621
6323
  });
6622
6324
  throw new MetadataProjectionUnavailableError(
6623
- "Metadata extension is unavailable and S3 fallback is disabled",
6325
+ catalogEmpty ? "Metadata extension is ready but did not publish a metadata type catalog, and S3 fallback is disabled" : "Metadata extension is unavailable and S3 fallback is disabled",
6624
6326
  { retryable: true }
6625
6327
  );
6626
6328
  }
6627
- await this.providerCoordinator.activateFallback("extension-init");
6329
+ await this.providerCoordinator.activateFallback(
6330
+ outcome === "catalog-empty" ? "extension-catalog-empty" : "extension-init"
6331
+ );
6628
6332
  }
6629
6333
  await this.refreshService.initialize(revision ?? this.config.revision);
6334
+ this.logInstalledManifest("s3");
6630
6335
  this.startS3PeriodicCheck();
6631
6336
  }
6632
6337
  /**
@@ -6646,8 +6351,7 @@ var RuntimeMetadataService = class {
6646
6351
  if (!this.metadataProviderFallback || err instanceof MetadataExtensionContractError) {
6647
6352
  throw err;
6648
6353
  }
6649
- this.logger.warn({
6650
- event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
6354
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK, {
6651
6355
  reason: "extension-refresh-failed",
6652
6356
  message: err instanceof Error ? err.message : String(err)
6653
6357
  });
@@ -6671,8 +6375,7 @@ var RuntimeMetadataService = class {
6671
6375
  if (!this.metadataProviderFallback || err instanceof MetadataExtensionContractError) {
6672
6376
  throw err;
6673
6377
  }
6674
- this.logger.warn({
6675
- event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
6378
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK, {
6676
6379
  reason: "extension-check-failed",
6677
6380
  message: err instanceof Error ? err.message : String(err)
6678
6381
  });
@@ -6708,13 +6411,12 @@ var RuntimeMetadataService = class {
6708
6411
  */
6709
6412
  async ensureProjectionsForResponse(response) {
6710
6413
  const potential = hasPotentialMetadata(response);
6414
+ const logs = createOperationalLogger(this.logger);
6711
6415
  if (!potential) {
6712
- this.logger.info({
6713
- event: "metadata-enrichment.trace.typeDetection.completed",
6416
+ logs.debug("metadata-enrichment.trace.typeDetection.completed", {
6714
6417
  stage: "ensureProjectionsForResponse",
6715
6418
  hasPotentialMetadata: false,
6716
- referencesFound: 0,
6717
- typeCodesFound: []
6419
+ referencesFound: 0
6718
6420
  });
6719
6421
  return;
6720
6422
  }
@@ -6728,20 +6430,32 @@ var RuntimeMetadataService = class {
6728
6430
  totalUniqueTypesDiscovered: 0,
6729
6431
  totalUniqueTypeValuesDiscovered: 0
6730
6432
  };
6731
- const references = collectResponseReferences(response, { knownTypes, diagnostics });
6732
- const typeCodes = collectResponseTypeCodes(response, { knownTypes, diagnostics });
6733
- this.logger.info({
6734
- event: "metadata-enrichment.trace.typeDetection.completed",
6433
+ let references = collectResponseReferences(response, { knownTypes, diagnostics });
6434
+ let typeCodes = collectResponseTypeCodes(response, { knownTypes, diagnostics });
6435
+ if ((!knownTypes || knownTypes.length === 0) && this.cache.isReady()) {
6436
+ const refreshedTypes = this.listMetadataTypes();
6437
+ if (refreshedTypes.length > 0) {
6438
+ references = collectResponseReferences(response, {
6439
+ knownTypes: refreshedTypes,
6440
+ diagnostics
6441
+ });
6442
+ typeCodes = collectResponseTypeCodes(response, {
6443
+ knownTypes: refreshedTypes,
6444
+ diagnostics
6445
+ });
6446
+ }
6447
+ }
6448
+ const knownTypesAvailable = knownTypes?.length ?? 0;
6449
+ logs.debug("metadata-enrichment.trace.typeDetection.completed", () => ({
6735
6450
  stage: "ensureProjectionsForResponse",
6736
6451
  hasPotentialMetadata: true,
6737
6452
  totalCandidatesDiscovered: diagnostics.totalCandidatesDiscovered,
6738
6453
  totalUniqueTypesDiscovered: diagnostics.totalUniqueTypesDiscovered,
6739
6454
  totalUniqueTypeValuesDiscovered: diagnostics.totalUniqueTypeValuesDiscovered,
6740
6455
  referencesFound: references.length,
6741
- typeCodesFound: typeCodes,
6742
- sampleCandidates: diagnostics.candidateFields.slice(0, 15),
6743
- knownTypesAvailable: knownTypes ? knownTypes.length : 0
6744
- });
6456
+ typeCodeCount: typeCodes.length,
6457
+ knownTypesAvailable
6458
+ }));
6745
6459
  if (references.length === 0) {
6746
6460
  return;
6747
6461
  }
@@ -6751,11 +6465,13 @@ var RuntimeMetadataService = class {
6751
6465
  );
6752
6466
  const batch = await this.batchGet(compact);
6753
6467
  if (batch.unavailable) {
6754
- await this.providerCoordinator.activateFallback("extension-lookup");
6755
- await this.ensureProjectionTypesLoaded(
6756
- collectResponseTypeCodes(response, { knownTypes })
6468
+ throw new MetadataProjectionUnavailableError(
6469
+ "Metadata extension batch lookup is unavailable",
6470
+ {
6471
+ retryable: true,
6472
+ metadata: { operation: "ensureProjectionsForResponse" }
6473
+ }
6757
6474
  );
6758
- return;
6759
6475
  }
6760
6476
  return;
6761
6477
  }
@@ -6775,15 +6491,11 @@ var RuntimeMetadataService = class {
6775
6491
  if (!this.cache.isReady()) {
6776
6492
  await this.initialize();
6777
6493
  }
6778
- const startLoadTime = Date.now();
6779
6494
  const inMemoryBefore = metadataTypeCodes.filter((c) => Boolean(this.cache.getDomainFile(c)));
6780
6495
  const missingInitial = this.findMissingTypeCodes(metadataTypeCodes);
6781
- this.logger.info({
6782
- event: "metadata-enrichment.trace.metadataLoading.start",
6496
+ const logs = createOperationalLogger(this.logger);
6497
+ logs.debug("metadata-enrichment.trace.metadataLoading.start", {
6783
6498
  stage: "ensureProjectionTypesLoaded",
6784
- requestedTypes: metadataTypeCodes,
6785
- typesInMemory: inMemoryBefore,
6786
- typesMissing: missingInitial,
6787
6499
  totalRequested: metadataTypeCodes.length,
6788
6500
  totalInMemory: inMemoryBefore.length,
6789
6501
  totalMissing: missingInitial.length
@@ -6791,14 +6503,6 @@ var RuntimeMetadataService = class {
6791
6503
  while (true) {
6792
6504
  const missing = this.findMissingTypeCodes(metadataTypeCodes);
6793
6505
  if (missing.length === 0) {
6794
- this.logger.info({
6795
- event: "metadata-enrichment.trace.metadataLoading.completed",
6796
- stage: "ensureProjectionTypesLoaded",
6797
- requestedTypes: metadataTypeCodes,
6798
- durationMs: Date.now() - startLoadTime,
6799
- s3IoAttempted: missingInitial.length > 0,
6800
- outcome: "all_types_in_cache"
6801
- });
6802
6506
  return;
6803
6507
  }
6804
6508
  const inFlight = missing.map((code) => this.domainLoadInFlight.get(code)).filter((p) => p != null);
@@ -7018,12 +6722,14 @@ var RuntimeMetadataService = class {
7018
6722
  const guard = this.currentWriteGuard();
7019
6723
  const value = await provider.getValue(typeCode, valueCode, options);
7020
6724
  this.hydrateProviderValues(value ? [value] : [], guard);
7021
- this.logger.info({
7022
- event: value ? RUNTIME_METADATA_EVENTS.CACHE_HIT : RUNTIME_METADATA_EVENTS.CACHE_MISS,
7023
- typeCode,
7024
- valueCode,
7025
- transport: this.providerCoordinator.getActiveKind()
7026
- });
6725
+ createOperationalLogger(this.logger).debug(
6726
+ value ? RUNTIME_METADATA_EVENTS.CACHE_HIT : RUNTIME_METADATA_EVENTS.CACHE_MISS,
6727
+ {
6728
+ typeCode,
6729
+ valueCode,
6730
+ transport: this.providerCoordinator.getActiveKind()
6731
+ }
6732
+ );
7027
6733
  return value;
7028
6734
  } catch (err) {
7029
6735
  if (await this.tryActivateFallbackFromError(err, "extension-lookup", provider)) {
@@ -7036,25 +6742,46 @@ var RuntimeMetadataService = class {
7036
6742
  }
7037
6743
  }
7038
6744
  async batchGet(references, options) {
6745
+ const started = Date.now();
7039
6746
  let provider;
7040
6747
  try {
7041
6748
  provider = await this.activeProvider();
7042
6749
  const generationAtStart = this.cache.getGeneration();
7043
6750
  const result = await provider.batchGet(references, options);
7044
- this.logger.info({
7045
- event: RUNTIME_METADATA_EVENTS.BATCH_LOOKUP,
7046
- requested: references.length,
7047
- resolved: Object.keys(result.items).length,
7048
- invalid: result.invalidReferences.length,
7049
- unavailable: result.unavailable,
6751
+ const durationMs = Date.now() - started;
6752
+ const uniqueCount = new Set(references.filter((ref) => ref.trim())).size;
6753
+ createOperationalLogger(this.logger).debug(RUNTIME_METADATA_EVENTS.BATCH_LOOKUP, {
6754
+ event: "metadata.lookup.completed",
6755
+ operation: "batchGet",
6756
+ component: "consumer",
7050
6757
  transport: this.providerCoordinator.getActiveKind(),
7051
- releaseId: result.releaseId
6758
+ releaseId: result.releaseId,
6759
+ durationMs,
6760
+ requestedCount: references.length,
6761
+ uniqueCount,
6762
+ resolvedCount: Object.keys(result.items).length,
6763
+ invalidCount: result.invalidReferences.length,
6764
+ providerRequestCount: 1,
6765
+ outcome: "success",
6766
+ ...correlationFields()
7052
6767
  });
7053
- if (result.unavailable && this.metadataProviderFallback && provider !== this.metadataProviderFallback) {
7054
- await this.providerCoordinator.activateFallback("batch-unavailable");
7055
- return this.metadataProviderFallback.batchGet(references, options);
6768
+ if (result.unavailable) {
6769
+ if (this.metadataProviderFallback && provider !== this.metadataProviderFallback) {
6770
+ await this.providerCoordinator.activateFallback("batch-unavailable");
6771
+ return this.metadataProviderFallback.batchGet(references, options);
6772
+ }
6773
+ if (this.metadataProviderFallback) {
6774
+ return result;
6775
+ }
6776
+ throw new MetadataProjectionUnavailableError(
6777
+ "Metadata extension batch lookup is unavailable",
6778
+ {
6779
+ retryable: true,
6780
+ metadata: { operation: "batchGet", requestedCount: references.length }
6781
+ }
6782
+ );
7056
6783
  }
7057
- this.installBatchReleaseIfCurrent(result, generationAtStart);
6784
+ await this.installBatchReleaseIfCurrent(result, generationAtStart);
7058
6785
  this.hydrateProviderValues(
7059
6786
  Object.values(result.items),
7060
6787
  {
@@ -7070,6 +6797,15 @@ var RuntimeMetadataService = class {
7070
6797
  return fallback.batchGet(references, options);
7071
6798
  }
7072
6799
  }
6800
+ createOperationalLogger(this.logger).error("metadata.lookup.failed", {
6801
+ operation: "batchGet",
6802
+ component: "consumer",
6803
+ transport: this.providerCoordinator.getActiveKind(),
6804
+ durationMs: Date.now() - started,
6805
+ errorCode: err instanceof MetadataProjectionUnavailableError ? err.code : err instanceof Error ? err.name : "METADATA_LOOKUP_FAILED",
6806
+ outcome: "error",
6807
+ ...correlationFields()
6808
+ });
7073
6809
  throw err;
7074
6810
  }
7075
6811
  }
@@ -7196,6 +6932,25 @@ var RuntimeMetadataService = class {
7196
6932
  const guard = this.currentWriteGuard();
7197
6933
  const listed = await provider.listTypeValues(typeCode, options);
7198
6934
  this.hydrateProviderValues(listed?.values ?? [], guard);
6935
+ if (listed?.type) {
6936
+ const typeCode2 = listed.type.metadataType;
6937
+ this.cache.mergeTypeCatalog(
6938
+ {
6939
+ [typeCode2]: {
6940
+ typeCode: typeCode2,
6941
+ projectionFile: `${typeCode2}.json`,
6942
+ valueDataType: listed.type.valueDataType,
6943
+ multiSelectAllowed: listed.type.multiSelectAllowed,
6944
+ ...listed.type.displayName ? {
6945
+ localizedDisplayName: {
6946
+ [this.cache.getManifest()?.localization?.defaultLocale ?? "en-US"]: listed.type.displayName
6947
+ }
6948
+ } : {}
6949
+ }
6950
+ },
6951
+ guard
6952
+ );
6953
+ }
7199
6954
  return listed;
7200
6955
  } catch (err) {
7201
6956
  if (await this.tryActivateFallbackFromError(err, "extension-list", provider)) {
@@ -7214,6 +6969,7 @@ var RuntimeMetadataService = class {
7214
6969
  * snapshot, so a mismatched pin must be retried as a new session.
7215
6970
  */
7216
6971
  async beginMetadataRead(options) {
6972
+ const started = Date.now();
7217
6973
  const provider = await this.activeProvider();
7218
6974
  const status = await provider.getStatus();
7219
6975
  const readPolicy = options?.readPolicy ?? METADATA_READ_POLICY.ALLOW_STALE;
@@ -7228,6 +6984,19 @@ var RuntimeMetadataService = class {
7228
6984
  "Metadata projection release is unavailable"
7229
6985
  );
7230
6986
  }
6987
+ const counters = performanceCounters(provider);
6988
+ const logs = createOperationalLogger(this.logger);
6989
+ logs.observe({
6990
+ event: "runtimeMetadata.metadataRead",
6991
+ durationMs: Date.now() - started,
6992
+ thresholdMs: logs.policy.slowLookupMs,
6993
+ fields: {
6994
+ releaseId: status.releaseId,
6995
+ readPolicy,
6996
+ ...counters ? { readinessCheckCount: counters.readinessCheckCount } : {},
6997
+ ...correlationFields()
6998
+ }
6999
+ });
7231
7000
  return { releaseId: status.releaseId, readPolicy };
7232
7001
  }
7233
7002
  async listValuesByType(typeCode, options) {
@@ -7236,14 +7005,18 @@ var RuntimeMetadataService = class {
7236
7005
  options?.readPolicy,
7237
7006
  (provider) => provider.listValuesByType(typeCode, options)
7238
7007
  );
7239
- this.logger.info({
7008
+ const logs = createOperationalLogger(this.logger);
7009
+ logs.observe({
7240
7010
  event: RUNTIME_METADATA_EVENTS.TYPE_ENUMERATION,
7241
- typeCode,
7242
- releaseId: result.releaseId,
7243
- itemCount: result.items.length,
7244
- paged: Boolean(options?.limit),
7245
7011
  durationMs: Date.now() - started,
7246
- transport: this.providerCoordinator.getActiveKind()
7012
+ thresholdMs: logs.policy.slowLookupMs,
7013
+ fields: {
7014
+ typeCode,
7015
+ releaseId: result.releaseId,
7016
+ itemCount: result.items.length,
7017
+ paged: Boolean(options?.limit),
7018
+ transport: this.providerCoordinator.getActiveKind()
7019
+ }
7247
7020
  });
7248
7021
  return result;
7249
7022
  }
@@ -7253,14 +7026,18 @@ var RuntimeMetadataService = class {
7253
7026
  options?.readPolicy,
7254
7027
  (provider) => provider.listValuesByTypes(typeCodes, options)
7255
7028
  );
7256
- this.logger.info({
7029
+ const logs = createOperationalLogger(this.logger);
7030
+ logs.observe({
7257
7031
  event: RUNTIME_METADATA_EVENTS.TYPE_BATCH_ENUMERATION,
7258
- typeCount: typeCodes.length,
7259
- releaseId: result.releaseId,
7260
- failed: result.types.filter((type) => type.errorCode).length,
7261
- unknown: result.types.filter((type) => !type.found).length,
7262
7032
  durationMs: Date.now() - started,
7263
- transport: this.providerCoordinator.getActiveKind()
7033
+ thresholdMs: logs.policy.slowLookupMs,
7034
+ fields: {
7035
+ typeCount: typeCodes.length,
7036
+ releaseId: result.releaseId,
7037
+ failed: result.types.filter((type) => type.errorCode).length,
7038
+ unknown: result.types.filter((type) => !type.found).length,
7039
+ transport: this.providerCoordinator.getActiveKind()
7040
+ }
7264
7041
  });
7265
7042
  return result;
7266
7043
  }
@@ -7270,22 +7047,93 @@ var RuntimeMetadataService = class {
7270
7047
  query.readPolicy,
7271
7048
  (provider) => provider.getRelationships(query)
7272
7049
  );
7273
- this.logger.info({
7050
+ const counters = performanceCounters(await this.activeProvider());
7051
+ const logs = createOperationalLogger(this.logger);
7052
+ logs.observe({
7274
7053
  event: RUNTIME_METADATA_EVENTS.RELATIONSHIP_QUERY,
7275
- sourceTypeCode: query.sourceTypeCode,
7276
- relationType: query.relationType,
7277
- direction: query.direction ?? "OUTGOING",
7278
- releaseId: result.releaseId,
7279
- supported: result.supported,
7280
- count: result.relationships.length,
7281
7054
  durationMs: Date.now() - started,
7282
- transport: this.providerCoordinator.getActiveKind()
7055
+ thresholdMs: logs.policy.slowLookupMs,
7056
+ fields: {
7057
+ sourceTypeCode: query.sourceTypeCode,
7058
+ relationType: query.relationType,
7059
+ direction: query.direction ?? "OUTGOING",
7060
+ releaseId: result.releaseId,
7061
+ supported: result.supported,
7062
+ count: result.relationships.length,
7063
+ transport: this.providerCoordinator.getActiveKind(),
7064
+ ...counters ? {
7065
+ relationshipRequestCount: counters.relationshipRequestCount,
7066
+ readinessCheckCount: counters.readinessCheckCount
7067
+ } : {},
7068
+ ...correlationFields()
7069
+ }
7283
7070
  });
7284
7071
  return result;
7285
7072
  }
7073
+ /**
7074
+ * Resolve many relationship queries with a bounded number of extension requests.
7075
+ * Providers without a batch method, and extensions that do not implement the
7076
+ * batch route, keep the existing per-query behavior.
7077
+ */
7078
+ async queryRelationships(queries) {
7079
+ if (queries.length === 0) {
7080
+ return [];
7081
+ }
7082
+ const started = Date.now();
7083
+ const readPolicy = queries.some(
7084
+ (query) => query.readPolicy === METADATA_READ_POLICY.REQUIRE_FRESH
7085
+ ) ? METADATA_READ_POLICY.REQUIRE_FRESH : queries[0]?.readPolicy;
7086
+ const results = await this.withDiscoveryProvider(readPolicy, async (provider) => {
7087
+ const batch = provider.queryRelationships;
7088
+ if (typeof batch === "function") {
7089
+ try {
7090
+ return await batch.call(provider, queries);
7091
+ } catch (error) {
7092
+ if (!(error instanceof MetadataExtensionContractError)) {
7093
+ throw error;
7094
+ }
7095
+ }
7096
+ }
7097
+ return mapPool(queries, 10, (query) => provider.getRelationships(query));
7098
+ });
7099
+ const counters = performanceCounters(await this.activeProvider());
7100
+ const logs = createOperationalLogger(this.logger);
7101
+ logs.observe({
7102
+ event: "runtimeMetadata.relationshipBatch",
7103
+ durationMs: Date.now() - started,
7104
+ thresholdMs: logs.policy.slowLookupMs,
7105
+ fields: {
7106
+ queryCount: queries.length,
7107
+ releaseId: results[0]?.releaseId ?? null,
7108
+ transport: this.providerCoordinator.getActiveKind(),
7109
+ ...counters ? {
7110
+ relationshipRequestCount: counters.relationshipRequestCount,
7111
+ readinessCheckCount: counters.readinessCheckCount
7112
+ } : {},
7113
+ ...correlationFields()
7114
+ }
7115
+ });
7116
+ return results;
7117
+ }
7286
7118
  getActiveProviderKind() {
7287
7119
  return this.providerCoordinator.getActiveKind();
7288
7120
  }
7121
+ /**
7122
+ * One localization dictionary for a locale (`localization/<locale>.json`).
7123
+ * A missing locale file returns undefined. Transport and projection failures throw.
7124
+ * An empty dictionary is a published file, not a failed read.
7125
+ */
7126
+ async getLocalizationMap(locale) {
7127
+ const provider = await this.activeProvider();
7128
+ const reader = provider.getLocalizationMap;
7129
+ if (typeof reader !== "function") {
7130
+ throw new MetadataProjectionUnavailableError(
7131
+ "Localization maps are not available from the active metadata provider",
7132
+ { retryable: false }
7133
+ );
7134
+ }
7135
+ return reader.call(provider, locale);
7136
+ }
7289
7137
  getProviderTransportState() {
7290
7138
  return this.providerCoordinator.getState();
7291
7139
  }
@@ -7317,47 +7165,69 @@ var RuntimeMetadataService = class {
7317
7165
  return changed;
7318
7166
  }
7319
7167
  async initializeFromExtension() {
7168
+ const started = Date.now();
7320
7169
  try {
7321
7170
  const extension = this.metadataProvider;
7322
7171
  const status = extension.waitUntilReady ? await extension.waitUntilReady() : await extension.getStatus();
7323
7172
  if (!isExtensionServing(status)) {
7324
- return false;
7173
+ return "unavailable";
7325
7174
  }
7326
- this.installExtensionManifest(
7175
+ const installed = this.installExtensionManifest(
7327
7176
  status.releaseId ?? "",
7328
7177
  status.metadataTypes ?? [],
7329
7178
  {
7330
7179
  forceReset: true
7331
7180
  }
7332
7181
  );
7333
- return true;
7182
+ return installed ? "ready" : "catalog-empty";
7334
7183
  } catch (err) {
7335
7184
  if (err instanceof MetadataExtensionContractError) {
7336
- this.logger.warn({
7337
- event: RUNTIME_METADATA_EVENTS.INIT_FAILED,
7185
+ createOperationalLogger(this.logger).error(RUNTIME_METADATA_EVENTS.INIT_FAILED, {
7338
7186
  reason: "extension-contract",
7339
- message: err.message
7187
+ message: err.message,
7188
+ durationMs: Date.now() - started,
7189
+ ...correlationFields()
7340
7190
  });
7341
7191
  throw err;
7342
7192
  }
7343
- this.logger.warn({
7344
- event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
7193
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK, {
7345
7194
  reason: "extension-unavailable",
7346
7195
  recoverable: true,
7347
- message: err instanceof Error ? err.message : String(err)
7196
+ durationMs: Date.now() - started,
7197
+ message: err instanceof Error ? err.message : String(err),
7198
+ ...correlationFields()
7348
7199
  });
7349
- return false;
7200
+ return "unavailable";
7350
7201
  }
7351
7202
  }
7352
7203
  installExtensionManifest(releaseId, metadataTypes, options) {
7353
7204
  if (!releaseId) {
7354
- return;
7205
+ return false;
7355
7206
  }
7356
7207
  const uniqueTypes = [...new Set(metadataTypes.filter((code) => code.trim()))].sort(
7357
7208
  (a, b) => a.localeCompare(b)
7358
7209
  );
7359
- if (!options?.forceReset && this.cache.isReady() && this.cache.getReleaseId() === releaseId) {
7360
- return;
7210
+ const installedTypeCount = Object.keys(
7211
+ this.cache.getManifest()?.metadataTypes ?? {}
7212
+ ).length;
7213
+ if (!options?.forceReset && this.cache.isReady() && this.cache.getReleaseId() === releaseId && installedTypeCount > 0) {
7214
+ return true;
7215
+ }
7216
+ if (uniqueTypes.length === 0) {
7217
+ createOperationalLogger(this.logger).warn(
7218
+ RUNTIME_METADATA_EVENTS.METADATA_MANIFEST_LOADED,
7219
+ {
7220
+ releaseId,
7221
+ transport: "extension",
7222
+ hasManifest: false,
7223
+ metadataTypeCount: 0,
7224
+ lookupIndexCount: 0,
7225
+ cacheStatus: this.cache.getStatus(),
7226
+ catalogAvailable: false,
7227
+ reason: "extension-catalog-empty"
7228
+ }
7229
+ );
7230
+ return false;
7361
7231
  }
7362
7232
  const types = {};
7363
7233
  for (const typeCode of uniqueTypes) {
@@ -7413,6 +7283,30 @@ var RuntimeMetadataService = class {
7413
7283
  };
7414
7284
  this.cache.replace(bundle);
7415
7285
  this.syncUnsupportedProjectionRelease(releaseId);
7286
+ this.logInstalledManifest("extension");
7287
+ return true;
7288
+ }
7289
+ logInstalledManifest(transport) {
7290
+ const manifest = this.cache.getManifest();
7291
+ const metadataTypeCount = Object.keys(manifest?.metadataTypes ?? {}).length;
7292
+ const lookupIndexCount = Object.keys(manifest?.lookupIndex ?? {}).length;
7293
+ const catalogAvailable = metadataTypeCount > 0;
7294
+ const logs = createOperationalLogger(this.logger);
7295
+ const payload = {
7296
+ releaseId: this.cache.getReleaseId(),
7297
+ transport,
7298
+ hasManifest: manifest != null,
7299
+ metadataTypeCount,
7300
+ lookupIndexCount,
7301
+ cacheStatus: this.cache.getStatus(),
7302
+ catalogAvailable,
7303
+ ...catalogAvailable ? {} : { reason: "catalog-empty" }
7304
+ };
7305
+ if (!catalogAvailable) {
7306
+ logs.warn(RUNTIME_METADATA_EVENTS.METADATA_MANIFEST_LOADED, payload);
7307
+ return;
7308
+ }
7309
+ logs.info(RUNTIME_METADATA_EVENTS.METADATA_MANIFEST_LOADED, payload);
7416
7310
  }
7417
7311
  hydrateProviderValues(values, guard) {
7418
7312
  if (!this.cache.isReady() || values.length === 0 || !guard.releaseId) {
@@ -7422,7 +7316,8 @@ var RuntimeMetadataService = class {
7422
7316
  values.map((value) => ({
7423
7317
  typeCode: value.typeCode,
7424
7318
  valueCode: value.valueCode,
7425
- entry: value.entry
7319
+ entry: value.entry,
7320
+ localizedLabel: value.localizedLabel
7426
7321
  })),
7427
7322
  guard
7428
7323
  );
@@ -7433,7 +7328,7 @@ var RuntimeMetadataService = class {
7433
7328
  generation: captured?.generation ?? this.cache.getGeneration()
7434
7329
  };
7435
7330
  }
7436
- installBatchReleaseIfCurrent(result, generationAtStart) {
7331
+ async installBatchReleaseIfCurrent(result, generationAtStart) {
7437
7332
  if (!result.releaseId || !this.usesExtensionTransport()) {
7438
7333
  return;
7439
7334
  }
@@ -7445,14 +7340,18 @@ var RuntimeMetadataService = class {
7445
7340
  if (staleInFlight) {
7446
7341
  return;
7447
7342
  }
7448
- this.installExtensionManifest(
7343
+ const status = await this.metadataProvider.getStatus();
7344
+ if (status.releaseId !== result.releaseId) {
7345
+ return;
7346
+ }
7347
+ const installed = this.installExtensionManifest(
7449
7348
  result.releaseId,
7450
- Object.keys(result.items).map((key) => {
7451
- const sep = key.indexOf(":");
7452
- return sep > 0 ? key.slice(0, sep) : key;
7453
- }),
7349
+ status.metadataTypes ?? [],
7454
7350
  { forceReset: true }
7455
7351
  );
7352
+ if (!installed) {
7353
+ this.cache.clear();
7354
+ }
7456
7355
  }
7457
7356
  async withDiscoveryProvider(readPolicy, run) {
7458
7357
  try {
@@ -7466,8 +7365,7 @@ var RuntimeMetadataService = class {
7466
7365
  } catch (err) {
7467
7366
  this.logFreshnessRejection(err);
7468
7367
  if (err instanceof MetadataExtensionContractError) {
7469
- this.logger.warn({
7470
- event: "runtimeMetadata.extension.contract",
7368
+ createOperationalLogger(this.logger).warn("runtimeMetadata.extension.contract", {
7471
7369
  code: err.code,
7472
7370
  message: err.message
7473
7371
  });
@@ -7486,8 +7384,7 @@ var RuntimeMetadataService = class {
7486
7384
  if (!(err instanceof MetadataFreshnessError)) {
7487
7385
  return;
7488
7386
  }
7489
- this.logger.info({
7490
- event: RUNTIME_METADATA_EVENTS.FRESHNESS_REJECTED,
7387
+ createOperationalLogger(this.logger).warn(RUNTIME_METADATA_EVENTS.FRESHNESS_REJECTED, {
7491
7388
  state: err.metadata?.state,
7492
7389
  releaseId: err.metadata?.releaseId
7493
7390
  });
@@ -7506,13 +7403,38 @@ var RuntimeMetadataService = class {
7506
7403
  function recoveryCooldownMs(env) {
7507
7404
  return resolveExtensionRecoveryIntervalMs(env);
7508
7405
  }
7509
-
7510
- // ../../libs/runtime-metadata/src/lib/integration/createRuntimeMetadataFromEnv.ts
7406
+ function correlationFields() {
7407
+ const correlationId = getContext().correlationId;
7408
+ if (!correlationId || correlationId === "unknown") {
7409
+ return {};
7410
+ }
7411
+ return { correlationId };
7412
+ }
7413
+ function performanceCounters(provider) {
7414
+ const candidate = provider;
7415
+ if (typeof candidate.getPerformanceCounters !== "function") {
7416
+ return void 0;
7417
+ }
7418
+ return candidate.getPerformanceCounters();
7419
+ }
7420
+ async function mapPool(items, limit, run) {
7421
+ const results = new Array(items.length);
7422
+ let next = 0;
7423
+ const workers = Array.from({ length: Math.min(Math.max(limit, 1), items.length) }, async () => {
7424
+ while (next < items.length) {
7425
+ const index = next;
7426
+ next += 1;
7427
+ results[index] = await run(items[index]);
7428
+ }
7429
+ });
7430
+ await Promise.all(workers);
7431
+ return results;
7432
+ }
7511
7433
  function createRuntimeMetadataFromEnv(options) {
7512
7434
  const env = options.env ?? process.env;
7513
7435
  const bucket = resolveMetadataProjectionsBucket(env);
7514
7436
  const environment = (options.environment ?? env.PROJECTION_ENVIRONMENT ?? env.STAGE ?? env.NODE_ENV ?? "dev").trim().toLowerCase();
7515
- const config2 = {
7437
+ const config = {
7516
7438
  bucket,
7517
7439
  prefix: resolveProjectionsPrefix(env),
7518
7440
  environment,
@@ -7524,12 +7446,12 @@ function createRuntimeMetadataFromEnv(options) {
7524
7446
  };
7525
7447
  return new RuntimeMetadataService({
7526
7448
  client: options.client,
7527
- config: config2,
7449
+ config,
7528
7450
  env,
7529
7451
  logger: options.logger ?? createLogger({ serviceName: "runtime-metadata" })
7530
7452
  });
7531
7453
  }
7532
- var logger2 = createLogger({
7454
+ var logger = createLogger({
7533
7455
  service: process.env.SERVICE_NAME ?? "api-service",
7534
7456
  redactPII: true
7535
7457
  });
@@ -7548,7 +7470,7 @@ function getRuntimeMetadataService() {
7548
7470
  client: new S3Client({
7549
7471
  region: process.env.AWS_REGION ?? process.env.REGION
7550
7472
  }),
7551
- logger: logger2
7473
+ logger
7552
7474
  });
7553
7475
  }
7554
7476
  return metadataServiceInstance;
@@ -7566,10 +7488,6 @@ async function ensureRuntimeMetadataLoaded() {
7566
7488
  initialized = true;
7567
7489
  lastUpdateCheckAtMs = Date.now();
7568
7490
  }).catch((error) => {
7569
- logger2.error({
7570
- error,
7571
- message: "Failed to initialize runtime metadata"
7572
- });
7573
7491
  initializePromise = void 0;
7574
7492
  throw error;
7575
7493
  });
@@ -7623,6 +7541,8 @@ var InMemoryMetadataProvider = class {
7623
7541
  knownTypeCodes = /* @__PURE__ */ new Set();
7624
7542
  lifecycleSupported;
7625
7543
  permissionRegistry;
7544
+ localization;
7545
+ localizationUnavailable;
7626
7546
  activeByType = /* @__PURE__ */ new Map();
7627
7547
  inactiveByType = /* @__PURE__ */ new Map();
7628
7548
  constructor(options = {}) {
@@ -7630,6 +7550,8 @@ var InMemoryMetadataProvider = class {
7630
7550
  this.unavailable = options.unavailable === true;
7631
7551
  this.lifecycleSupported = options.lifecycleSupported !== false;
7632
7552
  this.permissionRegistry = options.permissionRegistry;
7553
+ this.localization = options.localization;
7554
+ this.localizationUnavailable = options.localizationUnavailable === true;
7633
7555
  this.relations = options.relations;
7634
7556
  this.typedRelationIndex = options.relations ? buildTypedRelationIndex(options.relations) : void 0;
7635
7557
  for (const typeCode of options.knownTypeCodes ?? []) {
@@ -7684,9 +7606,9 @@ var InMemoryMetadataProvider = class {
7684
7606
  { retryable: true }
7685
7607
  );
7686
7608
  }
7687
- const resolved2 = this.readFilter(options);
7609
+ const resolved = this.readFilter(options);
7688
7610
  const record = this.byKey.get(formatMetadataReference(typeCode, valueCode));
7689
- if (!record || !statusMatchesFilter(record.entry.status, resolved2.filter)) {
7611
+ if (!record || !statusMatchesFilter(record.entry.status, resolved.filter)) {
7690
7612
  return null;
7691
7613
  }
7692
7614
  return projectionEntryToMetadataValue(
@@ -7744,12 +7666,12 @@ var InMemoryMetadataProvider = class {
7744
7666
  { retryable: true }
7745
7667
  );
7746
7668
  }
7747
- const resolved2 = resolveMetadataStatusFilter({ status: query.status });
7748
- if (!resolved2.ok) {
7749
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
7669
+ const resolved = resolveMetadataStatusFilter({ status: query.status });
7670
+ if (!resolved.ok) {
7671
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
7750
7672
  }
7751
7673
  if (!this.relations) {
7752
- if (resolved2.filter !== METADATA_STATUS_FILTER.ACTIVE) {
7674
+ if (resolved.filter !== METADATA_STATUS_FILTER.ACTIVE) {
7753
7675
  throw new MetadataDiscoveryError(
7754
7676
  "INACTIVE and ALL relationship queries require typed-relations.json",
7755
7677
  METADATA_LIFECYCLE_UNSUPPORTED
@@ -7762,7 +7684,7 @@ var InMemoryMetadataProvider = class {
7762
7684
  supported: true,
7763
7685
  relations: filterTypedRelations(this.relations, {
7764
7686
  ...query,
7765
- status: resolved2.filter
7687
+ status: resolved.filter
7766
7688
  })
7767
7689
  };
7768
7690
  }
@@ -7775,6 +7697,16 @@ var InMemoryMetadataProvider = class {
7775
7697
  }
7776
7698
  return this.relatedValuesFor(sourceTypeCode, sourceValueCode, targetTypeCode, options);
7777
7699
  }
7700
+ async getLocalizationMap(locale) {
7701
+ if (this.unavailable || this.localizationUnavailable) {
7702
+ throw new MetadataProjectionUnavailableError("Localization projection is unavailable", {
7703
+ retryable: true
7704
+ });
7705
+ }
7706
+ const dictionary = this.localization?.[locale];
7707
+ if (!dictionary) return void 0;
7708
+ return { ...dictionary };
7709
+ }
7778
7710
  async getPermissionRegistry() {
7779
7711
  if (this.unavailable || !this.permissionRegistry) {
7780
7712
  throw new MetadataProjectionUnavailableError(
@@ -7809,15 +7741,15 @@ var InMemoryMetadataProvider = class {
7809
7741
  return groups;
7810
7742
  }
7811
7743
  async relatedValuesFor(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
7812
- const resolved2 = this.readFilter(options);
7813
- if (resolved2.filter !== METADATA_STATUS_FILTER.ACTIVE && !this.relations) {
7814
- if (resolved2.enforceCapability) {
7744
+ const resolved = this.readFilter(options);
7745
+ if (resolved.filter !== METADATA_STATUS_FILTER.ACTIVE && !this.relations) {
7746
+ if (resolved.enforceCapability) {
7815
7747
  throw new MetadataDiscoveryError(
7816
7748
  "INACTIVE and ALL related-value queries require typed-relations.json",
7817
7749
  METADATA_LIFECYCLE_UNSUPPORTED
7818
7750
  );
7819
7751
  }
7820
- } else if (resolved2.filter !== METADATA_STATUS_FILTER.ACTIVE && this.relations) {
7752
+ } else if (resolved.filter !== METADATA_STATUS_FILTER.ACTIVE && this.relations) {
7821
7753
  const listed = resolvePublishedRelationshipQuery({
7822
7754
  typedSupported: true,
7823
7755
  relations: this.relations,
@@ -7825,7 +7757,7 @@ var InMemoryMetadataProvider = class {
7825
7757
  sourceTypeCode,
7826
7758
  sourceValueCode,
7827
7759
  targetTypeCode,
7828
- status: resolved2.filter
7760
+ status: resolved.filter
7829
7761
  });
7830
7762
  if (!listed.ok) {
7831
7763
  throw new MetadataDiscoveryError(listed.message, listed.code);
@@ -7868,8 +7800,8 @@ var InMemoryMetadataProvider = class {
7868
7800
  if (!this.hasType(typeCode)) {
7869
7801
  return null;
7870
7802
  }
7871
- const resolved2 = this.readFilter(options);
7872
- const records = this.recordsForFilter(typeCode, resolved2.filter);
7803
+ const resolved = this.readFilter(options);
7804
+ const records = this.recordsForFilter(typeCode, resolved.filter);
7873
7805
  const values = [];
7874
7806
  for (const record of records) {
7875
7807
  const value = await this.getValue(record.typeCode, record.valueCode, options);
@@ -7936,9 +7868,9 @@ var InMemoryMetadataProvider = class {
7936
7868
  }
7937
7869
  async getRelationships(query) {
7938
7870
  this.assertReadable(query.readPolicy, query.releaseId);
7939
- const resolved2 = resolveMetadataStatusFilter({ status: query.status });
7940
- if (!resolved2.ok) {
7941
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
7871
+ const resolved = resolveMetadataStatusFilter({ status: query.status });
7872
+ if (!resolved.ok) {
7873
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
7942
7874
  }
7943
7875
  const listed = resolvePublishedRelationshipQuery({
7944
7876
  typedSupported: this.relations !== void 0,
@@ -7949,7 +7881,7 @@ var InMemoryMetadataProvider = class {
7949
7881
  targetTypeCode: query.targetTypeCode,
7950
7882
  relationType: query.relationType,
7951
7883
  direction: query.direction,
7952
- status: resolved2.filter
7884
+ status: resolved.filter
7953
7885
  });
7954
7886
  if (!listed.ok) {
7955
7887
  throwPublishedListFailure(listed);
@@ -7964,22 +7896,22 @@ var InMemoryMetadataProvider = class {
7964
7896
  if (!this.hasType(typeCode)) {
7965
7897
  throw new UnknownMetadataTypeError(typeCode);
7966
7898
  }
7967
- const resolved2 = resolveMetadataStatusFilter({ status: options?.status });
7968
- if (!resolved2.ok) {
7969
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
7899
+ const resolved = resolveMetadataStatusFilter({ status: options?.status });
7900
+ if (!resolved.ok) {
7901
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
7970
7902
  }
7971
- if (resolved2.enforceCapability && !this.lifecycleSupported) {
7903
+ if (resolved.enforceCapability && !this.lifecycleSupported) {
7972
7904
  throw new MetadataDiscoveryError(
7973
7905
  "This projection release does not publish inactive lifecycle records. An INACTIVE or ALL query cannot be answered from active-only artifacts.",
7974
7906
  METADATA_LIFECYCLE_UNSUPPORTED
7975
7907
  );
7976
7908
  }
7977
- const entries = this.recordsForFilter(typeCode, resolved2.filter).map(
7909
+ const entries = this.recordsForFilter(typeCode, resolved.filter).map(
7978
7910
  (record) => record.entry
7979
7911
  );
7980
7912
  const listed = listPublishedValues(entries, {
7981
7913
  releaseId: this.releaseId,
7982
- status: projectionStatusLiterals(resolved2.filter),
7914
+ status: projectionStatusLiterals(resolved.filter),
7983
7915
  limit: options?.limit,
7984
7916
  cursor: options?.cursor,
7985
7917
  sortBy: options?.sortBy,
@@ -8030,20 +7962,20 @@ var InMemoryMetadataProvider = class {
8030
7962
  }
8031
7963
  }
8032
7964
  readFilter(options) {
8033
- const resolved2 = resolveMetadataStatusFilter({
7965
+ const resolved = resolveMetadataStatusFilter({
8034
7966
  status: options?.status,
8035
7967
  includeInactive: options?.includeInactive
8036
7968
  });
8037
- if (!resolved2.ok) {
8038
- throw new MetadataDiscoveryError(resolved2.message, resolved2.code);
7969
+ if (!resolved.ok) {
7970
+ throw new MetadataDiscoveryError(resolved.message, resolved.code);
8039
7971
  }
8040
- if (resolved2.enforceCapability && !this.lifecycleSupported) {
7972
+ if (resolved.enforceCapability && !this.lifecycleSupported) {
8041
7973
  throw new MetadataDiscoveryError(
8042
7974
  "This projection release does not publish inactive lifecycle records. An INACTIVE or ALL query cannot be answered from active-only artifacts.",
8043
7975
  METADATA_LIFECYCLE_UNSUPPORTED
8044
7976
  );
8045
7977
  }
8046
- return resolved2;
7978
+ return resolved;
8047
7979
  }
8048
7980
  recordsForFilter(typeCode, filter) {
8049
7981
  if (filter === METADATA_STATUS_FILTER.INACTIVE) {
@@ -8070,6 +8002,6 @@ var InMemoryMetadataProvider = class {
8070
8002
  }
8071
8003
  };
8072
8004
 
8073
- export { CACHE_STATUS, DEFAULT_EXCLUDED_CODE_FIELDS, DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS, ExtensionMetadataProvider, InMemoryMetadataProvider, InvalidMetadataReferenceError, METADATA_ATTRIBUTE_FILTER_KEY, METADATA_PROJECTIONS_BUCKET_ENV, METADATA_PROVIDER_KIND, METADATA_READ_POLICY, METADATA_RELATION_DIRECTION, ManifestValidationError, MetadataCache, MetadataDiscoveryError, MetadataDownloader, MetadataExtensionContractError, MetadataFreshnessError, MetadataHealthService, MetadataLoader, MetadataLookupError, MetadataNotReadyError, MetadataProjectionUnavailableError, MetadataRefreshService, MetadataReleaseMismatchError, 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, assertMetadataReadPolicy, assertReleasePin, canonicalMetadataProjectionsBucketName, collectResponseReferences, collectResponseTypeCodes, createCodeFieldExclusionSet, createRuntimeMetadataFromEnv, defaultExtensionBaseUrl, ensureRuntimeMetadataLoaded, formatMetadataReference, getCandidateTypeCodesForKey, getRuntimeMetadataHealth, getRuntimeMetadataService, hasPotentialMetadata, isCompactMetadataReference, isExtensionEnabled, isExtensionServing, isFreshProjectionState, isMetadataProjectionConfigured, isMetadataProjectionsBucketConfigured, isMetadataReference, isMetadataValueObject, isMetadataValueObjectArray, isWorkflowStepRecord, isWorkflowStepRuleField, localizedLabelFromEntry, manifestLocalizationSchema, metadataGroupFromManifest, metadataValueToReference, normalizeRuntimeMetadataTypeCode, onMetadataProjectionCompleted, parseMetadataReference, projectionEntryToMetadataValue, projectionManifestSchema, readMetadataProjectionsBucket, readModelGroupsFromManifest, relatedValueCodes, resetRuntimeMetadataBootstrapState, resolveMetadataProjectionsBucket, resolveRuntimeMetadataConfig, runtimeMetadataConfigSchema, selectMetadataProvider, supportsMetadataDiscovery, throwPublishedListFailure, tryGetRuntimeMetadataService, tryParseMetadataReference, typeCodeFromCodeFieldName };
8005
+ export { APPLIES_TO_LINKED_ENTITY_METADATA_TYPE, CACHE_STATUS, DEFAULT_EXCLUDED_CODE_FIELDS, DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS, ExtensionMetadataProvider, FIELD_KEY_METADATA_TYPE_ALIASES, InMemoryMetadataProvider, InvalidMetadataReferenceError, METADATA_ATTRIBUTE_FILTER_KEY, METADATA_PROJECTIONS_BUCKET_ENV, METADATA_PROVIDER_KIND, METADATA_READ_POLICY, METADATA_RELATION_DIRECTION, METADATA_TRAVERSAL_MAX_DEPTH, METADATA_TRAVERSAL_MAX_NODES, ManifestValidationError, MetadataCache, MetadataDiscoveryError, MetadataDownloader, MetadataExtensionContractError, MetadataFreshnessError, MetadataHealthService, MetadataLoader, MetadataLookupError, MetadataNotReadyError, MetadataProjectionUnavailableError, MetadataRefreshService, MetadataReleaseMismatchError, MetadataResolver, NON_METADATA_KEYS, PROVIDER_TRANSPORT_STATE, ProjectionDownloadError, ProviderFailoverCoordinator, REFRESH_STATUS, RELATIONSHIP_QUERY_BATCH_LIMIT, RUNTIME_METADATA_EVENTS, RUNTIME_METADATA_INTEGRATION_TARGETS, RUNTIME_METADATA_TYPE_CODE_ALIASES, RuntimeMetadataError, RuntimeMetadataService, S3MetadataProvider, UnknownMetadataTypeError, WORKFLOW_STEP_RULE_KEYS, assertMetadataReadPolicy, assertReleasePin, canonicalMetadataProjectionsBucketName, collectResponseReferences, collectResponseTypeCodes, createCodeFieldExclusionSet, createRuntimeMetadataFromEnv, defaultExtensionBaseUrl, ensureRuntimeMetadataLoaded, formatMetadataReference, getCandidateTypeCodesForKey, getRuntimeMetadataHealth, getRuntimeMetadataService, hasPotentialMetadata, isCompactMetadataReference, isExtensionEnabled, isExtensionServing, isFreshProjectionState, isLinkedEntityCodeField, isMetadataProjectionConfigured, isMetadataProjectionsBucketConfigured, isMetadataReference, isMetadataValueObject, isMetadataValueObjectArray, isTemplateRuleConfiguration, isTemplateRuleNode, isTemplateRulesMap, isWorkflowStepRecord, isWorkflowStepRuleField, linkedEntityMetadataTypeFromAppliesTo, localizedLabelFromEntry, manifestLocalizationSchema, metadataGroupFromManifest, metadataValueToReference, normalizeRuntimeMetadataTypeCode, onMetadataProjectionCompleted, parseMetadataReference, projectionEntryToMetadataValue, projectionManifestSchema, readAppliesToTypeValue, readMetadataProjectionsBucket, readModelGroupsFromManifest, relatedValueCodes, resetRuntimeMetadataBootstrapState, resolveMetadataProjectionsBucket, resolveRuntimeMetadataConfig, runtimeMetadataConfigSchema, selectMetadataProvider, supportsMetadataDiscovery, throwPublishedListFailure, tryGetRuntimeMetadataService, tryParseMetadataReference, typeCodeFromCodeFieldName };
8074
8006
  //# sourceMappingURL=index.js.map
8075
8007
  //# sourceMappingURL=index.js.map