api-sentinel-express 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,1124 @@
1
+ // src/config/defaults.js
2
+ var DEFAULT_CONFIG = Object.freeze({
3
+ slowRequestThresholdMs: 500,
4
+ maxRecentRequests: 200,
5
+ maxRouteEntries: 100,
6
+ windowSampleSize: 1e3,
7
+ requestIdHeader: "X-Request-ID",
8
+ trustIncomingRequestId: false,
9
+ fallbackRouteLabel: "/__overflow_routes__",
10
+ unmatchedRouteLabel: "/__unmatched__",
11
+ logging: Object.freeze({
12
+ enabled: true,
13
+ logAllRequests: false,
14
+ logSlowRequests: true,
15
+ logServerErrors: true,
16
+ logClientErrors: false
17
+ })
18
+ });
19
+ var CONFIG_BOUNDS = Object.freeze({
20
+ slowRequestThresholdMs: { min: 1, max: 36e5 },
21
+ maxRecentRequests: { min: 1, max: 5e4 },
22
+ maxRouteEntries: { min: 2, max: 1e4 },
23
+ windowSampleSize: { min: 10, max: 5e4 }
24
+ });
25
+
26
+ // src/core/percentile.js
27
+ function roundDuration(value) {
28
+ if (!Number.isFinite(value) || value <= 0) {
29
+ return 0;
30
+ }
31
+ return Math.round(value * 100) / 100;
32
+ }
33
+ function calculatePercentile(samples, percentile = 95) {
34
+ if (typeof percentile !== "number" || percentile <= 0 || percentile > 100 || !Number.isFinite(percentile)) {
35
+ throw new RangeError(
36
+ `Invalid percentile "${percentile}": must be a number in the range (0, 100].`
37
+ );
38
+ }
39
+ if (!Array.isArray(samples) || samples.length === 0) {
40
+ return 0;
41
+ }
42
+ const count = samples.length;
43
+ if (count === 1) {
44
+ return roundDuration(samples[0] ?? 0);
45
+ }
46
+ const sorted = [...samples].sort((a, b) => a - b);
47
+ const rankIndex = Math.min(
48
+ sorted.length - 1,
49
+ Math.max(0, Math.ceil(percentile / 100 * count) - 1)
50
+ );
51
+ return roundDuration(sorted[rankIndex] ?? 0);
52
+ }
53
+ var RollingWindowSampler = class {
54
+ /**
55
+ * @param {number} [capacity=1000] - Maximum number of samples retained in the rolling window.
56
+ */
57
+ constructor(capacity = 1e3) {
58
+ if (!Number.isInteger(capacity) || capacity < 1) {
59
+ throw new RangeError("RollingWindowSampler capacity must be a positive integer.");
60
+ }
61
+ this.capacity = capacity;
62
+ this.buffer = new Float64Array(capacity);
63
+ this.writeIndex = 0;
64
+ this.currentSize = 0;
65
+ }
66
+ /**
67
+ * Adds a new latency sample (in milliseconds) to the rolling window in O(1) time.
68
+ *
69
+ * @param {number} durationMs - Observed latency in milliseconds.
70
+ */
71
+ add(durationMs) {
72
+ if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0) {
73
+ return;
74
+ }
75
+ this.buffer[this.writeIndex] = durationMs;
76
+ this.writeIndex = (this.writeIndex + 1) % this.capacity;
77
+ if (this.currentSize < this.capacity) {
78
+ this.currentSize += 1;
79
+ }
80
+ }
81
+ /**
82
+ * Returns the current number of active samples in the rolling window (0 <= size <= capacity).
83
+ *
84
+ * @returns {number} Active sample count.
85
+ */
86
+ size() {
87
+ return this.currentSize;
88
+ }
89
+ /**
90
+ * Extracts a copy of the active samples currently stored in the ring buffer.
91
+ *
92
+ * @returns {number[]} Detached array of active latency samples.
93
+ */
94
+ getSamples() {
95
+ const result = new Array(this.currentSize);
96
+ for (let i = 0; i < this.currentSize; i += 1) {
97
+ result[i] = this.buffer[i] ?? 0;
98
+ }
99
+ return result;
100
+ }
101
+ /**
102
+ * Computes the target percentile (defaults to 95th percentile) over the current rolling window.
103
+ *
104
+ * @param {number} [percentile=95] - Target percentile (0, 100].
105
+ * @returns {number} Percentile latency in milliseconds.
106
+ */
107
+ getPercentile(percentile = 95) {
108
+ if (this.currentSize === 0) {
109
+ return 0;
110
+ }
111
+ return calculatePercentile(this.getSamples(), percentile);
112
+ }
113
+ /**
114
+ * Clears all samples in the rolling window.
115
+ */
116
+ reset() {
117
+ this.writeIndex = 0;
118
+ this.currentSize = 0;
119
+ this.buffer.fill(0);
120
+ }
121
+ };
122
+
123
+ // src/core/metrics-collector.js
124
+ var MetricsCollector = class {
125
+ /**
126
+ * @param {object} config - Resolved API Sentinel configuration.
127
+ */
128
+ constructor(config) {
129
+ this.config = config;
130
+ this.startedAt = /* @__PURE__ */ new Date();
131
+ this.totalRequests = 0;
132
+ this.informationalRequests = 0;
133
+ this.successfulRequests = 0;
134
+ this.redirectRequests = 0;
135
+ this.notModifiedRequests = 0;
136
+ this.clientErrorRequests = 0;
137
+ this.serverErrorRequests = 0;
138
+ this.notFoundRequests = 0;
139
+ this.unmatchedRouteRequests = 0;
140
+ this.slowRequests = 0;
141
+ this.abortedRequests = 0;
142
+ this.cardinalityOverflowCount = 0;
143
+ this.totalDurationMs = 0;
144
+ this.minDurationMs = Number.POSITIVE_INFINITY;
145
+ this.maxDurationMs = 0;
146
+ this.globalLatencySampler = new RollingWindowSampler(config.windowSampleSize);
147
+ this.statusDistribution = {
148
+ "1xx": 0,
149
+ "2xx": 0,
150
+ "3xx": 0,
151
+ "4xx": 0,
152
+ "5xx": 0
153
+ };
154
+ this.statusCodeCounts = /* @__PURE__ */ new Map();
155
+ this.endpoints = /* @__PURE__ */ new Map();
156
+ this.recentRequestsBuffer = new Array(config.maxRecentRequests);
157
+ this.recentWriteIndex = 0;
158
+ this.recentCount = 0;
159
+ }
160
+ /**
161
+ * Records a completed HTTP request into global counters, recent request history,
162
+ * and per-endpoint analytics.
163
+ *
164
+ * @param {object} record - Completed request telemetry record.
165
+ */
166
+ recordRequest(record) {
167
+ const duration = roundDuration(record.durationMs);
168
+ const status = record.statusCode;
169
+ this.totalRequests += 1;
170
+ this.totalDurationMs += duration;
171
+ if (duration < this.minDurationMs) {
172
+ this.minDurationMs = duration;
173
+ }
174
+ if (duration > this.maxDurationMs) {
175
+ this.maxDurationMs = duration;
176
+ }
177
+ this.globalLatencySampler.add(duration);
178
+ if (record.isSlow) {
179
+ this.slowRequests += 1;
180
+ }
181
+ if (record.isUnmatchedRoute) {
182
+ this.unmatchedRouteRequests += 1;
183
+ }
184
+ if (record.aborted) {
185
+ this.abortedRequests += 1;
186
+ }
187
+ const statusKey = String(status);
188
+ this.statusCodeCounts.set(statusKey, (this.statusCodeCounts.get(statusKey) ?? 0) + 1);
189
+ if (status === 404) {
190
+ this.notFoundRequests += 1;
191
+ }
192
+ if (status >= 500) {
193
+ this.serverErrorRequests += 1;
194
+ this.statusDistribution["5xx"] += 1;
195
+ } else if (status >= 400) {
196
+ this.clientErrorRequests += 1;
197
+ this.statusDistribution["4xx"] += 1;
198
+ } else if (status >= 300) {
199
+ if (status === 304) {
200
+ this.notModifiedRequests += 1;
201
+ } else {
202
+ this.redirectRequests += 1;
203
+ }
204
+ this.statusDistribution["3xx"] += 1;
205
+ } else if (status >= 200) {
206
+ this.successfulRequests += 1;
207
+ this.statusDistribution["2xx"] += 1;
208
+ } else {
209
+ this.informationalRequests += 1;
210
+ this.statusDistribution["1xx"] += 1;
211
+ }
212
+ this.appendRecentRequest(record);
213
+ this.recordEndpointMetrics(record, duration);
214
+ }
215
+ /**
216
+ * Appends a cloned request record to the bounded circular buffer.
217
+ *
218
+ * @param {object} record - Completed request record.
219
+ */
220
+ appendRecentRequest(record) {
221
+ const clonedRecord = {
222
+ requestId: record.requestId,
223
+ timestamp: record.timestamp,
224
+ method: record.method,
225
+ route: record.route,
226
+ statusCode: record.statusCode,
227
+ durationMs: roundDuration(record.durationMs),
228
+ isSlow: Boolean(record.isSlow),
229
+ outcome: record.outcome,
230
+ isUnmatchedRoute: Boolean(record.isUnmatchedRoute),
231
+ aborted: Boolean(record.aborted)
232
+ };
233
+ if (record.errorName !== void 0) {
234
+ clonedRecord.errorName = record.errorName;
235
+ }
236
+ if (record.errorCode !== void 0) {
237
+ clonedRecord.errorCode = record.errorCode;
238
+ }
239
+ this.recentRequestsBuffer[this.recentWriteIndex] = clonedRecord;
240
+ this.recentWriteIndex = (this.recentWriteIndex + 1) % this.config.maxRecentRequests;
241
+ if (this.recentCount < this.config.maxRecentRequests) {
242
+ this.recentCount += 1;
243
+ }
244
+ }
245
+ /**
246
+ * Updates per-endpoint metrics while strictly enforcing `maxRouteEntries`.
247
+ *
248
+ * @param {object} record - Completed request record.
249
+ * @param {number} duration - Rounded duration in milliseconds.
250
+ */
251
+ recordEndpointMetrics(record, duration) {
252
+ const method = record.method.toUpperCase();
253
+ const route = record.route;
254
+ const endpointKey = `${method} ${route}`;
255
+ const overflowKey = `ALL ${this.config.fallbackRouteLabel}`;
256
+ let state = this.endpoints.get(endpointKey);
257
+ if (!state) {
258
+ if (this.endpoints.size < this.config.maxRouteEntries) {
259
+ state = this.createEmptyEndpointState(endpointKey, method, route, record.timestamp, false);
260
+ this.endpoints.set(endpointKey, state);
261
+ } else {
262
+ this.cardinalityOverflowCount += 1;
263
+ state = this.getOrCreateOverflowBucket(overflowKey, record.timestamp);
264
+ }
265
+ }
266
+ this.applyRequestToEndpointState(state, record, duration);
267
+ }
268
+ /**
269
+ * Obtains or creates the overflow bucket when `maxRouteEntries` is reached.
270
+ * If all `maxRouteEntries` slots are currently occupied by normal routes, the least-frequently
271
+ * hit normal route is merged into the new overflow bucket so total entries never exceed `maxRouteEntries`.
272
+ *
273
+ * @param {string} overflowKey - Canonical key for the overflow bucket.
274
+ * @param {string} timestamp - ISO timestamp.
275
+ * @returns {object} Mutable overflow endpoint state.
276
+ */
277
+ getOrCreateOverflowBucket(overflowKey, timestamp) {
278
+ const existingOverflow = this.endpoints.get(overflowKey);
279
+ if (existingOverflow) {
280
+ return existingOverflow;
281
+ }
282
+ const overflowState = this.createEmptyEndpointState(
283
+ overflowKey,
284
+ "ALL",
285
+ this.config.fallbackRouteLabel,
286
+ timestamp,
287
+ true
288
+ );
289
+ if (this.endpoints.size >= this.config.maxRouteEntries) {
290
+ let victimKey;
291
+ let victimState;
292
+ for (const [key, candidate] of this.endpoints.entries()) {
293
+ if (candidate.isOverflowBucket) {
294
+ continue;
295
+ }
296
+ if (!victimState || candidate.requestCount < victimState.requestCount) {
297
+ victimKey = key;
298
+ victimState = candidate;
299
+ }
300
+ }
301
+ if (victimKey && victimState) {
302
+ this.endpoints.delete(victimKey);
303
+ this.mergeEndpointState(overflowState, victimState);
304
+ }
305
+ }
306
+ this.endpoints.set(overflowKey, overflowState);
307
+ return overflowState;
308
+ }
309
+ createEmptyEndpointState(key, method, route, timestamp, isOverflowBucket) {
310
+ return {
311
+ key,
312
+ method,
313
+ route,
314
+ requestCount: 0,
315
+ informationalCount: 0,
316
+ successCount: 0,
317
+ redirectCount: 0,
318
+ notModifiedCount: 0,
319
+ errorCount: 0,
320
+ clientErrorCount: 0,
321
+ serverErrorCount: 0,
322
+ slowRequestCount: 0,
323
+ totalDurationMs: 0,
324
+ minDurationMs: Number.POSITIVE_INFINITY,
325
+ maxDurationMs: 0,
326
+ sampler: new RollingWindowSampler(this.config.windowSampleSize),
327
+ lastSeenAt: timestamp,
328
+ isOverflowBucket
329
+ };
330
+ }
331
+ mergeEndpointState(target, source) {
332
+ target.requestCount += source.requestCount;
333
+ target.informationalCount += source.informationalCount;
334
+ target.successCount += source.successCount;
335
+ target.redirectCount += source.redirectCount;
336
+ target.notModifiedCount += source.notModifiedCount;
337
+ target.errorCount += source.errorCount;
338
+ target.clientErrorCount += source.clientErrorCount;
339
+ target.serverErrorCount += source.serverErrorCount;
340
+ target.slowRequestCount += source.slowRequestCount;
341
+ target.totalDurationMs += source.totalDurationMs;
342
+ if (source.minDurationMs < target.minDurationMs) {
343
+ target.minDurationMs = source.minDurationMs;
344
+ }
345
+ if (source.maxDurationMs > target.maxDurationMs) {
346
+ target.maxDurationMs = source.maxDurationMs;
347
+ }
348
+ for (const sample of source.sampler.getSamples()) {
349
+ target.sampler.add(sample);
350
+ }
351
+ if (source.lastSeenAt > target.lastSeenAt) {
352
+ target.lastSeenAt = source.lastSeenAt;
353
+ }
354
+ }
355
+ applyRequestToEndpointState(state, record, duration) {
356
+ state.requestCount += 1;
357
+ state.totalDurationMs += duration;
358
+ if (duration < state.minDurationMs) {
359
+ state.minDurationMs = duration;
360
+ }
361
+ if (duration > state.maxDurationMs) {
362
+ state.maxDurationMs = duration;
363
+ }
364
+ state.sampler.add(duration);
365
+ state.lastSeenAt = record.timestamp;
366
+ if (record.isSlow) {
367
+ state.slowRequestCount += 1;
368
+ }
369
+ if (record.statusCode >= 500) {
370
+ state.serverErrorCount += 1;
371
+ state.errorCount += 1;
372
+ } else if (record.statusCode >= 400) {
373
+ state.clientErrorCount += 1;
374
+ state.errorCount += 1;
375
+ } else if (record.statusCode >= 300) {
376
+ if (record.statusCode === 304) {
377
+ state.notModifiedCount += 1;
378
+ } else {
379
+ state.redirectCount += 1;
380
+ }
381
+ } else if (record.statusCode >= 200) {
382
+ state.successCount += 1;
383
+ } else {
384
+ state.informationalCount += 1;
385
+ }
386
+ }
387
+ /**
388
+ * Returns a detached array of per-endpoint analytics sorted by request volume.
389
+ *
390
+ * @returns {object[]} Detached list of endpoint metric objects.
391
+ */
392
+ getEndpointMetrics() {
393
+ const endpointsList = [];
394
+ for (const state of this.endpoints.values()) {
395
+ const epAvg = state.requestCount > 0 ? roundDuration(state.totalDurationMs / state.requestCount) : 0;
396
+ const epMin = state.requestCount > 0 && Number.isFinite(state.minDurationMs) ? state.minDurationMs : 0;
397
+ const epMax = state.requestCount > 0 ? state.maxDurationMs : 0;
398
+ endpointsList.push({
399
+ key: state.key,
400
+ method: state.method,
401
+ route: state.route,
402
+ requestCount: state.requestCount,
403
+ informationalCount: state.informationalCount,
404
+ successCount: state.successCount,
405
+ redirectCount: state.redirectCount,
406
+ notModifiedCount: state.notModifiedCount,
407
+ errorCount: state.errorCount,
408
+ clientErrorCount: state.clientErrorCount,
409
+ serverErrorCount: state.serverErrorCount,
410
+ slowRequestCount: state.slowRequestCount,
411
+ avgDurationMs: epAvg,
412
+ minDurationMs: epMin,
413
+ maxDurationMs: epMax,
414
+ p95DurationMs: state.sampler.getPercentile(95),
415
+ lastSeenAt: state.lastSeenAt,
416
+ isOverflowBucket: state.isOverflowBucket
417
+ });
418
+ }
419
+ endpointsList.sort((a, b) => {
420
+ if (a.isOverflowBucket !== b.isOverflowBucket) {
421
+ return a.isOverflowBucket ? 1 : -1;
422
+ }
423
+ return b.requestCount - a.requestCount || b.p95DurationMs - a.p95DurationMs;
424
+ });
425
+ return endpointsList;
426
+ }
427
+ /**
428
+ * Produces a detached, deeply cloned snapshot of all collected metrics.
429
+ *
430
+ * @returns {object} Detached metrics snapshot.
431
+ */
432
+ getMetrics() {
433
+ const now = /* @__PURE__ */ new Date();
434
+ const uptimeSeconds = Math.max(
435
+ 0,
436
+ roundDuration((now.getTime() - this.startedAt.getTime()) / 1e3)
437
+ );
438
+ const hasRequests = this.totalRequests > 0;
439
+ const totalErrors = this.clientErrorRequests + this.serverErrorRequests;
440
+ const errorRate = hasRequests ? roundDuration(totalErrors / this.totalRequests * 100) : 0;
441
+ const slowRequestRate = hasRequests ? roundDuration(this.slowRequests / this.totalRequests * 100) : 0;
442
+ const avgMs = hasRequests ? roundDuration(this.totalDurationMs / this.totalRequests) : 0;
443
+ const minMs = hasRequests && Number.isFinite(this.minDurationMs) ? this.minDurationMs : 0;
444
+ const maxMs = hasRequests ? this.maxDurationMs : 0;
445
+ const p95Ms = hasRequests ? this.globalLatencySampler.getPercentile(95) : 0;
446
+ const statusDistributionCopy = {
447
+ "1xx": this.statusDistribution["1xx"],
448
+ "2xx": this.statusDistribution["2xx"],
449
+ "3xx": this.statusDistribution["3xx"],
450
+ "4xx": this.statusDistribution["4xx"],
451
+ "5xx": this.statusDistribution["5xx"]
452
+ };
453
+ const statusCodeCountsCopy = {};
454
+ for (const [code, count] of this.statusCodeCounts.entries()) {
455
+ statusCodeCountsCopy[code] = count;
456
+ }
457
+ return {
458
+ generatedAt: now.toISOString(),
459
+ startedAt: this.startedAt.toISOString(),
460
+ uptimeSeconds,
461
+ totalRequests: this.totalRequests,
462
+ informationalRequests: this.informationalRequests,
463
+ successfulRequests: this.successfulRequests,
464
+ redirectRequests: this.redirectRequests,
465
+ notModifiedRequests: this.notModifiedRequests,
466
+ clientErrorRequests: this.clientErrorRequests,
467
+ serverErrorRequests: this.serverErrorRequests,
468
+ notFoundRequests: this.notFoundRequests,
469
+ unmatchedRouteRequests: this.unmatchedRouteRequests,
470
+ slowRequests: this.slowRequests,
471
+ abortedRequests: this.abortedRequests,
472
+ errorRate,
473
+ slowRequestRate,
474
+ latency: {
475
+ avgMs,
476
+ minMs,
477
+ maxMs,
478
+ p95Ms,
479
+ sampleCount: this.globalLatencySampler.size()
480
+ },
481
+ statusDistribution: statusDistributionCopy,
482
+ statusCodeCounts: statusCodeCountsCopy,
483
+ endpoints: this.getEndpointMetrics(),
484
+ cardinalityOverflowCount: this.cardinalityOverflowCount,
485
+ config: {
486
+ slowRequestThresholdMs: this.config.slowRequestThresholdMs,
487
+ maxRecentRequests: this.config.maxRecentRequests,
488
+ maxRouteEntries: this.config.maxRouteEntries,
489
+ windowSampleSize: this.config.windowSampleSize,
490
+ requestIdHeader: this.config.requestIdHeader
491
+ }
492
+ };
493
+ }
494
+ /**
495
+ * Returns a detached array of cloned recent request records ordered from newest to oldest.
496
+ *
497
+ * @param {number} [limit] - Optional maximum number of records to return.
498
+ * @returns {object[]} Array of recent request records.
499
+ */
500
+ getRecentRequests(limit) {
501
+ if (limit !== void 0) {
502
+ if (typeof limit !== "number" || !Number.isFinite(limit)) {
503
+ throw new TypeError(`Invalid "limit": expected a finite number, received ${typeof limit}.`);
504
+ }
505
+ if (limit <= 0) {
506
+ return [];
507
+ }
508
+ }
509
+ const maxToReturn = limit !== void 0 ? Math.min(Math.floor(limit), this.recentCount) : this.recentCount;
510
+ const results = [];
511
+ for (let i = 0; i < maxToReturn; i += 1) {
512
+ const bufferIndex = (this.recentWriteIndex - 1 - i + this.config.maxRecentRequests) % this.config.maxRecentRequests;
513
+ const item = this.recentRequestsBuffer[bufferIndex];
514
+ if (item) {
515
+ const copy = {
516
+ requestId: item.requestId,
517
+ timestamp: item.timestamp,
518
+ method: item.method,
519
+ route: item.route,
520
+ statusCode: item.statusCode,
521
+ durationMs: item.durationMs,
522
+ isSlow: item.isSlow,
523
+ outcome: item.outcome,
524
+ isUnmatchedRoute: item.isUnmatchedRoute,
525
+ aborted: item.aborted
526
+ };
527
+ if (item.errorName !== void 0) {
528
+ copy.errorName = item.errorName;
529
+ }
530
+ if (item.errorCode !== void 0) {
531
+ copy.errorCode = item.errorCode;
532
+ }
533
+ results.push(copy);
534
+ }
535
+ }
536
+ return results;
537
+ }
538
+ /**
539
+ * Resets all in-memory metrics, latency buffers, endpoint records, and recent request history.
540
+ */
541
+ reset() {
542
+ this.startedAt = /* @__PURE__ */ new Date();
543
+ this.totalRequests = 0;
544
+ this.informationalRequests = 0;
545
+ this.successfulRequests = 0;
546
+ this.redirectRequests = 0;
547
+ this.notModifiedRequests = 0;
548
+ this.clientErrorRequests = 0;
549
+ this.serverErrorRequests = 0;
550
+ this.notFoundRequests = 0;
551
+ this.unmatchedRouteRequests = 0;
552
+ this.slowRequests = 0;
553
+ this.abortedRequests = 0;
554
+ this.cardinalityOverflowCount = 0;
555
+ this.totalDurationMs = 0;
556
+ this.minDurationMs = Number.POSITIVE_INFINITY;
557
+ this.maxDurationMs = 0;
558
+ this.globalLatencySampler.reset();
559
+ this.statusDistribution = {
560
+ "1xx": 0,
561
+ "2xx": 0,
562
+ "3xx": 0,
563
+ "4xx": 0,
564
+ "5xx": 0
565
+ };
566
+ this.statusCodeCounts.clear();
567
+ this.endpoints.clear();
568
+ this.recentRequestsBuffer = new Array(this.config.maxRecentRequests);
569
+ this.recentWriteIndex = 0;
570
+ this.recentCount = 0;
571
+ }
572
+ };
573
+
574
+ // src/core/route-normalizer.js
575
+ var UUID_SEGMENT_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
576
+ var OBJECT_ID_SEGMENT_REGEX = /^[0-9a-f]{24}$/i;
577
+ var NUMERIC_SEGMENT_REGEX = /^\d+$/;
578
+ var LONG_TOKEN_SEGMENT_REGEX = /^(?=.*\d)[A-Za-z0-9_-]{12,}$/;
579
+ var HEX_HASH_SEGMENT_REGEX = /^[0-9a-f]{16,}$/i;
580
+ function cleanPathString(rawUrl) {
581
+ if (!rawUrl || typeof rawUrl !== "string") {
582
+ return "/";
583
+ }
584
+ const withoutQuery = rawUrl.split("?")[0]?.split("#")[0]?.trim() ?? "/";
585
+ if (withoutQuery.length === 0) {
586
+ return "/";
587
+ }
588
+ const withLeadingSlash = withoutQuery.startsWith("/") ? withoutQuery : `/${withoutQuery}`;
589
+ const collapsedSlashes = withLeadingSlash.replace(/\/+/g, "/");
590
+ if (collapsedSlashes.length > 1 && collapsedSlashes.endsWith("/")) {
591
+ return collapsedSlashes.slice(0, -1);
592
+ }
593
+ return collapsedSlashes;
594
+ }
595
+ function normalizeDynamicPathSegments(rawUrl) {
596
+ const cleaned = cleanPathString(rawUrl);
597
+ if (cleaned === "/") {
598
+ return "/";
599
+ }
600
+ const segments = cleaned.split("/").filter((seg) => seg.length > 0);
601
+ const normalizedSegments = segments.map((segment) => {
602
+ if (segment.startsWith(":")) {
603
+ return segment;
604
+ }
605
+ if (NUMERIC_SEGMENT_REGEX.test(segment) || UUID_SEGMENT_REGEX.test(segment) || OBJECT_ID_SEGMENT_REGEX.test(segment) || HEX_HASH_SEGMENT_REGEX.test(segment) || LONG_TOKEN_SEGMENT_REGEX.test(segment)) {
606
+ return ":id";
607
+ }
608
+ return segment;
609
+ });
610
+ return `/${normalizedSegments.join("/")}`;
611
+ }
612
+ function resolveNormalizedRoute(req, statusCode, unmatchedRouteLabel = "/__unmatched__") {
613
+ const matchedRoute = req && req.route;
614
+ if (matchedRoute && matchedRoute.path !== void 0) {
615
+ const baseUrl = typeof req.baseUrl === "string" ? req.baseUrl : "";
616
+ const routePath = typeof matchedRoute.path === "string" ? matchedRoute.path : Array.isArray(matchedRoute.path) && typeof matchedRoute.path[0] === "string" ? matchedRoute.path[0] : String(matchedRoute.path);
617
+ const combined = cleanPathString(`${baseUrl}/${routePath}`);
618
+ return {
619
+ route: combined,
620
+ isUnmatchedRoute: false
621
+ };
622
+ }
623
+ if (statusCode === 404) {
624
+ return {
625
+ route: cleanPathString(unmatchedRouteLabel),
626
+ isUnmatchedRoute: true
627
+ };
628
+ }
629
+ const rawCandidate = req && typeof req.originalUrl === "string" && req.originalUrl || req && typeof req.url === "string" && req.url || req && typeof req.path === "string" && req.path || "/";
630
+ return {
631
+ route: normalizeDynamicPathSegments(rawCandidate),
632
+ isUnmatchedRoute: false
633
+ };
634
+ }
635
+
636
+ // src/core/request-tracker.js
637
+ import { performance } from "node:perf_hooks";
638
+ var activeRequestContexts = /* @__PURE__ */ new WeakMap();
639
+ function startRequestTracking(req, requestId) {
640
+ const context = {
641
+ requestId,
642
+ startTimeMs: performance.now(),
643
+ errorName: void 0,
644
+ errorCode: void 0
645
+ };
646
+ if (req && typeof req === "object") {
647
+ activeRequestContexts.set(req, context);
648
+ }
649
+ return context;
650
+ }
651
+ function getRequestTrackingContext(req) {
652
+ if (!req || typeof req !== "object") {
653
+ return void 0;
654
+ }
655
+ return activeRequestContexts.get(req);
656
+ }
657
+ function calculateElapsedDurationMs(startTimeMs, endTimeMs = performance.now()) {
658
+ const diffMs = endTimeMs - startTimeMs;
659
+ if (!Number.isFinite(diffMs) || diffMs <= 0) {
660
+ return 0;
661
+ }
662
+ return roundDuration(diffMs);
663
+ }
664
+ function classifyHttpStatus(statusCode) {
665
+ if (statusCode >= 500) {
666
+ return "server_error";
667
+ }
668
+ if (statusCode >= 400) {
669
+ return "client_error";
670
+ }
671
+ if (statusCode === 304) {
672
+ return "not_modified";
673
+ }
674
+ if (statusCode >= 300) {
675
+ return "redirect";
676
+ }
677
+ if (statusCode >= 200) {
678
+ return "success";
679
+ }
680
+ return "informational";
681
+ }
682
+
683
+ // src/utils/request-id.js
684
+ import { randomUUID } from "node:crypto";
685
+ var SAFE_REQUEST_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
686
+ function generateRequestId() {
687
+ return randomUUID();
688
+ }
689
+ function isValidIncomingRequestId(candidate) {
690
+ return typeof candidate === "string" && SAFE_REQUEST_ID_PATTERN.test(candidate);
691
+ }
692
+ function resolveRequestId(req, headerName, trustIncoming = false) {
693
+ if (trustIncoming && req && req.headers) {
694
+ const rawHeader = req.headers[String(headerName).toLowerCase()];
695
+ const candidate = Array.isArray(rawHeader) ? rawHeader[0] : rawHeader;
696
+ if (isValidIncomingRequestId(candidate)) {
697
+ return candidate;
698
+ }
699
+ }
700
+ return generateRequestId();
701
+ }
702
+
703
+ // src/middleware/create-middleware.js
704
+ function shouldIgnoreRequest(req, ignorePaths) {
705
+ if (typeof ignorePaths === "function") {
706
+ return Boolean(ignorePaths(req));
707
+ }
708
+ if (!Array.isArray(ignorePaths) || ignorePaths.length === 0) {
709
+ return false;
710
+ }
711
+ const rawPath = req && typeof req.originalUrl === "string" && req.originalUrl || req && typeof req.url === "string" && req.url || req && typeof req.path === "string" && req.path || "/";
712
+ const cleanedPath = cleanPathString(rawPath);
713
+ for (const pattern of ignorePaths) {
714
+ if (typeof pattern === "string") {
715
+ if (cleanPathString(pattern) === cleanedPath) {
716
+ return true;
717
+ }
718
+ } else if (pattern instanceof RegExp) {
719
+ if (pattern.test(cleanedPath)) {
720
+ return true;
721
+ }
722
+ }
723
+ }
724
+ return false;
725
+ }
726
+ function createSentinelMiddleware({ config, collector, logger }) {
727
+ return function apiSentinelMiddleware(req, res, next) {
728
+ if (shouldIgnoreRequest(req, config.ignorePaths)) {
729
+ next();
730
+ return;
731
+ }
732
+ const requestId = resolveRequestId(req, config.requestIdHeader, config.trustIncomingRequestId);
733
+ const trackingContext = startRequestTracking(req, requestId);
734
+ if (res && typeof res.setHeader === "function" && !res.headersSent) {
735
+ res.setHeader(config.requestIdHeader, requestId);
736
+ }
737
+ if (res && typeof res.locals === "object" && res.locals !== null) {
738
+ res.locals.requestId = requestId;
739
+ }
740
+ let finalized = false;
741
+ const finalizeRequest = (aborted) => {
742
+ if (finalized) {
743
+ return;
744
+ }
745
+ finalized = true;
746
+ if (res && typeof res.removeListener === "function") {
747
+ res.removeListener("finish", onFinish);
748
+ res.removeListener("close", onClose);
749
+ }
750
+ const durationMs = calculateElapsedDurationMs(trackingContext.startTimeMs);
751
+ const rawStatus = res && typeof res.statusCode === "number" && Number.isFinite(res.statusCode) ? res.statusCode : 200;
752
+ const statusCode = aborted && !res?.writableEnded && rawStatus === 200 ? 499 : rawStatus;
753
+ const { route, isUnmatchedRoute } = resolveNormalizedRoute(
754
+ req,
755
+ statusCode,
756
+ config.unmatchedRouteLabel
757
+ );
758
+ const method = req && typeof req.method === "string" && req.method.trim().length > 0 ? req.method.toUpperCase() : "GET";
759
+ const isSlow = durationMs > config.slowRequestThresholdMs;
760
+ const outcome = classifyHttpStatus(statusCode);
761
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
762
+ const record = {
763
+ requestId,
764
+ timestamp,
765
+ method,
766
+ route,
767
+ statusCode,
768
+ durationMs,
769
+ isSlow,
770
+ outcome,
771
+ isUnmatchedRoute,
772
+ aborted
773
+ };
774
+ if (trackingContext.errorName !== void 0) {
775
+ record.errorName = trackingContext.errorName;
776
+ }
777
+ if (trackingContext.errorCode !== void 0) {
778
+ record.errorCode = trackingContext.errorCode;
779
+ }
780
+ collector.recordRequest(record);
781
+ logger.logCompletedRequest(record);
782
+ };
783
+ const onFinish = () => {
784
+ finalizeRequest(false);
785
+ };
786
+ const onClose = () => {
787
+ const wasAborted = !(res && (res.writableEnded || res.finished));
788
+ finalizeRequest(wasAborted);
789
+ };
790
+ if (res && typeof res.on === "function") {
791
+ res.on("finish", onFinish);
792
+ res.on("close", onClose);
793
+ }
794
+ next();
795
+ };
796
+ }
797
+
798
+ // src/utils/sanitizer.js
799
+ var SAFE_IDENTIFIER_REGEX = /^[A-Za-z0-9_.:-]+$/;
800
+ function sanitizeLogEvent(event) {
801
+ const clean = {
802
+ type: String(event.type),
803
+ requestId: String(event.requestId),
804
+ method: String(event.method).toUpperCase(),
805
+ route: String(event.route),
806
+ statusCode: Number(event.statusCode),
807
+ durationMs: Number(event.durationMs),
808
+ timestamp: String(event.timestamp)
809
+ };
810
+ if (event.outcome !== void 0) {
811
+ clean.outcome = String(event.outcome);
812
+ }
813
+ if (event.isSlow !== void 0) {
814
+ clean.isSlow = Boolean(event.isSlow);
815
+ }
816
+ if (event.isUnmatchedRoute !== void 0) {
817
+ clean.isUnmatchedRoute = Boolean(event.isUnmatchedRoute);
818
+ }
819
+ if (event.aborted !== void 0) {
820
+ clean.aborted = Boolean(event.aborted);
821
+ }
822
+ if (event.errorName !== void 0) {
823
+ clean.errorName = String(event.errorName).slice(0, 120);
824
+ }
825
+ if (event.errorCode !== void 0) {
826
+ clean.errorCode = String(event.errorCode).slice(0, 64);
827
+ }
828
+ return Object.freeze(clean);
829
+ }
830
+ function extractSafeErrorMetadata(err) {
831
+ if (err === null || err === void 0) {
832
+ return { errorName: "UnknownError" };
833
+ }
834
+ if (typeof err === "object") {
835
+ let rawName = "Error";
836
+ if (typeof err.name === "string" && err.name.trim().length > 0) {
837
+ rawName = err.name.trim();
838
+ } else if (err.constructor && typeof err.constructor.name === "string" && err.constructor.name.trim().length > 0) {
839
+ rawName = err.constructor.name.trim();
840
+ }
841
+ const sanitizedName = SAFE_IDENTIFIER_REGEX.test(rawName) ? rawName.slice(0, 80) : "ApplicationError";
842
+ let sanitizedCode;
843
+ if (typeof err.code === "string" && SAFE_IDENTIFIER_REGEX.test(err.code)) {
844
+ sanitizedCode = err.code.slice(0, 64);
845
+ } else if (typeof err.code === "number" && Number.isFinite(err.code)) {
846
+ sanitizedCode = String(err.code);
847
+ }
848
+ const result = { errorName: sanitizedName };
849
+ if (sanitizedCode !== void 0) {
850
+ result.errorCode = sanitizedCode;
851
+ }
852
+ return result;
853
+ }
854
+ return { errorName: "NonObjectThrown" };
855
+ }
856
+
857
+ // src/middleware/error-handler.js
858
+ function createSentinelErrorHandler({ config, logger }) {
859
+ return function apiSentinelErrorHandler(err, req, res, next) {
860
+ const safeMeta = extractSafeErrorMetadata(err);
861
+ const trackingContext = getRequestTrackingContext(req);
862
+ if (trackingContext) {
863
+ trackingContext.errorName = safeMeta.errorName;
864
+ if (safeMeta.errorCode !== void 0) {
865
+ trackingContext.errorCode = safeMeta.errorCode;
866
+ }
867
+ }
868
+ const requestId = trackingContext?.requestId ?? resolveRequestId(req, config.requestIdHeader, config.trustIncomingRequestId);
869
+ const durationMs = trackingContext ? calculateElapsedDurationMs(trackingContext.startTimeMs) : 0;
870
+ const currentStatus = res && typeof res.statusCode === "number" && res.statusCode >= 400 ? res.statusCode : 500;
871
+ const { route, isUnmatchedRoute } = resolveNormalizedRoute(
872
+ req,
873
+ currentStatus,
874
+ config.unmatchedRouteLabel
875
+ );
876
+ const method = req && typeof req.method === "string" && req.method.trim().length > 0 ? req.method.toUpperCase() : "GET";
877
+ if (config.logging.enabled && config.logging.logServerErrors) {
878
+ logger.emit({
879
+ type: "error-detected",
880
+ requestId,
881
+ method,
882
+ route,
883
+ statusCode: currentStatus,
884
+ durationMs,
885
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
886
+ outcome: currentStatus >= 500 ? "server_error" : "client_error",
887
+ isSlow: durationMs > config.slowRequestThresholdMs,
888
+ isUnmatchedRoute,
889
+ errorName: safeMeta.errorName,
890
+ ...safeMeta.errorCode !== void 0 ? { errorCode: safeMeta.errorCode } : {}
891
+ });
892
+ }
893
+ next(err);
894
+ };
895
+ }
896
+
897
+ // src/utils/logger.js
898
+ var StructuredLogger = class {
899
+ /**
900
+ * @param {object} loggingConfig - Resolved logging configuration.
901
+ */
902
+ constructor(loggingConfig) {
903
+ this.config = loggingConfig;
904
+ }
905
+ /**
906
+ * Emits a single structured log event if logging is enabled.
907
+ *
908
+ * @param {object} event - Event record to emit.
909
+ */
910
+ emit(event) {
911
+ if (!this.config || !this.config.enabled) {
912
+ return;
913
+ }
914
+ try {
915
+ const sanitized = sanitizeLogEvent(event);
916
+ if (typeof this.config.writer === "function") {
917
+ this.config.writer(sanitized);
918
+ return;
919
+ }
920
+ const serialized = JSON.stringify(sanitized);
921
+ if (sanitized.type === "server-error" || sanitized.type === "error-detected") {
922
+ console.error(serialized);
923
+ } else if (sanitized.type === "slow-request" || sanitized.type === "client-error") {
924
+ console.warn(serialized);
925
+ } else {
926
+ console.info(serialized);
927
+ }
928
+ } catch {
929
+ }
930
+ }
931
+ /**
932
+ * Evaluates a completed request and emits the appropriate structured event(s)
933
+ * according to the active logging configuration.
934
+ *
935
+ * @param {object} record - Completed request record.
936
+ */
937
+ logCompletedRequest(record) {
938
+ if (!this.config || !this.config.enabled) {
939
+ return;
940
+ }
941
+ const isServerError = record.statusCode >= 500;
942
+ const isClientError = record.statusCode >= 400 && record.statusCode < 500;
943
+ const isSlow = Boolean(record.isSlow);
944
+ if (isServerError && this.config.logServerErrors) {
945
+ this.emit({ ...record, type: "server-error" });
946
+ } else if (isClientError && this.config.logClientErrors) {
947
+ this.emit({ ...record, type: "client-error" });
948
+ }
949
+ if (isSlow && this.config.logSlowRequests) {
950
+ this.emit({ ...record, type: "slow-request" });
951
+ }
952
+ if (this.config.logAllRequests && !isSlow && !(isServerError && this.config.logServerErrors) && !(isClientError && this.config.logClientErrors)) {
953
+ this.emit({ ...record, type: "request-completed" });
954
+ }
955
+ }
956
+ };
957
+
958
+ // src/utils/validation.js
959
+ var HEADER_NAME_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
960
+ function validateNumberRange(value, fieldName, min, max) {
961
+ if (typeof value !== "number" || !Number.isFinite(value)) {
962
+ throw new TypeError(
963
+ `Invalid "${fieldName}": expected a finite number, received ${typeof value}.`
964
+ );
965
+ }
966
+ if (value < min || value > max) {
967
+ throw new RangeError(
968
+ `Invalid "${fieldName}": must be between ${min} and ${max}, received ${value}.`
969
+ );
970
+ }
971
+ return value;
972
+ }
973
+ function validateIntegerRange(value, fieldName, min, max) {
974
+ const num = validateNumberRange(value, fieldName, min, max);
975
+ if (!Number.isInteger(num)) {
976
+ throw new RangeError(`Invalid "${fieldName}": expected an integer, received ${value}.`);
977
+ }
978
+ return num;
979
+ }
980
+ function resolveLoggerConfig(logging) {
981
+ if (logging === void 0 || logging === true) {
982
+ return { ...DEFAULT_CONFIG.logging };
983
+ }
984
+ if (logging === false) {
985
+ return {
986
+ enabled: false,
987
+ logAllRequests: false,
988
+ logSlowRequests: false,
989
+ logServerErrors: false,
990
+ logClientErrors: false
991
+ };
992
+ }
993
+ if (typeof logging !== "object" || logging === null || Array.isArray(logging)) {
994
+ throw new TypeError('Invalid "logging" option: expected a boolean or configuration object.');
995
+ }
996
+ if (logging.writer !== void 0 && typeof logging.writer !== "function") {
997
+ throw new TypeError('Invalid "logging.writer": expected a callback function.');
998
+ }
999
+ const resolved = {
1000
+ enabled: logging.enabled ?? DEFAULT_CONFIG.logging.enabled,
1001
+ logAllRequests: logging.logAllRequests ?? DEFAULT_CONFIG.logging.logAllRequests,
1002
+ logSlowRequests: logging.logSlowRequests ?? DEFAULT_CONFIG.logging.logSlowRequests,
1003
+ logServerErrors: logging.logServerErrors ?? DEFAULT_CONFIG.logging.logServerErrors,
1004
+ logClientErrors: logging.logClientErrors ?? DEFAULT_CONFIG.logging.logClientErrors
1005
+ };
1006
+ if (typeof resolved.enabled !== "boolean") {
1007
+ throw new TypeError('Invalid "logging.enabled": expected a boolean.');
1008
+ }
1009
+ if (logging.writer) {
1010
+ resolved.writer = logging.writer;
1011
+ }
1012
+ return resolved;
1013
+ }
1014
+ function resolveAndValidateConfig(config = {}) {
1015
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
1016
+ throw new TypeError("Invalid configuration: expected a plain configuration object.");
1017
+ }
1018
+ const slowRequestThresholdMs = config.slowRequestThresholdMs !== void 0 ? validateNumberRange(
1019
+ config.slowRequestThresholdMs,
1020
+ "slowRequestThresholdMs",
1021
+ CONFIG_BOUNDS.slowRequestThresholdMs.min,
1022
+ CONFIG_BOUNDS.slowRequestThresholdMs.max
1023
+ ) : DEFAULT_CONFIG.slowRequestThresholdMs;
1024
+ const maxRecentRequests = config.maxRecentRequests !== void 0 ? validateIntegerRange(
1025
+ config.maxRecentRequests,
1026
+ "maxRecentRequests",
1027
+ CONFIG_BOUNDS.maxRecentRequests.min,
1028
+ CONFIG_BOUNDS.maxRecentRequests.max
1029
+ ) : DEFAULT_CONFIG.maxRecentRequests;
1030
+ const maxRouteEntries = config.maxRouteEntries !== void 0 ? validateIntegerRange(
1031
+ config.maxRouteEntries,
1032
+ "maxRouteEntries",
1033
+ CONFIG_BOUNDS.maxRouteEntries.min,
1034
+ CONFIG_BOUNDS.maxRouteEntries.max
1035
+ ) : DEFAULT_CONFIG.maxRouteEntries;
1036
+ const windowSampleSize = config.windowSampleSize !== void 0 ? validateIntegerRange(
1037
+ config.windowSampleSize,
1038
+ "windowSampleSize",
1039
+ CONFIG_BOUNDS.windowSampleSize.min,
1040
+ CONFIG_BOUNDS.windowSampleSize.max
1041
+ ) : DEFAULT_CONFIG.windowSampleSize;
1042
+ const requestIdHeader = config.requestIdHeader ?? DEFAULT_CONFIG.requestIdHeader;
1043
+ if (typeof requestIdHeader !== "string" || requestIdHeader.trim().length === 0 || !HEADER_NAME_REGEX.test(requestIdHeader)) {
1044
+ throw new TypeError(
1045
+ 'Invalid "requestIdHeader": must be a valid non-empty HTTP header token string.'
1046
+ );
1047
+ }
1048
+ const trustIncomingRequestId = config.trustIncomingRequestId ?? DEFAULT_CONFIG.trustIncomingRequestId;
1049
+ if (typeof trustIncomingRequestId !== "boolean") {
1050
+ throw new TypeError('Invalid "trustIncomingRequestId": expected a boolean.');
1051
+ }
1052
+ const ignorePaths = config.ignorePaths ?? [];
1053
+ if (typeof ignorePaths !== "function" && !Array.isArray(ignorePaths)) {
1054
+ throw new TypeError(
1055
+ 'Invalid "ignorePaths": expected an array of strings/RegExps or a predicate function.'
1056
+ );
1057
+ }
1058
+ if (Array.isArray(ignorePaths)) {
1059
+ for (const item of ignorePaths) {
1060
+ if (typeof item !== "string" && !(item instanceof RegExp)) {
1061
+ throw new TypeError(
1062
+ 'Invalid "ignorePaths" element: every item must be a string or RegExp.'
1063
+ );
1064
+ }
1065
+ }
1066
+ }
1067
+ const fallbackRouteLabel = config.fallbackRouteLabel ?? DEFAULT_CONFIG.fallbackRouteLabel;
1068
+ if (typeof fallbackRouteLabel !== "string" || !fallbackRouteLabel.startsWith("/")) {
1069
+ throw new TypeError('Invalid "fallbackRouteLabel": must be a string starting with "/".');
1070
+ }
1071
+ const unmatchedRouteLabel = config.unmatchedRouteLabel ?? DEFAULT_CONFIG.unmatchedRouteLabel;
1072
+ if (typeof unmatchedRouteLabel !== "string" || !unmatchedRouteLabel.startsWith("/")) {
1073
+ throw new TypeError('Invalid "unmatchedRouteLabel": must be a string starting with "/".');
1074
+ }
1075
+ return Object.freeze({
1076
+ slowRequestThresholdMs,
1077
+ maxRecentRequests,
1078
+ maxRouteEntries,
1079
+ windowSampleSize,
1080
+ requestIdHeader,
1081
+ trustIncomingRequestId,
1082
+ logging: Object.freeze(resolveLoggerConfig(config.logging)),
1083
+ ignorePaths,
1084
+ fallbackRouteLabel,
1085
+ unmatchedRouteLabel
1086
+ });
1087
+ }
1088
+
1089
+ // src/index.js
1090
+ function createApiSentinel(options = {}) {
1091
+ const config = resolveAndValidateConfig(options);
1092
+ const collector = new MetricsCollector(config);
1093
+ const logger = new StructuredLogger(config.logging);
1094
+ const middleware = createSentinelMiddleware({ config, collector, logger });
1095
+ const errorHandler = createSentinelErrorHandler({ config, logger });
1096
+ return Object.freeze({
1097
+ middleware,
1098
+ errorHandler,
1099
+ getMetrics: () => collector.getMetrics(),
1100
+ getRecentRequests: (limit) => collector.getRecentRequests(limit),
1101
+ getEndpointMetrics: () => collector.getEndpointMetrics(),
1102
+ resetMetrics: () => collector.reset(),
1103
+ getConfig: () => config
1104
+ });
1105
+ }
1106
+ var index_default = createApiSentinel;
1107
+ export {
1108
+ DEFAULT_CONFIG,
1109
+ RollingWindowSampler,
1110
+ calculatePercentile,
1111
+ cleanPathString,
1112
+ createApiSentinel,
1113
+ index_default as default,
1114
+ extractSafeErrorMetadata,
1115
+ generateRequestId,
1116
+ isValidIncomingRequestId,
1117
+ normalizeDynamicPathSegments,
1118
+ resolveAndValidateConfig,
1119
+ resolveNormalizedRoute,
1120
+ resolveRequestId,
1121
+ roundDuration,
1122
+ sanitizeLogEvent
1123
+ };
1124
+ //# sourceMappingURL=index.js.map