@samuelaj1/eazisend-service-kit 1.0.7 → 1.0.8

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.
@@ -0,0 +1,97 @@
1
+ // src/middlewares/monitoring.middleware.ts
2
+ import { collectDefaultMetrics, Counter, Gauge, Histogram, Registry } from "prom-client";
3
+ var applications = /* @__PURE__ */ new WeakMap();
4
+ var methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT", "TRACE"]);
5
+ function routeLabel(request) {
6
+ const path = request.route?.path;
7
+ if (typeof path === "string") return path;
8
+ if (Array.isArray(path) && path.every((value) => typeof value === "string")) {
9
+ return path.join("|");
10
+ }
11
+ return path instanceof RegExp ? "__regexp__" : "__unmatched__";
12
+ }
13
+ function setupMetrics(app, options) {
14
+ if (typeof options?.serviceName !== "string" || !options.serviceName.trim()) {
15
+ throw new Error("Metrics serviceName must be a non-empty string");
16
+ }
17
+ const existing = applications.get(app);
18
+ if (existing) {
19
+ if (existing.serviceName !== options.serviceName) {
20
+ throw new Error("Metrics already initialized with a different serviceName");
21
+ }
22
+ return existing.registry;
23
+ }
24
+ const registry = new Registry();
25
+ registry.setDefaultLabels({ service: options.serviceName });
26
+ collectDefaultMetrics({ register: registry });
27
+ const labelNames = ["method", "route", "status_code"];
28
+ const requests = new Counter({
29
+ name: "http_requests_total",
30
+ help: "Completed HTTP requests",
31
+ labelNames,
32
+ registers: [registry]
33
+ });
34
+ const duration = new Histogram({
35
+ name: "http_request_duration_seconds",
36
+ help: "HTTP request duration in seconds",
37
+ labelNames,
38
+ registers: [registry],
39
+ buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
40
+ });
41
+ const errors = new Counter({
42
+ name: "http_request_errors_total",
43
+ help: "Completed HTTP requests with 4xx or 5xx status",
44
+ labelNames,
45
+ registers: [registry]
46
+ });
47
+ const active = new Gauge({
48
+ name: "http_active_requests",
49
+ help: "HTTP requests currently in progress",
50
+ registers: [registry]
51
+ });
52
+ active.set(0);
53
+ const middleware = (request, response, next) => {
54
+ if (/^\/metrics\/?$/i.test(request.path)) return next();
55
+ const started = process.hrtime.bigint();
56
+ active.inc();
57
+ let completed = false;
58
+ const complete = () => {
59
+ if (completed) return;
60
+ completed = true;
61
+ response.removeListener("finish", complete);
62
+ response.removeListener("close", complete);
63
+ active.dec();
64
+ const labels = {
65
+ method: methods.has(request.method) ? request.method : "OTHER",
66
+ route: routeLabel(request),
67
+ // A disconnected response has no completed HTTP status.
68
+ status_code: response.writableFinished ? String(response.statusCode) : "aborted"
69
+ };
70
+ requests.inc(labels);
71
+ duration.observe(labels, Number(process.hrtime.bigint() - started) / 1e9);
72
+ if (response.writableFinished && response.statusCode >= 400 && response.statusCode < 600) {
73
+ errors.inc(labels);
74
+ }
75
+ };
76
+ response.once("finish", complete);
77
+ response.once("close", complete);
78
+ next();
79
+ };
80
+ app.use(middleware);
81
+ app.get("/metrics", async (_request, response, next) => {
82
+ try {
83
+ const metrics = await registry.metrics();
84
+ response.setHeader("Content-Type", registry.contentType);
85
+ response.setHeader("Cache-Control", "no-store");
86
+ response.end(metrics);
87
+ } catch (error) {
88
+ next(error);
89
+ }
90
+ });
91
+ applications.set(app, { serviceName: options.serviceName, registry });
92
+ return registry;
93
+ }
94
+
95
+ export {
96
+ setupMetrics
97
+ };
package/dist/index.cjs CHANGED
@@ -38,6 +38,7 @@ __export(index_exports, {
38
38
  registerSecurityMiddleware: () => registerSecurityMiddleware,
39
39
  registerStandardMiddleware: () => registerStandardMiddleware,
40
40
  runServer: () => runServer,
41
+ setupMetrics: () => setupMetrics,
41
42
  verifyGatewayRequest: () => verifyGatewayRequest
42
43
  });
43
44
  module.exports = __toCommonJS(index_exports);
@@ -428,6 +429,100 @@ function registerErrorMiddleware(app) {
428
429
  res.status(import_http_status_codes.StatusCodes.INTERNAL_SERVER_ERROR).json({ error: err.message });
429
430
  };
430
431
  }
432
+
433
+ // src/middlewares/monitoring.middleware.ts
434
+ var import_prom_client = require("prom-client");
435
+ var applications = /* @__PURE__ */ new WeakMap();
436
+ var methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT", "TRACE"]);
437
+ function routeLabel(request) {
438
+ const path = request.route?.path;
439
+ if (typeof path === "string") return path;
440
+ if (Array.isArray(path) && path.every((value) => typeof value === "string")) {
441
+ return path.join("|");
442
+ }
443
+ return path instanceof RegExp ? "__regexp__" : "__unmatched__";
444
+ }
445
+ function setupMetrics(app, options) {
446
+ if (typeof options?.serviceName !== "string" || !options.serviceName.trim()) {
447
+ throw new Error("Metrics serviceName must be a non-empty string");
448
+ }
449
+ const existing = applications.get(app);
450
+ if (existing) {
451
+ if (existing.serviceName !== options.serviceName) {
452
+ throw new Error("Metrics already initialized with a different serviceName");
453
+ }
454
+ return existing.registry;
455
+ }
456
+ const registry = new import_prom_client.Registry();
457
+ registry.setDefaultLabels({ service: options.serviceName });
458
+ (0, import_prom_client.collectDefaultMetrics)({ register: registry });
459
+ const labelNames = ["method", "route", "status_code"];
460
+ const requests = new import_prom_client.Counter({
461
+ name: "http_requests_total",
462
+ help: "Completed HTTP requests",
463
+ labelNames,
464
+ registers: [registry]
465
+ });
466
+ const duration = new import_prom_client.Histogram({
467
+ name: "http_request_duration_seconds",
468
+ help: "HTTP request duration in seconds",
469
+ labelNames,
470
+ registers: [registry],
471
+ buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
472
+ });
473
+ const errors = new import_prom_client.Counter({
474
+ name: "http_request_errors_total",
475
+ help: "Completed HTTP requests with 4xx or 5xx status",
476
+ labelNames,
477
+ registers: [registry]
478
+ });
479
+ const active = new import_prom_client.Gauge({
480
+ name: "http_active_requests",
481
+ help: "HTTP requests currently in progress",
482
+ registers: [registry]
483
+ });
484
+ active.set(0);
485
+ const middleware = (request, response, next) => {
486
+ if (/^\/metrics\/?$/i.test(request.path)) return next();
487
+ const started = process.hrtime.bigint();
488
+ active.inc();
489
+ let completed = false;
490
+ const complete = () => {
491
+ if (completed) return;
492
+ completed = true;
493
+ response.removeListener("finish", complete);
494
+ response.removeListener("close", complete);
495
+ active.dec();
496
+ const labels = {
497
+ method: methods.has(request.method) ? request.method : "OTHER",
498
+ route: routeLabel(request),
499
+ // A disconnected response has no completed HTTP status.
500
+ status_code: response.writableFinished ? String(response.statusCode) : "aborted"
501
+ };
502
+ requests.inc(labels);
503
+ duration.observe(labels, Number(process.hrtime.bigint() - started) / 1e9);
504
+ if (response.writableFinished && response.statusCode >= 400 && response.statusCode < 600) {
505
+ errors.inc(labels);
506
+ }
507
+ };
508
+ response.once("finish", complete);
509
+ response.once("close", complete);
510
+ next();
511
+ };
512
+ app.use(middleware);
513
+ app.get("/metrics", async (_request, response, next) => {
514
+ try {
515
+ const metrics = await registry.metrics();
516
+ response.setHeader("Content-Type", registry.contentType);
517
+ response.setHeader("Cache-Control", "no-store");
518
+ response.end(metrics);
519
+ } catch (error) {
520
+ next(error);
521
+ }
522
+ });
523
+ applications.set(app, { serviceName: options.serviceName, registry });
524
+ return registry;
525
+ }
431
526
  // Annotate the CommonJS export names for ESM import in node:
432
527
  0 && (module.exports = {
433
528
  LogLevelTypes,
@@ -438,5 +533,6 @@ function registerErrorMiddleware(app) {
438
533
  registerSecurityMiddleware,
439
534
  registerStandardMiddleware,
440
535
  runServer,
536
+ setupMetrics,
441
537
  verifyGatewayRequest
442
538
  });
package/dist/index.d.cts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Express, Request, Response, NextFunction, Application } from 'express';
2
2
  import { LogEntry } from 'winston';
3
3
  import { Channel } from 'amqplib';
4
+ export { MetricsOptions, setupMetrics } from './middlewares/monitoring.middleware.cjs';
5
+ import 'prom-client';
4
6
 
5
7
  declare function registerStandardMiddleware(app: Express): void;
6
8
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Express, Request, Response, NextFunction, Application } from 'express';
2
2
  import { LogEntry } from 'winston';
3
3
  import { Channel } from 'amqplib';
4
+ export { MetricsOptions, setupMetrics } from './middlewares/monitoring.middleware.js';
5
+ import 'prom-client';
4
6
 
5
7
  declare function registerStandardMiddleware(app: Express): void;
6
8
 
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ setupMetrics
3
+ } from "./chunk-TS72ONWN.js";
4
+
1
5
  // src/middlewares/standard.middleware.ts
2
6
  import { json, urlencoded } from "express";
3
7
  import compression from "compression";
@@ -389,5 +393,6 @@ export {
389
393
  registerSecurityMiddleware,
390
394
  registerStandardMiddleware,
391
395
  runServer,
396
+ setupMetrics,
392
397
  verifyGatewayRequest
393
398
  };
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/middlewares/monitoring.middleware.ts
21
+ var monitoring_middleware_exports = {};
22
+ __export(monitoring_middleware_exports, {
23
+ setupMetrics: () => setupMetrics
24
+ });
25
+ module.exports = __toCommonJS(monitoring_middleware_exports);
26
+ var import_prom_client = require("prom-client");
27
+ var applications = /* @__PURE__ */ new WeakMap();
28
+ var methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT", "TRACE"]);
29
+ function routeLabel(request) {
30
+ const path = request.route?.path;
31
+ if (typeof path === "string") return path;
32
+ if (Array.isArray(path) && path.every((value) => typeof value === "string")) {
33
+ return path.join("|");
34
+ }
35
+ return path instanceof RegExp ? "__regexp__" : "__unmatched__";
36
+ }
37
+ function setupMetrics(app, options) {
38
+ if (typeof options?.serviceName !== "string" || !options.serviceName.trim()) {
39
+ throw new Error("Metrics serviceName must be a non-empty string");
40
+ }
41
+ const existing = applications.get(app);
42
+ if (existing) {
43
+ if (existing.serviceName !== options.serviceName) {
44
+ throw new Error("Metrics already initialized with a different serviceName");
45
+ }
46
+ return existing.registry;
47
+ }
48
+ const registry = new import_prom_client.Registry();
49
+ registry.setDefaultLabels({ service: options.serviceName });
50
+ (0, import_prom_client.collectDefaultMetrics)({ register: registry });
51
+ const labelNames = ["method", "route", "status_code"];
52
+ const requests = new import_prom_client.Counter({
53
+ name: "http_requests_total",
54
+ help: "Completed HTTP requests",
55
+ labelNames,
56
+ registers: [registry]
57
+ });
58
+ const duration = new import_prom_client.Histogram({
59
+ name: "http_request_duration_seconds",
60
+ help: "HTTP request duration in seconds",
61
+ labelNames,
62
+ registers: [registry],
63
+ buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
64
+ });
65
+ const errors = new import_prom_client.Counter({
66
+ name: "http_request_errors_total",
67
+ help: "Completed HTTP requests with 4xx or 5xx status",
68
+ labelNames,
69
+ registers: [registry]
70
+ });
71
+ const active = new import_prom_client.Gauge({
72
+ name: "http_active_requests",
73
+ help: "HTTP requests currently in progress",
74
+ registers: [registry]
75
+ });
76
+ active.set(0);
77
+ const middleware = (request, response, next) => {
78
+ if (/^\/metrics\/?$/i.test(request.path)) return next();
79
+ const started = process.hrtime.bigint();
80
+ active.inc();
81
+ let completed = false;
82
+ const complete = () => {
83
+ if (completed) return;
84
+ completed = true;
85
+ response.removeListener("finish", complete);
86
+ response.removeListener("close", complete);
87
+ active.dec();
88
+ const labels = {
89
+ method: methods.has(request.method) ? request.method : "OTHER",
90
+ route: routeLabel(request),
91
+ // A disconnected response has no completed HTTP status.
92
+ status_code: response.writableFinished ? String(response.statusCode) : "aborted"
93
+ };
94
+ requests.inc(labels);
95
+ duration.observe(labels, Number(process.hrtime.bigint() - started) / 1e9);
96
+ if (response.writableFinished && response.statusCode >= 400 && response.statusCode < 600) {
97
+ errors.inc(labels);
98
+ }
99
+ };
100
+ response.once("finish", complete);
101
+ response.once("close", complete);
102
+ next();
103
+ };
104
+ app.use(middleware);
105
+ app.get("/metrics", async (_request, response, next) => {
106
+ try {
107
+ const metrics = await registry.metrics();
108
+ response.setHeader("Content-Type", registry.contentType);
109
+ response.setHeader("Cache-Control", "no-store");
110
+ response.end(metrics);
111
+ } catch (error) {
112
+ next(error);
113
+ }
114
+ });
115
+ applications.set(app, { serviceName: options.serviceName, registry });
116
+ return registry;
117
+ }
118
+ // Annotate the CommonJS export names for ESM import in node:
119
+ 0 && (module.exports = {
120
+ setupMetrics
121
+ });
@@ -0,0 +1,15 @@
1
+ import { Express } from 'express';
2
+ import { Registry } from 'prom-client';
3
+
4
+ interface MetricsOptions {
5
+ serviceName: string;
6
+ }
7
+ /**
8
+ * Register before authentication and application routes so GET /metrics bypasses auth.
9
+ * Restrict /metrics to internal access at the Kubernetes networking/Ingress level.
10
+ * Returns an app-local registry for custom metrics (use registers: [registry]).
11
+ * Router labels use leaf templates, omitting potentially dynamic mount prefixes.
12
+ */
13
+ declare function setupMetrics(app: Express, options: MetricsOptions): Registry;
14
+
15
+ export { type MetricsOptions, setupMetrics };
@@ -0,0 +1,15 @@
1
+ import { Express } from 'express';
2
+ import { Registry } from 'prom-client';
3
+
4
+ interface MetricsOptions {
5
+ serviceName: string;
6
+ }
7
+ /**
8
+ * Register before authentication and application routes so GET /metrics bypasses auth.
9
+ * Restrict /metrics to internal access at the Kubernetes networking/Ingress level.
10
+ * Returns an app-local registry for custom metrics (use registers: [registry]).
11
+ * Router labels use leaf templates, omitting potentially dynamic mount prefixes.
12
+ */
13
+ declare function setupMetrics(app: Express, options: MetricsOptions): Registry;
14
+
15
+ export { type MetricsOptions, setupMetrics };
@@ -0,0 +1,6 @@
1
+ import {
2
+ setupMetrics
3
+ } from "../chunk-TS72ONWN.js";
4
+ export {
5
+ setupMetrics
6
+ };
package/package.json CHANGED
@@ -1,10 +1,20 @@
1
1
  {
2
2
  "name": "@samuelaj1/eazisend-service-kit",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "scripts": {
5
5
  "build": "tsup"
6
6
  },
7
7
  "exports": {
8
+ "./monitoring": {
9
+ "import": {
10
+ "types": "./dist/middlewares/monitoring.middleware.d.ts",
11
+ "default": "./dist/middlewares/monitoring.middleware.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/middlewares/monitoring.middleware.d.cts",
15
+ "default": "./dist/middlewares/monitoring.middleware.cjs"
16
+ }
17
+ },
8
18
  ".": {
9
19
  "import": {
10
20
  "types": "./dist/index.d.ts",
@@ -49,6 +59,7 @@
49
59
  "hpp": "^0.2.3",
50
60
  "http-status-codes": "^2.3.0",
51
61
  "jsonwebtoken": "^9.0.3",
62
+ "prom-client": "^15.1.3",
52
63
  "winston": "^3.19.0",
53
64
  "winston-elasticsearch": "^0.19.0"
54
65
  }