@burdenoff/be-sdk 2026.1123.3 → 2026.1123.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/auth/index.d.ts +1 -1
  2. package/dist/auth/index.js +1 -1
  3. package/dist/{auth-C5ctwSLp.js → auth-DqD4_tHM.js} +39 -6
  4. package/dist/auth-DqD4_tHM.js.map +1 -0
  5. package/dist/{client-BgAEvDC2.d.ts → client-NknQrWsP.d.ts} +3 -1
  6. package/dist/feature-flags/index.d.ts +1 -1
  7. package/dist/graph/index.d.ts +1 -1
  8. package/dist/graph/index.js +2 -2
  9. package/dist/{graph-Egewc_K7.js → graph-BdoM7_90.js} +2 -2
  10. package/dist/{graph-Egewc_K7.js.map → graph-BdoM7_90.js.map} +1 -1
  11. package/dist/{index-HeUeEsMU.d.ts → index-BaskMO3C.d.ts} +8 -2
  12. package/dist/{index-479i3w77.d.ts → index-BgOU0pxB.d.ts} +30 -5
  13. package/dist/{index-FKohsiex.d.ts → index-BrRQe24P.d.ts} +3 -2
  14. package/dist/{index-BiTzGUZP.d.ts → index-BwgBHUuX.d.ts} +2 -2
  15. package/dist/{index-DMeQh75K.d.ts → index-CIayzveI.d.ts} +1 -1
  16. package/dist/{index-DSA8h4W3.d.ts → index-CUiL43SY.d.ts} +2 -2
  17. package/dist/{index-CzMD97-N.d.ts → index-CkQieKSy.d.ts} +16 -2
  18. package/dist/{index-nP7g1FZm.d.ts → index-DFEKBKBE.d.ts} +4 -1
  19. package/dist/{index-DhFP_AIB.d.ts → index-DkitHCtV.d.ts} +1 -1
  20. package/dist/index.d.ts +8 -8
  21. package/dist/index.js +7 -7
  22. package/dist/init/index.js +1 -1
  23. package/dist/{init-B1DRke7D.js → init-4vv4gYEm.js} +2 -2
  24. package/dist/{init-B1DRke7D.js.map → init-4vv4gYEm.js.map} +1 -1
  25. package/dist/instrumentation/index.d.ts +2 -2
  26. package/dist/instrumentation/index.js +3 -3
  27. package/dist/{instrumentation-SvRAUsCQ.js → instrumentation-C738xDj8.js} +45 -6
  28. package/dist/instrumentation-C738xDj8.js.map +1 -0
  29. package/dist/lake/index.d.ts +52 -3
  30. package/dist/lake/index.js +238 -9
  31. package/dist/lake/index.js.map +1 -1
  32. package/dist/metrics/index.js +1 -1
  33. package/dist/{metrics-BfG_SWb_.js → metrics-CQaHT12m.js} +2 -2
  34. package/dist/{metrics-BfG_SWb_.js.map → metrics-CQaHT12m.js.map} +1 -1
  35. package/dist/{metrics-collector-6S-7Smug.js → metrics-collector-DXQrMUle.js} +117 -116
  36. package/dist/metrics-collector-DXQrMUle.js.map +1 -0
  37. package/dist/{middleware-B9eyLP7A.js → middleware-z8KzMFU_.js} +95 -5
  38. package/dist/middleware-z8KzMFU_.js.map +1 -0
  39. package/dist/prisma/index.d.ts +3 -3
  40. package/dist/prisma/index.js +3 -3
  41. package/dist/{prisma-CML_Prrn.js → prisma-J-ZUmVWJ.js} +4 -2
  42. package/dist/{prisma-CML_Prrn.js.map → prisma-J-ZUmVWJ.js.map} +1 -1
  43. package/dist/{rate-limit-CBrK_U5H.js → rate-limit-ISSpByjW.js} +25 -25
  44. package/dist/rate-limit-ISSpByjW.js.map +1 -0
  45. package/dist/resource-caps/index.d.ts +77 -0
  46. package/dist/resource-caps/index.js +235 -31
  47. package/dist/resource-caps/index.js.map +1 -1
  48. package/dist/security/index.d.ts +1 -1
  49. package/dist/security/index.js +1 -1
  50. package/dist/security/rate-limit/index.d.ts +1 -1
  51. package/dist/security/rate-limit/index.js +1 -1
  52. package/dist/server/index.d.ts +4 -4
  53. package/dist/server/index.js +112 -6
  54. package/dist/server/index.js.map +1 -1
  55. package/dist/tags/index.d.ts +1 -1
  56. package/dist/tags/index.js +1 -1
  57. package/dist/{tags-CbijgoqR.js → tags-C316oA9r.js} +14 -3
  58. package/dist/{tags-CbijgoqR.js.map → tags-C316oA9r.js.map} +1 -1
  59. package/dist/telemetry/index.d.ts +1 -1
  60. package/dist/telemetry/index.js +1 -1
  61. package/dist/{types-De_pO1Wz.d.ts → types-BWN8tMdF.d.ts} +5 -1
  62. package/dist/utils/index.d.ts +2 -2
  63. package/dist/utils/index.js +2 -2
  64. package/dist/{utils-DL85Tnbn.js → utils-DpW6K_iB.js} +24 -7
  65. package/dist/{utils-DL85Tnbn.js.map → utils-DpW6K_iB.js.map} +1 -1
  66. package/package.json +1 -1
  67. package/dist/auth-C5ctwSLp.js.map +0 -1
  68. package/dist/instrumentation-SvRAUsCQ.js.map +0 -1
  69. package/dist/metrics-collector-6S-7Smug.js.map +0 -1
  70. package/dist/middleware-B9eyLP7A.js.map +0 -1
  71. package/dist/rate-limit-CBrK_U5H.js.map +0 -1
@@ -122,7 +122,9 @@ const DEFAULT_GRAPHQL_CONFIG = {
122
122
  documentDepth: 3,
123
123
  ignoredOperations: ["IntrospectionQuery"],
124
124
  includeResolvers: true,
125
- resolverSpanDepth: 3
125
+ resolverSpanDepth: 3,
126
+ includeOperationNameInMetrics: false,
127
+ maxOperationNameCardinality: 100
126
128
  };
127
129
  /**
128
130
  * Default database instrumentation configuration
@@ -348,6 +350,21 @@ function resetInstrumentationConfig() {
348
350
  * @category Observability
349
351
  */
350
352
  /**
353
+ * Default maximum distinct label combinations retained per metric before
354
+ * routing new label sets into the bounded overflow bucket.
355
+ */
356
+ const DEFAULT_MAX_SERIES_PER_METRIC = 500;
357
+ /**
358
+ * Default process-level cap on total distinct label series across a
359
+ * {@link MetricsRegistry} instance.
360
+ */
361
+ const DEFAULT_MAX_TOTAL_SERIES = 5e3;
362
+ /**
363
+ * Internal label key used when a metric or registry reaches its cardinality
364
+ * ceiling. Emits `{__overflow__="true"}` in Prometheus exposition format.
365
+ */
366
+ const OVERFLOW_LABEL_KEY = "__overflow__=true";
367
+ /**
351
368
  * Generate label key for storage
352
369
  */
353
370
  function getLabelKey(labels) {
@@ -403,27 +420,24 @@ function formatPrometheusLabelPairs(labelKey) {
403
420
  return pairs.join(",");
404
421
  }
405
422
  /**
406
- * In-memory counter implementation
423
+ * Shared cardinality-bounded series store for all in-memory metrics.
407
424
  */
408
- var InMemoryCounter = class {
425
+ var InMemorySeriesStore = class {
409
426
  values = /* @__PURE__ */ new Map();
410
427
  name;
411
428
  description;
412
- constructor(name, description) {
429
+ budget;
430
+ constructor(name, description, budget) {
413
431
  this.name = name;
414
432
  this.description = description;
433
+ this.budget = budget;
415
434
  }
416
- add(value, labels) {
417
- const key = getLabelKey(labels);
418
- const current = this.values.get(key) || 0;
419
- this.values.set(key, current + value);
420
- }
421
- inc(labels) {
422
- this.add(1, labels);
423
- }
424
- getValue(labels) {
435
+ resolveKeyForWrite(labels, initOverflow) {
425
436
  const key = getLabelKey(labels);
426
- return this.values.get(key) || 0;
437
+ if (this.values.has(key)) return key;
438
+ if (this.budget.tryReserveSeries(this.values.size)) return key;
439
+ if (!this.values.has("__overflow__=true")) this.values.set(OVERFLOW_LABEL_KEY, initOverflow());
440
+ return OVERFLOW_LABEL_KEY;
427
441
  }
428
442
  getName() {
429
443
  return this.name;
@@ -431,11 +445,35 @@ var InMemoryCounter = class {
431
445
  getDescription() {
432
446
  return this.description;
433
447
  }
448
+ reset() {
449
+ const trackedCount = this.values.has("__overflow__=true") ? this.values.size - 1 : this.values.size;
450
+ if (trackedCount > 0) this.budget.releaseSeries(trackedCount);
451
+ this.values.clear();
452
+ }
453
+ };
454
+ /**
455
+ * Shared scalar numeric metric base (counters, gauges, up-down counters).
456
+ */
457
+ var InMemoryNumericMetric = class extends InMemorySeriesStore {
458
+ add(value, labels) {
459
+ const key = this.resolveKeyForWrite(labels, () => 0);
460
+ const current = this.values.get(key) || 0;
461
+ this.values.set(key, current + value);
462
+ }
463
+ getValue(labels) {
464
+ const key = getLabelKey(labels);
465
+ return this.values.get(key) || 0;
466
+ }
434
467
  getAllValues() {
435
468
  return new Map(this.values);
436
469
  }
437
- reset() {
438
- this.values.clear();
470
+ };
471
+ /**
472
+ * In-memory counter implementation
473
+ */
474
+ var InMemoryCounter = class extends InMemoryNumericMetric {
475
+ inc(labels) {
476
+ this.add(1, labels);
439
477
  }
440
478
  };
441
479
  /** Default bucket upper bounds (milliseconds-oriented) when none are supplied. */
@@ -469,31 +507,30 @@ function normaliseBoundaries(boundaries) {
469
507
  /**
470
508
  * In-memory cumulative histogram implementation
471
509
  */
472
- var InMemoryHistogram = class {
473
- series = /* @__PURE__ */ new Map();
474
- name;
475
- description;
510
+ var InMemoryHistogram = class extends InMemorySeriesStore {
476
511
  boundaries;
477
- constructor(name, description, boundaries) {
478
- this.name = name;
479
- this.description = description;
512
+ constructor(name, description, budget, boundaries) {
513
+ super(name, description, budget);
480
514
  this.boundaries = normaliseBoundaries(boundaries);
481
515
  }
516
+ createEmptySeries(initialValue) {
517
+ return {
518
+ bucketCounts: new Array(this.boundaries.length).fill(0),
519
+ count: 0,
520
+ sum: 0,
521
+ min: initialValue,
522
+ max: initialValue,
523
+ reservoir: [],
524
+ reservoirNext: 0
525
+ };
526
+ }
482
527
  record(value, labels) {
483
528
  if (Number.isNaN(value)) return;
484
- const key = getLabelKey(labels);
485
- let series = this.series.get(key);
529
+ const key = this.resolveKeyForWrite(labels, () => this.createEmptySeries(value));
530
+ let series = this.values.get(key);
486
531
  if (!series) {
487
- series = {
488
- bucketCounts: new Array(this.boundaries.length).fill(0),
489
- count: 0,
490
- sum: 0,
491
- min: value,
492
- max: value,
493
- reservoir: [],
494
- reservoirNext: 0
495
- };
496
- this.series.set(key, series);
532
+ series = this.createEmptySeries(value);
533
+ this.values.set(key, series);
497
534
  }
498
535
  const bucketIndex = this.findBucketIndex(value);
499
536
  if (bucketIndex < series.bucketCounts.length) series.bucketCounts[bucketIndex] = (series.bucketCounts[bucketIndex] ?? 0) + 1;
@@ -538,7 +575,7 @@ var InMemoryHistogram = class {
538
575
  * observations only.
539
576
  */
540
577
  getData(labels) {
541
- const series = this.series.get(getLabelKey(labels));
578
+ const series = this.values.get(getLabelKey(labels));
542
579
  if (!series || series.count === 0) return {
543
580
  count: 0,
544
581
  sum: 0,
@@ -575,15 +612,9 @@ var InMemoryHistogram = class {
575
612
  }
576
613
  };
577
614
  }
578
- getName() {
579
- return this.name;
580
- }
581
- getDescription() {
582
- return this.description;
583
- }
584
615
  getAllData() {
585
616
  const result = /* @__PURE__ */ new Map();
586
- for (const key of this.series.keys()) result.set(key, this.getData(key ? this.parseLabels(key) : void 0));
617
+ for (const key of this.values.keys()) result.set(key, this.getData(key ? this.parseLabels(key) : void 0));
587
618
  return result;
588
619
  }
589
620
  /**
@@ -592,7 +623,7 @@ var InMemoryHistogram = class {
592
623
  */
593
624
  getExportSnapshots() {
594
625
  const result = /* @__PURE__ */ new Map();
595
- for (const [key, series] of this.series) result.set(key, {
626
+ for (const [key, series] of this.values) result.set(key, {
596
627
  buckets: this.cumulativeBuckets(series),
597
628
  count: series.count,
598
629
  sum: series.sum
@@ -608,83 +639,23 @@ var InMemoryHistogram = class {
608
639
  }
609
640
  return labels;
610
641
  }
611
- reset() {
612
- this.series.clear();
613
- }
614
642
  };
615
643
  /**
616
644
  * In-memory gauge implementation
617
645
  */
618
- var InMemoryGauge = class {
619
- values = /* @__PURE__ */ new Map();
620
- name;
621
- description;
622
- constructor(name, description) {
623
- this.name = name;
624
- this.description = description;
625
- }
646
+ var InMemoryGauge = class extends InMemoryNumericMetric {
626
647
  set(value, labels) {
627
- const key = getLabelKey(labels);
648
+ const key = this.resolveKeyForWrite(labels, () => 0);
628
649
  this.values.set(key, value);
629
650
  }
630
- add(value, labels) {
631
- const key = getLabelKey(labels);
632
- const current = this.values.get(key) || 0;
633
- this.values.set(key, current + value);
634
- }
635
651
  sub(value, labels) {
636
652
  this.add(-value, labels);
637
653
  }
638
- getValue(labels) {
639
- const key = getLabelKey(labels);
640
- return this.values.get(key) || 0;
641
- }
642
- getName() {
643
- return this.name;
644
- }
645
- getDescription() {
646
- return this.description;
647
- }
648
- getAllValues() {
649
- return new Map(this.values);
650
- }
651
- reset() {
652
- this.values.clear();
653
- }
654
654
  };
655
655
  /**
656
656
  * In-memory UpDownCounter implementation
657
657
  */
658
- var InMemoryUpDownCounter = class {
659
- values = /* @__PURE__ */ new Map();
660
- name;
661
- description;
662
- constructor(name, description) {
663
- this.name = name;
664
- this.description = description;
665
- }
666
- add(value, labels) {
667
- const key = getLabelKey(labels);
668
- const current = this.values.get(key) || 0;
669
- this.values.set(key, current + value);
670
- }
671
- getValue(labels) {
672
- const key = getLabelKey(labels);
673
- return this.values.get(key) || 0;
674
- }
675
- getName() {
676
- return this.name;
677
- }
678
- getDescription() {
679
- return this.description;
680
- }
681
- getAllValues() {
682
- return new Map(this.values);
683
- }
684
- reset() {
685
- this.values.clear();
686
- }
687
- };
658
+ var InMemoryUpDownCounter = class extends InMemoryNumericMetric {};
688
659
  /**
689
660
  * No-op implementations for when metrics are disabled
690
661
  */
@@ -739,9 +710,38 @@ var MetricsRegistry = class {
739
710
  upDownCounters = /* @__PURE__ */ new Map();
740
711
  serviceName;
741
712
  metricPrefix;
742
- constructor(serviceName, metricPrefix = "") {
713
+ maxSeriesPerMetric;
714
+ maxTotalSeries;
715
+ totalSeriesCount = 0;
716
+ budget;
717
+ constructor(serviceName = "unknown-service", metricPrefix = "", options = {}) {
743
718
  this.serviceName = serviceName;
744
719
  this.metricPrefix = metricPrefix;
720
+ this.maxSeriesPerMetric = Math.max(1, Math.floor(options.maxSeriesPerMetric ?? 500));
721
+ this.maxTotalSeries = Math.max(1, Math.floor(options.maxTotalSeries ?? 5e3));
722
+ this.budget = {
723
+ maxSeriesPerMetric: this.maxSeriesPerMetric,
724
+ tryReserveSeries: (currentMetricSeriesCount) => {
725
+ if (currentMetricSeriesCount >= this.maxSeriesPerMetric || this.totalSeriesCount >= this.maxTotalSeries) return false;
726
+ this.totalSeriesCount += 1;
727
+ return true;
728
+ },
729
+ releaseSeries: (count) => {
730
+ this.totalSeriesCount = Math.max(0, this.totalSeriesCount - count);
731
+ }
732
+ };
733
+ }
734
+ /** Number of tracked non-overflow label series currently held across this registry. */
735
+ getTotalSeriesCount() {
736
+ return this.totalSeriesCount;
737
+ }
738
+ /** Configured process-level series cap for this registry. */
739
+ getMaxTotalSeries() {
740
+ return this.maxTotalSeries;
741
+ }
742
+ /** Configured per-metric series cap for this registry. */
743
+ getMaxSeriesPerMetric() {
744
+ return this.maxSeriesPerMetric;
745
745
  }
746
746
  /**
747
747
  * Get service name
@@ -769,7 +769,7 @@ var MetricsRegistry = class {
769
769
  const prefixedName = this.getPrefixedName(name);
770
770
  let counter = this.counters.get(prefixedName);
771
771
  if (!counter) {
772
- counter = new InMemoryCounter(prefixedName, description);
772
+ counter = new InMemoryCounter(prefixedName, description, this.budget);
773
773
  this.counters.set(prefixedName, counter);
774
774
  }
775
775
  return counter;
@@ -782,7 +782,7 @@ var MetricsRegistry = class {
782
782
  const prefixedName = this.getPrefixedName(name);
783
783
  let histogram = this.histograms.get(prefixedName);
784
784
  if (!histogram) {
785
- histogram = new InMemoryHistogram(prefixedName, description, boundaries);
785
+ histogram = new InMemoryHistogram(prefixedName, description, this.budget, boundaries);
786
786
  this.histograms.set(prefixedName, histogram);
787
787
  }
788
788
  return histogram;
@@ -795,7 +795,7 @@ var MetricsRegistry = class {
795
795
  const prefixedName = this.getPrefixedName(name);
796
796
  let gauge = this.gauges.get(prefixedName);
797
797
  if (!gauge) {
798
- gauge = new InMemoryGauge(prefixedName, description);
798
+ gauge = new InMemoryGauge(prefixedName, description, this.budget);
799
799
  this.gauges.set(prefixedName, gauge);
800
800
  }
801
801
  return gauge;
@@ -808,7 +808,7 @@ var MetricsRegistry = class {
808
808
  const prefixedName = this.getPrefixedName(name);
809
809
  let counter = this.upDownCounters.get(prefixedName);
810
810
  if (!counter) {
811
- counter = new InMemoryUpDownCounter(prefixedName, description);
811
+ counter = new InMemoryUpDownCounter(prefixedName, description, this.budget);
812
812
  this.upDownCounters.set(prefixedName, counter);
813
813
  }
814
814
  return counter;
@@ -945,6 +945,7 @@ var MetricsRegistry = class {
945
945
  this.histograms.clear();
946
946
  this.gauges.clear();
947
947
  this.upDownCounters.clear();
948
+ this.totalSeriesCount = 0;
948
949
  }
949
950
  };
950
951
  /**
@@ -954,8 +955,8 @@ let globalRegistry = null;
954
955
  /**
955
956
  * Initialize global metrics registry
956
957
  */
957
- function initializeMetricsRegistry(serviceName, metricPrefix = "") {
958
- globalRegistry = new MetricsRegistry(serviceName, metricPrefix);
958
+ function initializeMetricsRegistry(serviceName, metricPrefix = "", options) {
959
+ globalRegistry = new MetricsRegistry(serviceName, metricPrefix, options);
959
960
  return globalRegistry;
960
961
  }
961
962
  /**
@@ -994,5 +995,5 @@ function createUpDownCounter(name, description) {
994
995
  return getMetricsRegistry().createUpDownCounter(name, description);
995
996
  }
996
997
 
997
- export { resetInstrumentationConfig as A, buildInstrumentationConfig as C, initializeInstrumentationConfig as D, getInstrumentationConfig as E, isFeatureEnabled as O, buildGraphQLConfig as S, buildTracingConfig as T, DEFAULT_METRICS_CONFIG as _, createUpDownCounter as a, buildDatabaseConfig as b, isMetricsRegistryInitialized as c, DEFAULT_DATABASE_CONFIG as d, DEFAULT_EVENT_QUEUE_CONFIG as f, DEFAULT_LOGGING_CONFIG as g, DEFAULT_HTTP_CONFIG as h, createHistogram as i, updateInstrumentationConfig as j, isInstrumentationConfigInitialized as k, resetMetricsRegistry as l, DEFAULT_GRAPHQL_CONFIG as m, createCounter as n, getMetricsRegistry as o, DEFAULT_FEATURE_FLAGS as p, createGauge as r, initializeMetricsRegistry as s, MetricsRegistry as t, DEFAULT_CACHE_CONFIG as u, DEFAULT_TRACING_CONFIG as v, buildMetricsConfig as w, buildFeatureFlags as x, ENV_VARS as y };
998
- //# sourceMappingURL=metrics-collector-6S-7Smug.js.map
998
+ export { initializeInstrumentationConfig as A, buildDatabaseConfig as C, buildMetricsConfig as D, buildInstrumentationConfig as E, isInstrumentationConfigInitialized as M, resetInstrumentationConfig as N, buildTracingConfig as O, updateInstrumentationConfig as P, ENV_VARS as S, buildGraphQLConfig as T, DEFAULT_GRAPHQL_CONFIG as _, createCounter as a, DEFAULT_METRICS_CONFIG as b, createUpDownCounter as c, isMetricsRegistryInitialized as d, resetMetricsRegistry as f, DEFAULT_FEATURE_FLAGS as g, DEFAULT_EVENT_QUEUE_CONFIG as h, OVERFLOW_LABEL_KEY as i, isFeatureEnabled as j, getInstrumentationConfig as k, getMetricsRegistry as l, DEFAULT_DATABASE_CONFIG as m, DEFAULT_MAX_TOTAL_SERIES as n, createGauge as o, DEFAULT_CACHE_CONFIG as p, MetricsRegistry as r, createHistogram as s, DEFAULT_MAX_SERIES_PER_METRIC as t, initializeMetricsRegistry as u, DEFAULT_HTTP_CONFIG as v, buildFeatureFlags as w, DEFAULT_TRACING_CONFIG as x, DEFAULT_LOGGING_CONFIG as y };
999
+ //# sourceMappingURL=metrics-collector-DXQrMUle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics-collector-DXQrMUle.js","names":[],"sources":["../src/instrumentation/config.ts","../src/instrumentation/metrics-collector.ts"],"sourcesContent":["/**\n * Instrumentation Configuration\n *\n * Provides configuration management for OpenTelemetry instrumentation\n * with environment variable support and sensible defaults.\n *\n * @module instrumentation/config\n * @category Observability\n */\n\nimport type {\n CacheInstrumentationConfig,\n DatabaseInstrumentationConfig,\n EventQueueInstrumentationConfig,\n GraphQLInstrumentationConfig,\n HTTPInstrumentationConfig,\n InstrumentationConfig,\n InstrumentationFeatureFlags,\n LoggingConfig,\n MetricsConfig,\n TracingConfig,\n} from './types.js';\n\n/**\n * Environment variable names for instrumentation configuration\n */\nexport const ENV_VARS = {\n // Master switch\n INSTRUMENTATION_ENABLED: 'INSTRUMENTATION_ENABLED',\n\n // Feature flags\n INSTRUMENTATION_TRACING: 'INSTRUMENTATION_TRACING',\n INSTRUMENTATION_METRICS: 'INSTRUMENTATION_METRICS',\n INSTRUMENTATION_LOGGING: 'INSTRUMENTATION_LOGGING',\n INSTRUMENTATION_GRAPHQL: 'INSTRUMENTATION_GRAPHQL',\n INSTRUMENTATION_DATABASE: 'INSTRUMENTATION_DATABASE',\n INSTRUMENTATION_HTTP: 'INSTRUMENTATION_HTTP',\n INSTRUMENTATION_CACHE: 'INSTRUMENTATION_CACHE',\n INSTRUMENTATION_EVENT_QUEUE: 'INSTRUMENTATION_EVENT_QUEUE',\n\n // Tracing\n OTEL_SERVICE_NAME: 'OTEL_SERVICE_NAME',\n OTEL_SERVICE_VERSION: 'OTEL_SERVICE_VERSION',\n OTEL_ENVIRONMENT: 'OTEL_ENVIRONMENT',\n OTEL_EXPORTER_OTLP_ENDPOINT: 'OTEL_EXPORTER_OTLP_ENDPOINT',\n OTEL_EXPORTER_TYPE: 'OTEL_EXPORTER_TYPE',\n OTEL_SAMPLING_RATE: 'OTEL_SAMPLING_RATE',\n OTEL_PROPAGATION_FORMAT: 'OTEL_PROPAGATION_FORMAT',\n\n // Metrics\n METRICS_EXPORTER_TYPE: 'METRICS_EXPORTER_TYPE',\n METRICS_PROMETHEUS_ENDPOINT: 'METRICS_PROMETHEUS_ENDPOINT',\n METRICS_PROMETHEUS_PORT: 'METRICS_PROMETHEUS_PORT',\n METRICS_COLLECT_INTERVAL: 'METRICS_COLLECT_INTERVAL',\n METRICS_DEFAULT_ENABLED: 'METRICS_DEFAULT_ENABLED',\n METRICS_PREFIX: 'METRICS_PREFIX',\n\n // Database\n DB_INSTRUMENTATION_INCLUDE_STATEMENT: 'DB_INSTRUMENTATION_INCLUDE_STATEMENT',\n DB_INSTRUMENTATION_SLOW_QUERY_THRESHOLD: 'DB_INSTRUMENTATION_SLOW_QUERY_THRESHOLD',\n\n // GraphQL\n GRAPHQL_INSTRUMENTATION_INCLUDE_DOCUMENT: 'GRAPHQL_INSTRUMENTATION_INCLUDE_DOCUMENT',\n GRAPHQL_INSTRUMENTATION_INCLUDE_VARIABLES: 'GRAPHQL_INSTRUMENTATION_INCLUDE_VARIABLES',\n GRAPHQL_INSTRUMENTATION_INCLUDE_RESOLVERS: 'GRAPHQL_INSTRUMENTATION_INCLUDE_RESOLVERS',\n} as const;\n\n/**\n * Get environment variable as boolean\n */\nfunction getEnvBoolean(key: string, defaultValue: boolean): boolean {\n const value = process.env[key];\n if (value === undefined || value === '') return defaultValue;\n return value.toLowerCase() === 'true' || value === '1';\n}\n\n/**\n * Get environment variable as number\n */\nfunction getEnvNumber(key: string, defaultValue: number): number {\n const value = process.env[key];\n if (value === undefined || value === '') return defaultValue;\n const parsed = parseFloat(value);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Get environment variable as string\n */\nfunction getEnvString(key: string, defaultValue: string): string {\n const value = process.env[key];\n return value !== undefined && value !== '' ? value : defaultValue;\n}\n\n/**\n * Default feature flags\n */\nexport const DEFAULT_FEATURE_FLAGS: InstrumentationFeatureFlags = {\n tracing: true,\n metrics: true,\n logging: true,\n graphql: true,\n database: true,\n http: true,\n cache: true,\n eventQueue: true,\n};\n\n/**\n * Default tracing configuration\n */\nexport const DEFAULT_TRACING_CONFIG: TracingConfig = {\n enabled: true,\n serviceName: 'unknown-service',\n serviceVersion: '1.0.0',\n environment: 'development',\n exporterType: 'none',\n samplingRate: 1.0,\n propagationFormat: 'w3c',\n resourceAttributes: {},\n ignoredRoutes: ['/health', '/ready', '/live', '/metrics'],\n ignoredOperations: ['IntrospectionQuery'],\n};\n\n/**\n * Default metrics configuration\n */\nexport const DEFAULT_METRICS_CONFIG: MetricsConfig = {\n enabled: true,\n serviceName: 'unknown-service',\n exporterType: 'none',\n prometheusEndpoint: '/metrics',\n prometheusPort: 9090,\n collectInterval: 60000,\n defaultMetrics: true,\n metricPrefix: '',\n};\n\n/**\n * Default logging configuration\n */\nexport const DEFAULT_LOGGING_CONFIG: LoggingConfig = {\n enabled: true,\n includeTraceId: true,\n includeSpanId: true,\n includeTraceFlags: false,\n level: 'info',\n};\n\n/**\n * Default GraphQL instrumentation configuration\n */\nexport const DEFAULT_GRAPHQL_CONFIG: GraphQLInstrumentationConfig = {\n enabled: true,\n includeDocument: false,\n includeVariables: false,\n includeResult: false,\n documentDepth: 3,\n ignoredOperations: ['IntrospectionQuery'],\n includeResolvers: true,\n resolverSpanDepth: 3,\n includeOperationNameInMetrics: false,\n maxOperationNameCardinality: 100,\n};\n\n/**\n * Default database instrumentation configuration\n */\nexport const DEFAULT_DATABASE_CONFIG: DatabaseInstrumentationConfig = {\n enabled: true,\n includeStatement: false,\n includeParameters: false,\n includeRowCount: true,\n slowQueryThreshold: 1000,\n ignoredOperations: [],\n};\n\n/**\n * Default HTTP instrumentation configuration\n */\nexport const DEFAULT_HTTP_CONFIG: HTTPInstrumentationConfig = {\n enabled: true,\n includeRequestHeaders: false,\n includeResponseHeaders: false,\n includeRequestBody: false,\n includeResponseBody: false,\n redactedHeaders: ['authorization', 'cookie', 'set-cookie', 'x-api-key'],\n ignoredRoutes: ['/health', '/ready', '/live', '/metrics'],\n maxBodySize: 10240,\n};\n\n/**\n * Default cache instrumentation configuration\n */\nexport const DEFAULT_CACHE_CONFIG: CacheInstrumentationConfig = {\n enabled: true,\n includeKey: true,\n includeValueSize: true,\n includeTTL: true,\n};\n\n/**\n * Default event queue instrumentation configuration\n */\nexport const DEFAULT_EVENT_QUEUE_CONFIG: EventQueueInstrumentationConfig = {\n enabled: true,\n includePayload: false,\n includeHeaders: true,\n maxPayloadSize: 1024,\n};\n\n/**\n * Global instrumentation configuration state\n */\nlet globalConfig: InstrumentationConfig | null = null;\n\n/**\n * Build feature flags from environment variables\n */\nexport function buildFeatureFlags(overrides?: Partial<InstrumentationFeatureFlags>): InstrumentationFeatureFlags {\n return {\n tracing: getEnvBoolean(ENV_VARS.INSTRUMENTATION_TRACING, DEFAULT_FEATURE_FLAGS.tracing),\n metrics: getEnvBoolean(ENV_VARS.INSTRUMENTATION_METRICS, DEFAULT_FEATURE_FLAGS.metrics),\n logging: getEnvBoolean(ENV_VARS.INSTRUMENTATION_LOGGING, DEFAULT_FEATURE_FLAGS.logging),\n graphql: getEnvBoolean(ENV_VARS.INSTRUMENTATION_GRAPHQL, DEFAULT_FEATURE_FLAGS.graphql),\n database: getEnvBoolean(ENV_VARS.INSTRUMENTATION_DATABASE, DEFAULT_FEATURE_FLAGS.database),\n http: getEnvBoolean(ENV_VARS.INSTRUMENTATION_HTTP, DEFAULT_FEATURE_FLAGS.http),\n cache: getEnvBoolean(ENV_VARS.INSTRUMENTATION_CACHE, DEFAULT_FEATURE_FLAGS.cache),\n eventQueue: getEnvBoolean(ENV_VARS.INSTRUMENTATION_EVENT_QUEUE, DEFAULT_FEATURE_FLAGS.eventQueue),\n ...overrides,\n };\n}\n\n/**\n * Build tracing configuration from environment variables\n */\nexport function buildTracingConfig(serviceName: string, overrides?: Partial<TracingConfig>): TracingConfig {\n return {\n enabled: getEnvBoolean(ENV_VARS.INSTRUMENTATION_TRACING, DEFAULT_TRACING_CONFIG.enabled),\n serviceName: getEnvString(ENV_VARS.OTEL_SERVICE_NAME, serviceName),\n serviceVersion: getEnvString(ENV_VARS.OTEL_SERVICE_VERSION, DEFAULT_TRACING_CONFIG.serviceVersion!),\n environment: getEnvString(ENV_VARS.OTEL_ENVIRONMENT, process.env['NODE_ENV'] || 'development'),\n exporterEndpoint: process.env[ENV_VARS.OTEL_EXPORTER_OTLP_ENDPOINT],\n exporterType: getEnvString(ENV_VARS.OTEL_EXPORTER_TYPE, DEFAULT_TRACING_CONFIG.exporterType!) as\n 'otlp' | 'console' | 'none',\n samplingRate: getEnvNumber(ENV_VARS.OTEL_SAMPLING_RATE, DEFAULT_TRACING_CONFIG.samplingRate!),\n propagationFormat: getEnvString(ENV_VARS.OTEL_PROPAGATION_FORMAT, DEFAULT_TRACING_CONFIG.propagationFormat!) as\n 'w3c' | 'b3' | 'jaeger',\n resourceAttributes: DEFAULT_TRACING_CONFIG.resourceAttributes,\n ignoredRoutes: DEFAULT_TRACING_CONFIG.ignoredRoutes,\n ignoredOperations: DEFAULT_TRACING_CONFIG.ignoredOperations,\n ...overrides,\n };\n}\n\n/**\n * Build metrics configuration from environment variables\n */\nexport function buildMetricsConfig(serviceName: string, overrides?: Partial<MetricsConfig>): MetricsConfig {\n return {\n enabled: getEnvBoolean(ENV_VARS.INSTRUMENTATION_METRICS, DEFAULT_METRICS_CONFIG.enabled),\n serviceName: getEnvString(ENV_VARS.OTEL_SERVICE_NAME, serviceName),\n exporterEndpoint: process.env[ENV_VARS.OTEL_EXPORTER_OTLP_ENDPOINT],\n exporterType: getEnvString(ENV_VARS.METRICS_EXPORTER_TYPE, DEFAULT_METRICS_CONFIG.exporterType!) as\n 'otlp' | 'prometheus' | 'console' | 'none',\n prometheusEndpoint: getEnvString(ENV_VARS.METRICS_PROMETHEUS_ENDPOINT, DEFAULT_METRICS_CONFIG.prometheusEndpoint!),\n prometheusPort: getEnvNumber(ENV_VARS.METRICS_PROMETHEUS_PORT, DEFAULT_METRICS_CONFIG.prometheusPort!),\n collectInterval: getEnvNumber(ENV_VARS.METRICS_COLLECT_INTERVAL, DEFAULT_METRICS_CONFIG.collectInterval!),\n defaultMetrics: getEnvBoolean(ENV_VARS.METRICS_DEFAULT_ENABLED, DEFAULT_METRICS_CONFIG.defaultMetrics!),\n metricPrefix: getEnvString(ENV_VARS.METRICS_PREFIX, DEFAULT_METRICS_CONFIG.metricPrefix!),\n ...overrides,\n };\n}\n\n/**\n * Build database instrumentation configuration\n */\nexport function buildDatabaseConfig(overrides?: Partial<DatabaseInstrumentationConfig>): DatabaseInstrumentationConfig {\n return {\n enabled: getEnvBoolean(ENV_VARS.INSTRUMENTATION_DATABASE, DEFAULT_DATABASE_CONFIG.enabled),\n includeStatement: getEnvBoolean(\n ENV_VARS.DB_INSTRUMENTATION_INCLUDE_STATEMENT,\n DEFAULT_DATABASE_CONFIG.includeStatement!\n ),\n includeParameters: DEFAULT_DATABASE_CONFIG.includeParameters,\n includeRowCount: DEFAULT_DATABASE_CONFIG.includeRowCount,\n slowQueryThreshold: getEnvNumber(\n ENV_VARS.DB_INSTRUMENTATION_SLOW_QUERY_THRESHOLD,\n DEFAULT_DATABASE_CONFIG.slowQueryThreshold!\n ),\n ignoredOperations: DEFAULT_DATABASE_CONFIG.ignoredOperations,\n ...overrides,\n };\n}\n\n/**\n * Build GraphQL instrumentation configuration\n */\nexport function buildGraphQLConfig(overrides?: Partial<GraphQLInstrumentationConfig>): GraphQLInstrumentationConfig {\n return {\n enabled: getEnvBoolean(ENV_VARS.INSTRUMENTATION_GRAPHQL, DEFAULT_GRAPHQL_CONFIG.enabled),\n includeDocument: getEnvBoolean(\n ENV_VARS.GRAPHQL_INSTRUMENTATION_INCLUDE_DOCUMENT,\n DEFAULT_GRAPHQL_CONFIG.includeDocument!\n ),\n includeVariables: getEnvBoolean(\n ENV_VARS.GRAPHQL_INSTRUMENTATION_INCLUDE_VARIABLES,\n DEFAULT_GRAPHQL_CONFIG.includeVariables!\n ),\n includeResult: DEFAULT_GRAPHQL_CONFIG.includeResult,\n documentDepth: DEFAULT_GRAPHQL_CONFIG.documentDepth,\n ignoredOperations: DEFAULT_GRAPHQL_CONFIG.ignoredOperations,\n includeResolvers: getEnvBoolean(\n ENV_VARS.GRAPHQL_INSTRUMENTATION_INCLUDE_RESOLVERS,\n DEFAULT_GRAPHQL_CONFIG.includeResolvers!\n ),\n resolverSpanDepth: DEFAULT_GRAPHQL_CONFIG.resolverSpanDepth,\n ...overrides,\n };\n}\n\n/**\n * Build complete instrumentation configuration\n */\nexport function buildInstrumentationConfig(\n serviceName: string,\n overrides?: Partial<InstrumentationConfig>\n): InstrumentationConfig {\n const enabled = getEnvBoolean(ENV_VARS.INSTRUMENTATION_ENABLED, true);\n\n return {\n enabled,\n features: buildFeatureFlags(overrides?.features),\n tracing: buildTracingConfig(serviceName, overrides?.tracing),\n metrics: buildMetricsConfig(serviceName, overrides?.metrics),\n logging: { ...DEFAULT_LOGGING_CONFIG, ...overrides?.logging },\n graphql: buildGraphQLConfig(overrides?.graphql),\n database: buildDatabaseConfig(overrides?.database),\n http: { ...DEFAULT_HTTP_CONFIG, ...overrides?.http },\n cache: { ...DEFAULT_CACHE_CONFIG, ...overrides?.cache },\n eventQueue: { ...DEFAULT_EVENT_QUEUE_CONFIG, ...overrides?.eventQueue },\n };\n}\n\n/**\n * Initialize global instrumentation configuration\n */\nexport function initializeInstrumentationConfig(\n serviceName: string,\n overrides?: Partial<InstrumentationConfig>\n): InstrumentationConfig {\n globalConfig = buildInstrumentationConfig(serviceName, overrides);\n return globalConfig;\n}\n\n/**\n * Get current instrumentation configuration\n * @throws Error if configuration not initialized\n */\nexport function getInstrumentationConfig(): InstrumentationConfig {\n if (!globalConfig) {\n throw new Error('Instrumentation config not initialized. Call initializeInstrumentationConfig() first.');\n }\n return globalConfig;\n}\n\n/**\n * Check if instrumentation configuration is initialized\n */\nexport function isInstrumentationConfigInitialized(): boolean {\n return globalConfig !== null;\n}\n\n/**\n * Check if a specific feature is enabled\n */\nexport function isFeatureEnabled(feature: keyof InstrumentationFeatureFlags): boolean {\n if (!globalConfig) return false;\n return globalConfig.enabled && globalConfig.features[feature];\n}\n\n/**\n * Update instrumentation configuration at runtime\n */\nexport function updateInstrumentationConfig(updates: Partial<InstrumentationConfig>): InstrumentationConfig {\n if (!globalConfig) {\n throw new Error('Instrumentation config not initialized. Call initializeInstrumentationConfig() first.');\n }\n globalConfig = { ...globalConfig, ...updates };\n return globalConfig;\n}\n\n/**\n * Reset instrumentation configuration (useful for testing)\n */\nexport function resetInstrumentationConfig(): void {\n globalConfig = null;\n}\n","/**\n * Metrics Collector Module\n *\n * OpenTelemetry-style metrics collection with counters, histograms,\n * and gauges for comprehensive service monitoring.\n *\n * @module instrumentation/metrics-collector\n * @category Observability\n */\n\nimport { isFeatureEnabled, isInstrumentationConfigInitialized } from './config.js';\nimport type { MetricDefinition } from './types.js';\n\n/**\n * Metric labels\n */\nexport type MetricLabels = Record<string, string>;\n\n/**\n * Counter metric interface\n */\nexport interface Counter {\n /** Add value to counter */\n add(value: number, labels?: MetricLabels): void;\n /** Increment counter by 1 */\n inc(labels?: MetricLabels): void;\n /** Get current value */\n getValue(labels?: MetricLabels): number;\n}\n\n/**\n * Histogram metric interface\n */\nexport interface Histogram {\n /** Record a value */\n record(value: number, labels?: MetricLabels): void;\n /** Get histogram data */\n getData(labels?: MetricLabels): HistogramData;\n}\n\n/**\n * Histogram data\n */\nexport interface HistogramData {\n count: number;\n sum: number;\n min: number;\n max: number;\n avg: number;\n buckets: Map<number, number>;\n percentiles: {\n p50: number;\n p75: number;\n p90: number;\n p95: number;\n p99: number;\n };\n}\n\n/**\n * Gauge metric interface\n */\nexport interface Gauge {\n /** Set gauge value */\n set(value: number, labels?: MetricLabels): void;\n /** Add to gauge value */\n add(value: number, labels?: MetricLabels): void;\n /** Subtract from gauge value */\n sub(value: number, labels?: MetricLabels): void;\n /** Get current value */\n getValue(labels?: MetricLabels): number;\n}\n\n/**\n * UpDownCounter metric interface (can go up or down)\n */\nexport interface UpDownCounter {\n /** Add value (can be negative) */\n add(value: number, labels?: MetricLabels): void;\n /** Get current value */\n getValue(labels?: MetricLabels): number;\n}\n\n/**\n * Default maximum distinct label combinations retained per metric before\n * routing new label sets into the bounded overflow bucket.\n */\nexport const DEFAULT_MAX_SERIES_PER_METRIC = 500;\n\n/**\n * Default process-level cap on total distinct label series across a\n * {@link MetricsRegistry} instance.\n */\nexport const DEFAULT_MAX_TOTAL_SERIES = 5000;\n\n/**\n * Internal label key used when a metric or registry reaches its cardinality\n * ceiling. Emits `{__overflow__=\"true\"}` in Prometheus exposition format.\n */\nexport const OVERFLOW_LABEL_KEY = '__overflow__=true';\n\nexport interface MetricsRegistryOptions {\n /** Maximum distinct label combinations per metric (default: 500). */\n maxSeriesPerMetric?: number;\n /** Maximum total distinct label series across the registry (default: 5000). */\n maxTotalSeries?: number;\n}\n\ninterface SeriesBudget {\n readonly maxSeriesPerMetric: number;\n tryReserveSeries(currentMetricSeriesCount: number): boolean;\n releaseSeries(count: number): void;\n}\n\n/**\n * Generate label key for storage\n */\nfunction getLabelKey(labels?: MetricLabels): string {\n if (!labels || Object.keys(labels).length === 0) return '';\n return Object.entries(labels)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(',');\n}\n\n/**\n * Escape a label value for the Prometheus text exposition format.\n *\n * The spec requires backslash, double quote, and line feed to be escaped.\n */\nfunction escapePrometheusLabelValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n');\n}\n\n/**\n * Render the internal label key (`k=v,k2=v2`) as Prometheus label pairs\n * (`k=\"v\",k2=\"v2\"`), without the surrounding braces.\n *\n * The internal key is a Map key, not an exposition fragment: it leaves values\n * unquoted. Interpolating it straight into `{...}` produced output such as\n * `svc_requests{service=tags} 1`, which Prometheus rejects as a parse error —\n * and a parse error fails the *entire* scrape, not just the offending line, so\n * every service exposing SDK metrics scraped as down.\n *\n * Values containing a comma remain ambiguous because the flat key cannot encode\n * them; such labels are dropped rather than emitted as malformed pairs.\n */\n/**\n * Sanitize a metric name for the Prometheus text exposition format\n * (`[a-zA-Z_:][a-zA-Z0-9_:]*`). Registry names follow OTel conventions and\n * may contain dots (e.g. `resource_caps.plan_resolution_total`), but a dot in\n * an exposed metric name is a parse error — and a parse error fails the\n * ENTIRE scrape, so one dotted counter made every service that registered it\n * report as down (BOFF-6343: auth/tenant/devportal/tags/... all up==0 in AMP\n * while rbac, which never registers resource-caps counters, scraped fine).\n * Same failure class as the unquoted-label bug fixed above: sanitize at the\n * exposition boundary, exactly like the official OTel Prometheus exporters.\n */\nfunction sanitizePrometheusMetricName(name: string): string {\n const sanitized = name.replace(/[^a-zA-Z0-9_:]/g, '_');\n return /^[a-zA-Z_:]/.test(sanitized) ? sanitized : `_${sanitized}`;\n}\n\nfunction formatPrometheusLabelPairs(labelKey: string): string {\n if (!labelKey) return '';\n const pairs: string[] = [];\n for (const part of labelKey.split(',')) {\n const eq = part.indexOf('=');\n if (eq <= 0) continue;\n const name = part.slice(0, eq);\n const value = part.slice(eq + 1);\n pairs.push(`${name}=\"${escapePrometheusLabelValue(value)}\"`);\n }\n return pairs.join(',');\n}\n\n/**\n * Shared cardinality-bounded series store for all in-memory metrics.\n */\nabstract class InMemorySeriesStore<T> {\n protected values: Map<string, T> = new Map();\n private readonly name: string;\n private readonly description: string;\n private readonly budget: SeriesBudget;\n\n constructor(name: string, description: string, budget: SeriesBudget) {\n this.name = name;\n this.description = description;\n this.budget = budget;\n }\n\n protected resolveKeyForWrite(labels: MetricLabels | undefined, initOverflow: () => T): string {\n const key = getLabelKey(labels);\n if (this.values.has(key)) return key;\n if (this.budget.tryReserveSeries(this.values.size)) {\n return key;\n }\n if (!this.values.has(OVERFLOW_LABEL_KEY)) {\n this.values.set(OVERFLOW_LABEL_KEY, initOverflow());\n }\n return OVERFLOW_LABEL_KEY;\n }\n\n getName(): string {\n return this.name;\n }\n\n getDescription(): string {\n return this.description;\n }\n\n reset(): void {\n const trackedCount = this.values.has(OVERFLOW_LABEL_KEY) ? this.values.size - 1 : this.values.size;\n if (trackedCount > 0) this.budget.releaseSeries(trackedCount);\n this.values.clear();\n }\n}\n\n/**\n * Shared scalar numeric metric base (counters, gauges, up-down counters).\n */\nabstract class InMemoryNumericMetric extends InMemorySeriesStore<number> {\n add(value: number, labels?: MetricLabels): void {\n const key = this.resolveKeyForWrite(labels, () => 0);\n const current = this.values.get(key) || 0;\n this.values.set(key, current + value);\n }\n\n getValue(labels?: MetricLabels): number {\n const key = getLabelKey(labels);\n return this.values.get(key) || 0;\n }\n\n getAllValues(): Map<string, number> {\n return new Map(this.values);\n }\n}\n\n/**\n * In-memory counter implementation\n */\nclass InMemoryCounter extends InMemoryNumericMetric implements Counter {\n inc(labels?: MetricLabels): void {\n this.add(1, labels);\n }\n}\n\n/** Default bucket upper bounds (milliseconds-oriented) when none are supplied. */\nconst DEFAULT_HISTOGRAM_BOUNDARIES: readonly number[] = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];\n\n/**\n * Number of recent observations kept per label set for `getData()` percentiles.\n * The reservoir is never exported to Prometheus; it only feeds the in-process\n * percentile estimate.\n */\nexport const HISTOGRAM_PERCENTILE_RESERVOIR_SIZE = 10_000;\n\n/**\n * Normalise caller-supplied bucket boundaries: drop non-finite values (the\n * `+Inf` bucket is always emitted separately), de-duplicate, and sort\n * ascending, because Prometheus requires `le` to increase along the series.\n */\nfunction normaliseBoundaries(boundaries?: number[]): number[] {\n const source = boundaries ?? DEFAULT_HISTOGRAM_BOUNDARIES;\n return [...new Set(source.filter((b) => Number.isFinite(b)))].sort((a, b) => a - b);\n}\n\n/**\n * Cumulative state for one label set of a histogram.\n *\n * `bucketCounts`, `count` and `sum` only ever grow (for non-negative\n * observations), which is what Prometheus expects from a histogram: rate(),\n * increase() and histogram_quantile() all treat a decrease as a counter reset.\n * The previous implementation stored the last 10,000 raw values and derived the\n * exported series from that sliding window, so `_count` froze at 10,000 and\n * `_sum`/`_bucket` went down whenever a large value was evicted (BOFF-14872).\n */\ninterface HistogramSeries {\n /** Non-cumulative count per finite boundary, same order as the boundaries. */\n bucketCounts: number[];\n count: number;\n sum: number;\n min: number;\n max: number;\n /** Ring buffer of recent observations, used only for percentile estimates. */\n reservoir: number[];\n /** Next write position in `reservoir` once it is full. */\n reservoirNext: number;\n}\n\n/**\n * Point-in-time cumulative view of one histogram series, as exported to\n * Prometheus. Building it is O(buckets): no sorting, no scan of observations.\n */\ninterface HistogramExportSnapshot {\n /** Cumulative counts keyed by upper bound, ending with `Infinity`. */\n buckets: Map<number, number>;\n count: number;\n sum: number;\n}\n\n/**\n * In-memory cumulative histogram implementation\n */\nclass InMemoryHistogram extends InMemorySeriesStore<HistogramSeries> implements Histogram {\n private readonly boundaries: number[];\n\n constructor(name: string, description: string, budget: SeriesBudget, boundaries?: number[]) {\n super(name, description, budget);\n this.boundaries = normaliseBoundaries(boundaries);\n }\n\n private createEmptySeries(initialValue: number): HistogramSeries {\n return {\n bucketCounts: new Array<number>(this.boundaries.length).fill(0),\n count: 0,\n sum: 0,\n min: initialValue,\n max: initialValue,\n reservoir: [],\n reservoirNext: 0,\n };\n }\n\n record(value: number, labels?: MetricLabels): void {\n // NaN would poison `_sum` permanently; Prometheus client libraries ignore it too.\n if (Number.isNaN(value)) return;\n\n const key = this.resolveKeyForWrite(labels, () => this.createEmptySeries(value));\n let series = this.values.get(key);\n if (!series) {\n series = this.createEmptySeries(value);\n this.values.set(key, series);\n }\n\n const bucketIndex = this.findBucketIndex(value);\n if (bucketIndex < series.bucketCounts.length) {\n series.bucketCounts[bucketIndex] = (series.bucketCounts[bucketIndex] ?? 0) + 1;\n }\n series.count += 1;\n series.sum += value;\n if (value < series.min) series.min = value;\n if (value > series.max) series.max = value;\n\n if (series.reservoir.length < HISTOGRAM_PERCENTILE_RESERVOIR_SIZE) {\n series.reservoir.push(value);\n } else {\n series.reservoir[series.reservoirNext] = value;\n series.reservoirNext = (series.reservoirNext + 1) % HISTOGRAM_PERCENTILE_RESERVOIR_SIZE;\n }\n }\n\n /**\n * Index of the first boundary `>= value` (binary search), or\n * `boundaries.length` when the value only falls in the `+Inf` bucket.\n */\n private findBucketIndex(value: number): number {\n let lo = 0;\n let hi = this.boundaries.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (value <= (this.boundaries[mid] ?? Infinity)) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return lo;\n }\n\n private cumulativeBuckets(series: HistogramSeries): Map<number, number> {\n const buckets = new Map<number, number>();\n let running = 0;\n this.boundaries.forEach((boundary, index) => {\n running += series.bucketCounts[index] ?? 0;\n buckets.set(boundary, running);\n });\n buckets.set(Infinity, series.count);\n return buckets;\n }\n\n /**\n * `count`, `sum`, `min`, `max`, `avg` and `buckets` cover every observation\n * since the series was created (or last reset). `percentiles` are estimated\n * from the most recent {@link HISTOGRAM_PERCENTILE_RESERVOIR_SIZE}\n * observations only.\n */\n getData(labels?: MetricLabels): HistogramData {\n const series = this.values.get(getLabelKey(labels));\n\n if (!series || series.count === 0) {\n return {\n count: 0,\n sum: 0,\n min: 0,\n max: 0,\n avg: 0,\n buckets: new Map(),\n percentiles: { p50: 0, p75: 0, p90: 0, p95: 0, p99: 0 },\n };\n }\n\n const sorted = [...series.reservoir].sort((a, b) => a - b);\n const percentile = (p: number): number => {\n const index = Math.ceil((p / 100) * sorted.length) - 1;\n return sorted[Math.max(0, index)] ?? 0;\n };\n\n return {\n count: series.count,\n sum: series.sum,\n min: series.min,\n max: series.max,\n avg: series.sum / series.count,\n buckets: this.cumulativeBuckets(series),\n percentiles: {\n p50: percentile(50),\n p75: percentile(75),\n p90: percentile(90),\n p95: percentile(95),\n p99: percentile(99),\n },\n };\n }\n\n getAllData(): Map<string, HistogramData> {\n const result = new Map<string, HistogramData>();\n for (const key of this.values.keys()) {\n result.set(key, this.getData(key ? this.parseLabels(key) : undefined));\n }\n return result;\n }\n\n /**\n * Cumulative series for the Prometheus exposition, keyed by internal label\n * key. Cheap per scrape: it never sorts or walks the percentile reservoir.\n */\n getExportSnapshots(): Map<string, HistogramExportSnapshot> {\n const result = new Map<string, HistogramExportSnapshot>();\n for (const [key, series] of this.values) {\n result.set(key, { buckets: this.cumulativeBuckets(series), count: series.count, sum: series.sum });\n }\n return result;\n }\n\n private parseLabels(key: string): MetricLabels {\n const labels: MetricLabels = {};\n for (const part of key.split(',')) {\n const eq = part.indexOf('=');\n if (eq <= 0) continue;\n labels[part.slice(0, eq)] = part.slice(eq + 1);\n }\n return labels;\n }\n}\n\n/**\n * In-memory gauge implementation\n */\nclass InMemoryGauge extends InMemoryNumericMetric implements Gauge {\n set(value: number, labels?: MetricLabels): void {\n const key = this.resolveKeyForWrite(labels, () => 0);\n this.values.set(key, value);\n }\n\n sub(value: number, labels?: MetricLabels): void {\n this.add(-value, labels);\n }\n}\n\n/**\n * In-memory UpDownCounter implementation\n */\nclass InMemoryUpDownCounter extends InMemoryNumericMetric implements UpDownCounter {}\n\n/**\n * No-op implementations for when metrics are disabled\n */\nclass NoOpCounter implements Counter {\n add(): void {}\n inc(): void {}\n getValue(): number {\n return 0;\n }\n}\n\nclass NoOpHistogram implements Histogram {\n record(): void {}\n getData(): HistogramData {\n return {\n count: 0,\n sum: 0,\n min: 0,\n max: 0,\n avg: 0,\n buckets: new Map(),\n percentiles: { p50: 0, p75: 0, p90: 0, p95: 0, p99: 0 },\n };\n }\n}\n\nclass NoOpGauge implements Gauge {\n set(): void {}\n add(): void {}\n sub(): void {}\n getValue(): number {\n return 0;\n }\n}\n\nclass NoOpUpDownCounter implements UpDownCounter {\n add(): void {}\n getValue(): number {\n return 0;\n }\n}\n\n/**\n * Metrics registry for managing all metrics\n */\nexport class MetricsRegistry {\n private counters: Map<string, InMemoryCounter> = new Map();\n private histograms: Map<string, InMemoryHistogram> = new Map();\n private gauges: Map<string, InMemoryGauge> = new Map();\n private upDownCounters: Map<string, InMemoryUpDownCounter> = new Map();\n private serviceName: string;\n private metricPrefix: string;\n private readonly maxSeriesPerMetric: number;\n private readonly maxTotalSeries: number;\n private totalSeriesCount = 0;\n private readonly budget: SeriesBudget;\n\n constructor(serviceName = 'unknown-service', metricPrefix = '', options: MetricsRegistryOptions = {}) {\n this.serviceName = serviceName;\n this.metricPrefix = metricPrefix;\n this.maxSeriesPerMetric = Math.max(1, Math.floor(options.maxSeriesPerMetric ?? DEFAULT_MAX_SERIES_PER_METRIC));\n this.maxTotalSeries = Math.max(1, Math.floor(options.maxTotalSeries ?? DEFAULT_MAX_TOTAL_SERIES));\n this.budget = {\n maxSeriesPerMetric: this.maxSeriesPerMetric,\n tryReserveSeries: (currentMetricSeriesCount: number): boolean => {\n if (currentMetricSeriesCount >= this.maxSeriesPerMetric || this.totalSeriesCount >= this.maxTotalSeries) {\n return false;\n }\n this.totalSeriesCount += 1;\n return true;\n },\n releaseSeries: (count: number): void => {\n this.totalSeriesCount = Math.max(0, this.totalSeriesCount - count);\n },\n };\n }\n\n /** Number of tracked non-overflow label series currently held across this registry. */\n getTotalSeriesCount(): number {\n return this.totalSeriesCount;\n }\n\n /** Configured process-level series cap for this registry. */\n getMaxTotalSeries(): number {\n return this.maxTotalSeries;\n }\n\n /** Configured per-metric series cap for this registry. */\n getMaxSeriesPerMetric(): number {\n return this.maxSeriesPerMetric;\n }\n\n /**\n * Get service name\n */\n getServiceName(): string {\n return this.serviceName;\n }\n\n /**\n * Check if metrics are enabled\n */\n private isEnabled(): boolean {\n return isInstrumentationConfigInitialized() && isFeatureEnabled('metrics');\n }\n\n /**\n * Get prefixed metric name\n */\n private getPrefixedName(name: string): string {\n return this.metricPrefix ? `${this.metricPrefix}_${name}` : name;\n }\n\n /**\n * Create or get a counter\n */\n createCounter(name: string, description: string): Counter {\n if (!this.isEnabled()) {\n return new NoOpCounter();\n }\n\n const prefixedName = this.getPrefixedName(name);\n let counter = this.counters.get(prefixedName);\n if (!counter) {\n counter = new InMemoryCounter(prefixedName, description, this.budget);\n this.counters.set(prefixedName, counter);\n }\n return counter;\n }\n\n /**\n * Create or get a histogram\n */\n createHistogram(name: string, description: string, boundaries?: number[]): Histogram {\n if (!this.isEnabled()) {\n return new NoOpHistogram();\n }\n\n const prefixedName = this.getPrefixedName(name);\n let histogram = this.histograms.get(prefixedName);\n if (!histogram) {\n histogram = new InMemoryHistogram(prefixedName, description, this.budget, boundaries);\n this.histograms.set(prefixedName, histogram);\n }\n return histogram;\n }\n\n /**\n * Create or get a gauge\n */\n createGauge(name: string, description: string): Gauge {\n if (!this.isEnabled()) {\n return new NoOpGauge();\n }\n\n const prefixedName = this.getPrefixedName(name);\n let gauge = this.gauges.get(prefixedName);\n if (!gauge) {\n gauge = new InMemoryGauge(prefixedName, description, this.budget);\n this.gauges.set(prefixedName, gauge);\n }\n return gauge;\n }\n\n /**\n * Create or get an up-down counter\n */\n createUpDownCounter(name: string, description: string): UpDownCounter {\n if (!this.isEnabled()) {\n return new NoOpUpDownCounter();\n }\n\n const prefixedName = this.getPrefixedName(name);\n let counter = this.upDownCounters.get(prefixedName);\n if (!counter) {\n counter = new InMemoryUpDownCounter(prefixedName, description, this.budget);\n this.upDownCounters.set(prefixedName, counter);\n }\n return counter;\n }\n\n /**\n * Create metric from definition\n */\n createFromDefinition(definition: MetricDefinition): Counter | Histogram | Gauge | UpDownCounter {\n switch (definition.type) {\n case 'counter':\n return this.createCounter(definition.name, definition.description);\n case 'histogram':\n return this.createHistogram(definition.name, definition.description, definition.boundaries);\n case 'gauge':\n return this.createGauge(definition.name, definition.description);\n case 'upDownCounter':\n return this.createUpDownCounter(definition.name, definition.description);\n default:\n throw new Error(`Unknown metric type: ${definition.type}`);\n }\n }\n\n /**\n * Get all metrics data\n */\n getAllMetrics(): {\n counters: Array<{ name: string; description: string; values: Map<string, number> }>;\n histograms: Array<{ name: string; description: string; data: Map<string, HistogramData> }>;\n gauges: Array<{ name: string; description: string; values: Map<string, number> }>;\n upDownCounters: Array<{ name: string; description: string; values: Map<string, number> }>;\n } {\n return {\n counters: Array.from(this.counters.values()).map((c) => ({\n name: c.getName(),\n description: c.getDescription(),\n values: c.getAllValues(),\n })),\n histograms: Array.from(this.histograms.values()).map((h) => ({\n name: h.getName(),\n description: h.getDescription(),\n data: h.getAllData(),\n })),\n gauges: Array.from(this.gauges.values()).map((g) => ({\n name: g.getName(),\n description: g.getDescription(),\n values: g.getAllValues(),\n })),\n upDownCounters: Array.from(this.upDownCounters.values()).map((c) => ({\n name: c.getName(),\n description: c.getDescription(),\n values: c.getAllValues(),\n })),\n };\n }\n\n /**\n * Export counter metrics to Prometheus format\n */\n private exportCountersToPrometheus(lines: string[]): void {\n for (const counter of this.counters.values()) {\n const name = sanitizePrometheusMetricName(counter.getName());\n lines.push(`# HELP ${name} ${counter.getDescription()}`);\n lines.push(`# TYPE ${name} counter`);\n for (const [labels, value] of counter.getAllValues()) {\n const pairs = formatPrometheusLabelPairs(labels);\n const labelStr = pairs ? `{${pairs}}` : '';\n lines.push(`${name}${labelStr} ${value}`);\n }\n }\n }\n\n /**\n * Export histogram metrics to Prometheus format\n */\n private exportHistogramsToPrometheus(lines: string[]): void {\n for (const histogram of this.histograms.values()) {\n const name = sanitizePrometheusMetricName(histogram.getName());\n lines.push(`# HELP ${name} ${histogram.getDescription()}`);\n lines.push(`# TYPE ${name} histogram`);\n for (const [labels, data] of histogram.getExportSnapshots()) {\n const pairs = formatPrometheusLabelPairs(labels);\n const labelStr = pairs ? `,${pairs}` : '';\n for (const [le, count] of data.buckets) {\n const leStr = le === Infinity ? '+Inf' : le.toString();\n lines.push(`${name}_bucket{le=\"${leStr}\"${labelStr}} ${count}`);\n }\n lines.push(`${name}_sum{${pairs}} ${data.sum}`);\n lines.push(`${name}_count{${pairs}} ${data.count}`);\n }\n }\n }\n\n /**\n * Export gauge metrics to Prometheus format\n */\n private exportGaugesToPrometheus(lines: string[]): void {\n for (const gauge of this.gauges.values()) {\n const name = sanitizePrometheusMetricName(gauge.getName());\n lines.push(`# HELP ${name} ${gauge.getDescription()}`);\n lines.push(`# TYPE ${name} gauge`);\n for (const [labels, value] of gauge.getAllValues()) {\n const pairs = formatPrometheusLabelPairs(labels);\n const labelStr = pairs ? `{${pairs}}` : '';\n lines.push(`${name}${labelStr} ${value}`);\n }\n }\n }\n\n /**\n * Export up-down counter metrics to Prometheus format (as gauges)\n */\n private exportUpDownCountersToPrometheus(lines: string[]): void {\n for (const counter of this.upDownCounters.values()) {\n const name = sanitizePrometheusMetricName(counter.getName());\n lines.push(`# HELP ${name} ${counter.getDescription()}`);\n lines.push(`# TYPE ${name} gauge`);\n for (const [labels, value] of counter.getAllValues()) {\n const pairs = formatPrometheusLabelPairs(labels);\n const labelStr = pairs ? `{${pairs}}` : '';\n lines.push(`${name}${labelStr} ${value}`);\n }\n }\n }\n\n /**\n * Export metrics in Prometheus format\n */\n toPrometheusFormat(): string {\n const lines: string[] = [];\n\n this.exportCountersToPrometheus(lines);\n this.exportHistogramsToPrometheus(lines);\n this.exportGaugesToPrometheus(lines);\n this.exportUpDownCountersToPrometheus(lines);\n\n return lines.join('\\n');\n }\n\n /**\n * Reset all metrics\n */\n reset(): void {\n for (const counter of this.counters.values()) {\n counter.reset();\n }\n for (const histogram of this.histograms.values()) {\n histogram.reset();\n }\n for (const gauge of this.gauges.values()) {\n gauge.reset();\n }\n for (const counter of this.upDownCounters.values()) {\n counter.reset();\n }\n }\n\n /**\n * Clear all metrics (remove registrations)\n */\n clear(): void {\n this.counters.clear();\n this.histograms.clear();\n this.gauges.clear();\n this.upDownCounters.clear();\n this.totalSeriesCount = 0;\n }\n}\n\n/**\n * Global metrics registry\n */\nlet globalRegistry: MetricsRegistry | null = null;\n\n/**\n * Initialize global metrics registry\n */\nexport function initializeMetricsRegistry(\n serviceName: string,\n metricPrefix = '',\n options?: MetricsRegistryOptions\n): MetricsRegistry {\n globalRegistry = new MetricsRegistry(serviceName, metricPrefix, options);\n return globalRegistry;\n}\n\n/**\n * Get global metrics registry\n */\nexport function getMetricsRegistry(): MetricsRegistry {\n if (!globalRegistry) {\n globalRegistry = new MetricsRegistry('unknown-service');\n }\n return globalRegistry;\n}\n\n/**\n * Check if metrics registry is initialized\n */\nexport function isMetricsRegistryInitialized(): boolean {\n return globalRegistry !== null;\n}\n\n/**\n * Reset global metrics registry (useful for testing)\n */\nexport function resetMetricsRegistry(): void {\n if (globalRegistry) {\n globalRegistry.clear();\n }\n globalRegistry = null;\n}\n\n/**\n * Convenience functions for creating metrics\n */\nexport function createCounter(name: string, description: string): Counter {\n return getMetricsRegistry().createCounter(name, description);\n}\n\nexport function createHistogram(name: string, description: string, boundaries?: number[]): Histogram {\n return getMetricsRegistry().createHistogram(name, description, boundaries);\n}\n\nexport function createGauge(name: string, description: string): Gauge {\n return getMetricsRegistry().createGauge(name, description);\n}\n\nexport function createUpDownCounter(name: string, description: string): UpDownCounter {\n return getMetricsRegistry().createUpDownCounter(name, description);\n}\n"],"mappings":";;;;AA0BA,MAAa,WAAW;CAEtB,yBAAyB;CAGzB,yBAAyB;CACzB,yBAAyB;CACzB,yBAAyB;CACzB,yBAAyB;CACzB,0BAA0B;CAC1B,sBAAsB;CACtB,uBAAuB;CACvB,6BAA6B;CAG7B,mBAAmB;CACnB,sBAAsB;CACtB,kBAAkB;CA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A,eAAe,IACf,SACiB;CACjB,iBAAiB,IAAI,gBAAgB,aAAa,cAAc,OAAO;CACvE,OAAO;AACT;;;;AAKA,SAAgB,qBAAsC;CACpD,IAAI,CAAC,gBACH,iBAAiB,IAAI,gBAAgB,iBAAiB;CAExD,OAAO;AACT;;;;AAKA,SAAgB,+BAAwC;CACtD,OAAO,mBAAmB;AAC5B;;;;AAKA,SAAgB,uBAA6B;CAC3C,IAAI,gBACF,eAAe,MAAM;CAEvB,iBAAiB;AACnB;;;;AAKA,SAAgB,cAAc,MAAc,aAA8B;CACxE,OAAO,mBAAmB,CAAC,CAAC,cAAc,MAAM,WAAW;AAC7D;AAEA,SAAgB,gBAAgB,MAAc,aAAqB,YAAkC;CACnG,OAAO,mBAAmB,CAAC,CAAC,gBAAgB,MAAM,aAAa,UAAU;AAC3E;AAEA,SAAgB,YAAY,MAAc,aAA4B;CACpE,OAAO,mBAAmB,CAAC,CAAC,YAAY,MAAM,WAAW;AAC3D;AAEA,SAAgB,oBAAoB,MAAc,aAAoC;CACpF,OAAO,mBAAmB,CAAC,CAAC,oBAAoB,MAAM,WAAW;AACnE"}
@@ -1,6 +1,7 @@
1
1
  import { a as logger } from "./logger-B6rCpb7D.js";
2
2
  import { i as safeStringify } from "./EventQueueFactory-BhNJE93c.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { createHash } from "node:crypto";
4
5
  import { PrismaPg } from "@prisma/adapter-pg";
5
6
  import { Pool } from "pg";
6
7
 
@@ -560,6 +561,92 @@ function ensureServiceApplicationName(productName) {
560
561
  function createPrismaAdapter(pool) {
561
562
  return new PrismaPg(pool);
562
563
  }
564
+ function isIdentifierChar(ch) {
565
+ if (!ch) return false;
566
+ const code = ch.charCodeAt(0);
567
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
568
+ }
569
+ function isDigitChar(ch) {
570
+ if (!ch) return false;
571
+ const code = ch.charCodeAt(0);
572
+ return code >= 48 && code <= 57;
573
+ }
574
+ function scanSingleQuotedLiteral(sql, quoteStart) {
575
+ let i = quoteStart + 1;
576
+ while (i < sql.length) {
577
+ if (sql[i] === "'") {
578
+ if (sql[i + 1] === "'") {
579
+ i += 2;
580
+ continue;
581
+ }
582
+ return i + 1;
583
+ }
584
+ i += 1;
585
+ }
586
+ return sql.length;
587
+ }
588
+ function matchDollarQuoteTag(sql, start) {
589
+ if (sql[start] !== "$") return null;
590
+ let i = start + 1;
591
+ if (sql[i] === "$") return "$$";
592
+ if (!isIdentifierChar(sql[i]) || isDigitChar(sql[i])) return null;
593
+ while (i < sql.length && isIdentifierChar(sql[i])) i += 1;
594
+ return sql[i] === "$" ? sql.slice(start, i + 1) : null;
595
+ }
596
+ /**
597
+ * Normalize a SQL query string into a value-free template by stripping inline
598
+ * string, dollar-quoted, hex/bit/escape, and numeric literals (preserving
599
+ * positional `$1`, `$2`, ... placeholders) in a single linear pass.
600
+ */
601
+ function normalizeSqlTemplate(sql) {
602
+ const out = [];
603
+ let i = 0;
604
+ while (i < sql.length) {
605
+ const ch = sql[i];
606
+ const prev = i > 0 ? sql[i - 1] : void 0;
607
+ if (ch === "$") {
608
+ const tag = matchDollarQuoteTag(sql, i);
609
+ if (tag) {
610
+ const closeIdx = sql.indexOf(tag, i + tag.length);
611
+ out.push("'?'");
612
+ i = closeIdx >= 0 ? closeIdx + tag.length : sql.length;
613
+ continue;
614
+ }
615
+ }
616
+ if ((ch === "e" || ch === "E" || ch === "x" || ch === "X" || ch === "b" || ch === "B") && sql[i + 1] === "'" && !isIdentifierChar(prev)) {
617
+ out.push("'?'");
618
+ i = scanSingleQuotedLiteral(sql, i + 1);
619
+ continue;
620
+ }
621
+ if (ch === "'") {
622
+ out.push("'?'");
623
+ i = scanSingleQuotedLiteral(sql, i);
624
+ continue;
625
+ }
626
+ if (isDigitChar(ch) && prev !== "$" && !isIdentifierChar(prev)) {
627
+ let end = i + 1;
628
+ while (end < sql.length && isDigitChar(sql[end])) end += 1;
629
+ if (sql[end] === "." && isDigitChar(sql[end + 1])) {
630
+ end += 2;
631
+ while (end < sql.length && isDigitChar(sql[end])) end += 1;
632
+ }
633
+ if (!isIdentifierChar(sql[end])) {
634
+ out.push("?");
635
+ i = end;
636
+ continue;
637
+ }
638
+ }
639
+ out.push(ch);
640
+ i += 1;
641
+ }
642
+ return out.join("").replace(/\s+/g, " ").trim();
643
+ }
644
+ /**
645
+ * Stable short SHA-256 fingerprint for a normalized SQL query template.
646
+ */
647
+ function fingerprintSqlQuery(normalizedQuery) {
648
+ return createHash("sha256").update(normalizedQuery).digest("hex").slice(0, 16);
649
+ }
563
650
  /**
564
651
  * Configure Prisma client logging
565
652
  */
@@ -568,13 +655,16 @@ function configurePrismaLogging(client, config) {
568
655
  const slowQueryThreshold = config.slowQueryThreshold ?? (isDevelopment ? 100 : 500);
569
656
  if (config.enableQueryLogging ?? isDevelopment) client.$on("query", (e) => {
570
657
  if ("query" in e && "duration" in e) {
658
+ const normalizedQuery = normalizeSqlTemplate(e.query);
659
+ const queryFingerprint = fingerprintSqlQuery(normalizedQuery);
571
660
  if (e.duration > slowQueryThreshold) logger.warn("[Prisma] Slow query detected", {
572
- query: e.query.substring(0, 200) + (e.query.length > 200 ? "..." : ""),
573
- params: e.params,
661
+ query: normalizedQuery.substring(0, 200) + (normalizedQuery.length > 200 ? "..." : ""),
662
+ queryFingerprint,
574
663
  duration: `${e.duration}ms`
575
664
  });
576
665
  else logger.debug("[Prisma] Query", {
577
- query: e.query.substring(0, 100) + (e.query.length > 100 ? "..." : ""),
666
+ query: normalizedQuery.substring(0, 100) + (normalizedQuery.length > 100 ? "..." : ""),
667
+ queryFingerprint,
578
668
  duration: `${e.duration}ms`
579
669
  });
580
670
  }
@@ -1239,5 +1329,5 @@ function addGraphExtension(baseClient, config) {
1239
1329
  } } });
1240
1330
  }
1241
1331
 
1242
- export { shouldSyncEntity as _, createConnectionPool as a, ensureServiceApplicationName as c, createEntityEvent as d, createRelationshipEvent as f, parseRelationship as g, getCollectionForEntity as h, configurePrismaLogging as i, installAcquireRetry as l, extractMinimalFields as m, withDeferredGraphEvents as n, createPrismaAdapter as o, extractEntityTitle as p, PrismaClientWrapper as r, createPrismaClient as s, addGraphExtension as t, isTransientAcquireError as u, shouldSyncRelationship as v, GraphRegistry as y };
1243
- //# sourceMappingURL=middleware-B9eyLP7A.js.map
1332
+ export { getCollectionForEntity as _, createConnectionPool as a, shouldSyncRelationship as b, ensureServiceApplicationName as c, isTransientAcquireError as d, normalizeSqlTemplate as f, extractMinimalFields as g, extractEntityTitle as h, configurePrismaLogging as i, fingerprintSqlQuery as l, createRelationshipEvent as m, withDeferredGraphEvents as n, createPrismaAdapter as o, createEntityEvent as p, PrismaClientWrapper as r, createPrismaClient as s, addGraphExtension as t, installAcquireRetry as u, parseRelationship as v, GraphRegistry as x, shouldSyncEntity as y };
1333
+ //# sourceMappingURL=middleware-z8KzMFU_.js.map