@visulima/health-check 1.0.6 → 1.0.9

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/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ ## @visulima/health-check [1.0.9](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.8...@visulima/health-check@1.0.9) (2023-07-28)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * Update eslint rules and dependencies ([01a4bef](https://github.com/visulima/visulima/commit/01a4beff467091ac2d2fc6f342d274d282391842))
7
+
8
+ ## @visulima/health-check [1.0.8](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.7...@visulima/health-check@1.0.8) (2023-07-26)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * Refactor code for improved readability and error handling ([2b280d8](https://github.com/visulima/visulima/commit/2b280d836593800f13066ee31828a7f20400eb58))
14
+ * Update eslint-config version to 10.0.6 across multiple packages ([391238a](https://github.com/visulima/visulima/commit/391238ab4d00335e4ad47d7b705960d0af9a5412))
15
+
16
+ ## @visulima/health-check [1.0.7](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.6...@visulima/health-check@1.0.7) (2023-06-08)
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * skipped all ping-check tests on ci ([34c2497](https://github.com/visulima/visulima/commit/34c2497dc0d607d051c8ba138ff9763edd56877d))
22
+
1
23
  ## @visulima/health-check [1.0.6](https://github.com/visulima/visulima/compare/@visulima/health-check@1.0.5...@visulima/health-check@1.0.6) (2023-06-08)
2
24
 
3
25
 
@@ -0,0 +1,70 @@
1
+ import { Options, IPFamily } from 'cacheable-lookup';
2
+ import { extendedPingOptions } from 'pingman';
3
+ import { IncomingMessage, ServerResponse } from 'node:http';
4
+
5
+ /**
6
+ * Shape of health report entry. Each checker must
7
+ * return an object with similar shape.
8
+ */
9
+ interface HealthReportEntry {
10
+ displayName: string;
11
+ health: {
12
+ healthy: boolean;
13
+ message?: string;
14
+ timestamp: string;
15
+ };
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ meta?: any;
18
+ }
19
+
20
+ type Checker = () => Promise<HealthReportEntry>;
21
+
22
+ /**
23
+ * The shape of entire report
24
+ */
25
+ type HealthReport = Record<string, HealthReportEntry>;
26
+
27
+ /**
28
+ * Shape of health check contract
29
+ */
30
+ interface HealthCheck {
31
+ addChecker: (service: string, checker: Checker) => void;
32
+ getReport: () => Promise<{ healthy: boolean; report: HealthReport }>;
33
+ isLive: () => Promise<boolean>;
34
+ servicesList: string[];
35
+ }
36
+
37
+ declare const dnsCheck: (host: string, expectedAddresses?: string[], options?: Options & {
38
+ family?: IPFamily | "all";
39
+ hints?: number;
40
+ }) => Checker;
41
+
42
+ declare const httpCheck: (host: RequestInfo | URL, options?: {
43
+ expected?: {
44
+ body?: string;
45
+ status?: number;
46
+ };
47
+ fetchOptions?: RequestInit;
48
+ }) => Checker;
49
+
50
+ declare const nodeEnvironmentCheck: (expectedEnvironment?: string) => Checker;
51
+
52
+ declare const pingCheck: (host: string, options?: extendedPingOptions) => Checker;
53
+
54
+ declare const _default$1: (healthCheck: HealthCheck, sendHeader?: boolean | undefined) => <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(_: Request_1, response: Response_1) => Promise<void>;
55
+
56
+ declare const _default: <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(healthCheck: HealthCheck) => (_request: Request_1, response: Response_1) => Promise<void>;
57
+
58
+ declare class Healthcheck implements HealthCheck {
59
+ private healthCheckers;
60
+ private invokeChecker;
61
+ addChecker(service: string, checker: Checker): void;
62
+ getReport(): Promise<{
63
+ healthy: boolean;
64
+ report: HealthReport;
65
+ }>;
66
+ isLive(): Promise<boolean>;
67
+ get servicesList(): string[];
68
+ }
69
+
70
+ export { Checker, Healthcheck as HealthCheck, dnsCheck, _default$1 as healthCheckHandler, _default as healthReadyHandler, httpCheck, nodeEnvironmentCheck as nodeEnvCheck, pingCheck };
package/dist/index.d.ts CHANGED
@@ -1,54 +1,37 @@
1
- import { IncomingMessage, ServerResponse } from 'node:http';
2
1
  import { Options, IPFamily } from 'cacheable-lookup';
3
2
  import { extendedPingOptions } from 'pingman';
4
-
5
- type Checker = () => Promise<HealthReportEntry>;
3
+ import { IncomingMessage, ServerResponse } from 'node:http';
6
4
 
7
5
  /**
8
6
  * Shape of health report entry. Each checker must
9
7
  * return an object with similar shape.
10
8
  */
11
- type HealthReportEntry = {
9
+ interface HealthReportEntry {
12
10
  displayName: string;
13
11
  health: {
14
12
  healthy: boolean;
15
13
  message?: string;
16
14
  timestamp: string;
17
15
  };
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
17
  meta?: any;
19
- };
18
+ }
19
+
20
+ type Checker = () => Promise<HealthReportEntry>;
20
21
 
21
22
  /**
22
23
  * The shape of entire report
23
24
  */
24
- type HealthReport = {
25
- [service: string]: HealthReportEntry;
26
- };
25
+ type HealthReport = Record<string, HealthReportEntry>;
27
26
 
28
27
  /**
29
28
  * Shape of health check contract
30
29
  */
31
30
  interface HealthCheck {
32
- servicesList: string[];
33
31
  addChecker: (service: string, checker: Checker) => void;
34
- isLive: () => Promise<boolean>;
35
32
  getReport: () => Promise<{ healthy: boolean; report: HealthReport }>;
36
- }
37
-
38
- declare const _default$1: (healthCheck: HealthCheck, sendHeader?: boolean | undefined) => <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(_: Request_1, response: Response_1) => Promise<void>;
39
-
40
- declare const _default: <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(healthCheck: HealthCheck) => (_request: Request_1, response: Response_1) => Promise<void>;
41
-
42
- declare class Healthcheck implements HealthCheck {
43
- private healthCheckers;
44
- get servicesList(): string[];
45
- private invokeChecker;
46
- addChecker(service: string, checker: Checker): void;
47
- getReport(): Promise<{
48
- healthy: boolean;
49
- report: HealthReport;
50
- }>;
51
- isLive(): Promise<boolean>;
33
+ isLive: () => Promise<boolean>;
34
+ servicesList: string[];
52
35
  }
53
36
 
54
37
  declare const dnsCheck: (host: string, expectedAddresses?: string[], options?: Options & {
@@ -57,15 +40,31 @@ declare const dnsCheck: (host: string, expectedAddresses?: string[], options?: O
57
40
  }) => Checker;
58
41
 
59
42
  declare const httpCheck: (host: RequestInfo | URL, options?: {
60
- fetchOptions?: RequestInit;
61
43
  expected?: {
62
- status?: number;
63
44
  body?: string;
45
+ status?: number;
64
46
  };
47
+ fetchOptions?: RequestInit;
65
48
  }) => Checker;
66
49
 
67
50
  declare const nodeEnvironmentCheck: (expectedEnvironment?: string) => Checker;
68
51
 
69
52
  declare const pingCheck: (host: string, options?: extendedPingOptions) => Checker;
70
53
 
54
+ declare const _default$1: (healthCheck: HealthCheck, sendHeader?: boolean | undefined) => <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(_: Request_1, response: Response_1) => Promise<void>;
55
+
56
+ declare const _default: <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(healthCheck: HealthCheck) => (_request: Request_1, response: Response_1) => Promise<void>;
57
+
58
+ declare class Healthcheck implements HealthCheck {
59
+ private healthCheckers;
60
+ private invokeChecker;
61
+ addChecker(service: string, checker: Checker): void;
62
+ getReport(): Promise<{
63
+ healthy: boolean;
64
+ report: HealthReport;
65
+ }>;
66
+ isLive(): Promise<boolean>;
67
+ get servicesList(): string[];
68
+ }
69
+
71
70
  export { Checker, Healthcheck as HealthCheck, dnsCheck, _default$1 as healthCheckHandler, _default as healthReadyHandler, httpCheck, nodeEnvironmentCheck as nodeEnvCheck, pingCheck };
package/dist/index.js CHANGED
@@ -1,23 +1,23 @@
1
1
  'use strict';
2
2
 
3
- var httpStatusCodes = require('http-status-codes');
4
- var k = require('cacheable-lookup');
3
+ var f = require('cacheable-lookup');
5
4
  var assert = require('assert');
6
- var R = require('pingman');
5
+ var O = require('pingman');
6
+ var httpStatusCodes = require('http-status-codes');
7
7
 
8
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
9
 
10
- var k__default = /*#__PURE__*/_interopDefault(k);
11
- var R__default = /*#__PURE__*/_interopDefault(R);
10
+ var f__default = /*#__PURE__*/_interopDefault(f);
11
+ var O__default = /*#__PURE__*/_interopDefault(O);
12
12
 
13
- var f=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",timestamp:new Date().toISOString(),reports:o};r.statusCode=s?httpStatusCodes.StatusCodes.OK:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var u=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?httpStatusCodes.StatusCodes.NO_CONTENT:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){this.healthCheckers={};}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},g=c;var i="DNS check for",C=(t,e,a)=>async()=>{let{hints:r,family:s="all",...o}=a??{},l=new k__default.default(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},S=C;var h="HTTP check for",$=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{assert.deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},O=$;var y="Node Environment Check",E=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:y,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:y,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},I=E;var p="Ping check for",w=(t,e)=>async()=>{try{let a=await R__default.default(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},x=w;
13
+ var i="DNS check for",u=(t,e,a)=>async()=>{let{family:r="all",hints:s,...o}=a??{},l=new f__default.default(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:n,host:t}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:n,host:t}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},g=u;var h="HTTP check for",C=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{assert.deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},S=C;var m="Node Environment Check",N=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:m,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:m,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},$=N;var p="Ping check for",R=(t,e)=>async()=>{try{let a=await O__default.default(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},w=R;var E=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:o,status:s?"ok":"error",timestamp:new Date().toISOString()};r.statusCode=s?httpStatusCodes.StatusCodes.OK:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var I=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?httpStatusCodes.StatusCodes.NO_CONTENT:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){this.healthCheckers={};}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(async r=>await this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}get servicesList(){return Object.keys(this.healthCheckers)}},x=c;
14
14
 
15
- exports.HealthCheck = g;
16
- exports.dnsCheck = S;
17
- exports.healthCheckHandler = f;
18
- exports.healthReadyHandler = u;
19
- exports.httpCheck = O;
20
- exports.nodeEnvCheck = I;
21
- exports.pingCheck = x;
15
+ exports.HealthCheck = x;
16
+ exports.dnsCheck = g;
17
+ exports.healthCheckHandler = E;
18
+ exports.healthReadyHandler = I;
19
+ exports.httpCheck = S;
20
+ exports.nodeEnvCheck = $;
21
+ exports.pingCheck = w;
22
22
  //# sourceMappingURL=out.js.map
23
23
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","readyhandler_default","_request","Healthcheck","service","reportSheet","checker","error","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","dns_check_default","deepStrictEqual","httpCheck","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default"],"mappings":"AAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAsC,CAC5M,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAe,UACpC,WAAY,QAAQ,IAAI,aAAkB,UAC1C,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAR,MAAmB,oBAM5B,IAAOS,EAA2EP,GAA6B,MAAOQ,EAAmBL,IAAsC,CAC3K,GAAM,CAAE,QAAAC,CAAQ,EAAI,MAAMJ,EAAY,UAAU,EAEhDG,EAAS,WAAaC,EAAUN,EAAY,WAAaA,EAAY,oBACrEK,EAAS,IAAI,CACjB,ECPA,IAAMM,EAAN,KAAkD,CAAlD,cAII,KAAQ,eAAiD,CAAC,E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ACH,YAAa,GAAGY,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,KAAgBE,oBAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMd,CACV,EAnBW,CACH,YAAa,GAAGY,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,mBAAmBA,KAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMd,CACV,CAYR,OAASU,EAAP,CACE,MAAO,CACH,YAAa,GAAGE,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAUJ,EAAgB,QAC1B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEOwB,EAAQD","sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"error\" | \"ok\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import type {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (\n host: RequestInfo | URL,\n options?: {\n fetchOptions?: RequestInit;\n expected?: { status?: number; body?: string };\n },\n): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"]}
1
+ {"version":3,"sources":["../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts","../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts"],"names":["CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","family","hints","config","cacheable","meta","error","dns_check_default","deepStrictEqual","httpCheck","response","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default","StatusCodes","healthcheck_default","healthCheck","sendHeader","_","healthy","report","payload","readyhandler_default","_request","Healthcheck","service","reportSheet","checker"],"mappings":"AACA,OAAOA,MAAqB,mBAI5B,IAAMC,EAAe,gBAKfC,EACF,CACIC,EACAC,EACAC,IAKJ,SAAY,CACR,GAAM,CAAE,OAAAC,EAAS,MAAO,MAAAC,EAAO,GAAGC,CAAO,EAAIH,GAAW,CAAC,EAEnDI,EAAY,IAAIT,EAAgBQ,CAAM,EAE5C,GAAI,CACA,IAAME,EAAO,MAAMD,EAAU,YAAYN,EAAK,QAAQ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\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck =\n (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n ): Checker =>\n async () => {\n const { family = \"all\", hints, ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n addresses: meta,\n host,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n addresses: meta,\n host,\n },\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n };\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck =\n (\n host: RequestInfo | URL,\n options?: {\n expected?: { body?: string; status?: number };\n fetchOptions?: RequestInit;\n },\n ): Checker =>\n async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host as string} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(\n `${DISPLAY_NAME} ${host as string} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`,\n );\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host as string}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host as string} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host as string}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n };\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck =\n (expectedEnvironment?: string): Checker =>\n async () => {\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n };\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck =\n (host: string, options?: extendedPingOptions): Checker =>\n async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n };\n\nexport default pingCheck;\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\nexport interface HealthCheckApiPayload {\n appName: string;\n appVersion: string;\n message: string;\n reports: HealthReport;\n status: \"error\" | \"ok\";\n timestamp: string;\n}\n\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n reports: report,\n status: healthy ? \"ok\" : \"error\",\n timestamp: new Date().toISOString(),\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n };\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) =>\n async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n };\n","import type { Checker, HealthReport, HealthReportEntry, HealthCheck as HealthcheckInterface } from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: Record<string, Checker> = {};\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n // eslint-disable-next-line security/detect-object-injection\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign,security/detect-object-injection\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n // eslint-disable-next-line security/detect-object-injection\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map(async (service) => await this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n // eslint-disable-next-line security/detect-object-injection\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n}\n\nexport default Healthcheck;\n"]}
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { StatusCodes } from 'http-status-codes';
2
- import k from 'cacheable-lookup';
1
+ import f from 'cacheable-lookup';
3
2
  import { deepStrictEqual } from 'assert';
4
- import R from 'pingman';
3
+ import O from 'pingman';
4
+ import { StatusCodes } from 'http-status-codes';
5
5
 
6
- var f=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={status:s?"ok":"error",message:s?"Health check successful":"Health check failed",appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",timestamp:new Date().toISOString(),reports:o};r.statusCode=s?StatusCodes.OK:StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var u=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?StatusCodes.NO_CONTENT:StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){this.healthCheckers={};}get servicesList(){return Object.keys(this.healthCheckers)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(r=>this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}},g=c;var i="DNS check for",C=(t,e,a)=>async()=>{let{hints:r,family:s="all",...o}=a??{},l=new k(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:r,...s==="all"?{all:!0}:{family:s}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{host:t,addresses:n}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},S=C;var h="HTTP check for",$=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},O=$;var y="Node Environment Check",E=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:y,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:y,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},I=E;var p="Ping check for",w=(t,e)=>async()=>{try{let a=await R(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},x=w;
6
+ var i="DNS check for",u=(t,e,a)=>async()=>{let{family:r="all",hints:s,...o}=a??{},l=new f(o);try{let n=await l.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(n.address)?{displayName:`${i} ${t}`,health:{healthy:!1,message:`${i} ${t} returned address ${n.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:n,host:t}}:{displayName:`${i} ${t}`,health:{healthy:!0,message:`${i} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:n,host:t}}}catch(n){return {displayName:`${i} ${t}`,health:{healthy:!1,message:n.message,timestamp:new Date().toISOString()},meta:{host:t}}}},g=u;var h="HTTP check for",C=(t,e)=>async()=>{try{let a=await fetch(t,e?.fetchOptions??{});if(e?.expected?.status!==void 0&&e.expected.status!==a.status)throw new Error(`${h} ${t} returned status ${a.status} instead of ${e.expected.status}`);if(e?.expected?.body!==void 0){let r=await a.text();try{deepStrictEqual(r,e.expected.body);}catch{throw new Error(`${h} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${h} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},S=C;var m="Node Environment Check",N=t=>async()=>{let e="production",a;return t!==void 0&&e!==t?a=`NODE_ENV environment variable is set to "${e}" instead of "${t}".`:e,a!==void 0?{displayName:m,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:m,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},$=N;var p="Ping check for",R=(t,e)=>async()=>{try{let a=await O(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${p} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},w=R;var E=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:o}=await t.getReport(),l={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:o,status:s?"ok":"error",timestamp:new Date().toISOString()};r.statusCode=s?StatusCodes.OK:StatusCodes.SERVICE_UNAVAILABLE,e&&r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(l,null,2));};var I=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?StatusCodes.NO_CONTENT:StatusCodes.SERVICE_UNAVAILABLE,a.end();};var c=class{constructor(){this.healthCheckers={};}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(o){s={displayName:e,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}addChecker(e,a){this.healthCheckers[e]=a;}async getReport(){let e={};return await Promise.all(Object.keys(this.healthCheckers).map(async r=>await this.invokeChecker(r,e))),{healthy:!Object.keys(e).find(r=>!e[r].health.healthy),report:e}}async isLive(){let{healthy:e}=await this.getReport();return e}get servicesList(){return Object.keys(this.healthCheckers)}},x=c;
7
7
 
8
- export { g as HealthCheck, S as dnsCheck, f as healthCheckHandler, u as healthReadyHandler, O as httpCheck, I as nodeEnvCheck, x as pingCheck };
8
+ export { x as HealthCheck, g as dnsCheck, E as healthCheckHandler, I as healthReadyHandler, S as httpCheck, $ as nodeEnvCheck, w as pingCheck };
9
9
  //# sourceMappingURL=out.js.map
10
10
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts","../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts"],"names":["StatusCodes","healthcheck_default","healthCheck","sendHeader","_","response","healthy","report","payload","readyhandler_default","_request","Healthcheck","service","reportSheet","checker","error","CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","hints","family","config","cacheable","meta","dns_check_default","deepStrictEqual","httpCheck","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default"],"mappings":"AAAA,OAAS,eAAAA,MAAmB,oBAM5B,IAAOC,EAAQ,CAACC,EAA0BC,EAAkC,KAAS,MAAyEC,EAAYC,IAAsC,CAC5M,GAAM,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAI,MAAML,EAAY,UAAU,EAElDM,EAAiC,CACnC,OAAQF,EAAU,KAAO,QACzB,QAASA,EAAU,0BAA4B,sBAC/C,QAAS,QAAQ,IAAI,UAAe,UACpC,WAAY,QAAQ,IAAI,aAAkB,UAC1C,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,QAASC,CACb,EAEAF,EAAS,WAAaC,EAAUN,EAAY,GAAKA,EAAY,oBAEzDG,GACAE,EAAS,UAAU,eAAgB,kBAAkB,EAGzDA,EAAS,IAAI,KAAK,UAAUG,EAAS,KAAM,CAAC,CAAC,CACjD,ECzBA,OAAS,eAAAR,MAAmB,oBAM5B,IAAOS,EAA2EP,GAA6B,MAAOQ,EAAmBL,IAAsC,CAC3K,GAAM,CAAE,QAAAC,CAAQ,EAAI,MAAMJ,EAAY,UAAU,EAEhDG,EAAS,WAAaC,EAAUN,EAAY,WAAaA,EAAY,oBACrEK,EAAS,IAAI,CACjB,ECPA,IAAMM,EAAN,KAAkD,CAAlD,cAII,KAAQ,eAAiD,CAAC,EAK1D,IAAW,cAAyB,CAChC,OAAO,OAAO,KAAK,KAAK,cAAc,CAC1C,CAKA,MAAc,cAAcC,EAAiBC,EAA6C,CACtF,IAAMC,EAAU,KAAK,eAA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KAAMd,CACV,EAnBW,CACH,YAAa,GAAGY,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAS,mBAAmBA,KAC5B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAMd,CACV,CAYR,OAASU,EAAP,CACE,MAAO,CACH,YAAa,GAAGE,KAAgBE,IAChC,OAAQ,CACJ,QAAS,GACT,QAAUJ,EAAgB,QAC1B,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,CACJ,CACJ,CACJ,EAEOwB,EAAQD","sourcesContent":["import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) => async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n status: healthy ? \"ok\" : \"error\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n timestamp: new Date().toISOString(),\n reports: report,\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n};\n\nexport type HealthCheckApiPayload = {\n status: \"error\" | \"ok\";\n message: string;\n appName: string;\n appVersion: string;\n timestamp: string;\n reports: HealthReport;\n};\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\n// eslint-disable-next-line max-len\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) => async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n};\n","import type {\n Checker, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry,\n} from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: { [service: string]: Checker } = {};\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error: any) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map((service) => this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n}\n\nexport default Healthcheck;\n","import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck = (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n): Checker => async () => {\n const { hints, family = \"all\", ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n addresses: meta,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n};\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck = (\n host: RequestInfo | URL,\n options?: {\n fetchOptions?: RequestInit;\n expected?: { status?: number; body?: string };\n },\n): Checker => async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(`${DISPLAY_NAME} ${host} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`);\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n};\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck = (expectedEnvironment?: string): Checker => async () => {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n};\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck = (host: string, options?: extendedPingOptions): Checker => async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error: any) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n};\n\nexport default pingCheck;\n"]}
1
+ {"version":3,"sources":["../src/checks/dns-check.ts","../src/checks/http-check.ts","../src/checks/node-environment-check.ts","../src/checks/ping-check.ts","../src/handler/healthcheck.ts","../src/handler/readyhandler.ts","../src/healthcheck.ts"],"names":["CacheableLookup","DISPLAY_NAME","dnsCheck","host","expectedAddresses","options","family","hints","config","cacheable","meta","error","dns_check_default","deepStrictEqual","httpCheck","response","textBody","http_check_default","nodeEnvironmentCheck","expectedEnvironment","environment","errorMessage","node_environment_check_default","ping","pingCheck","ping_check_default","StatusCodes","healthcheck_default","healthCheck","sendHeader","_","healthy","report","payload","readyhandler_default","_request","Healthcheck","service","reportSheet","checker"],"mappings":"AACA,OAAOA,MAAqB,mBAI5B,IAAMC,EAAe,gBAKfC,EACF,CACIC,EACAC,EACAC,IAKJ,SAAY,CACR,GAAM,CAAE,OAAAC,EAAS,MAAO,MAAAC,EAAO,GAAGC,CAAO,EAAIH,GAAW,CAAC,EAEnDI,EAAY,IAAIT,EAAgBQ,CAAM,EAE5C,GAAI,CACA,IAAME,EAAO,MAAMD,EAAU,YAAYN,EAAK,QAAQ,eAAgB,EAAE,EAAG,CACvE,MAAAI,EACA,GAAID,IAAW,MAAQ,CAAE,IAAK,EAAK,EAAI,CAAE,OAAAA,CAAO,CACpD,CAAC,EAED,OAAI,MA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AAS,WAAagB,EAAUL,EAAY,WAAaA,EAAY,oBACrEX,EAAS,IAAI,CACjB,ECTJ,IAAMqB,EAAN,KAAkD,CAAlD,cAII,KAAQ,eAA0C,CAAC,EAKnD,MAAc,cAAcC,EAAiBC,EAA6C,CAEtF,IAAMC,EAAU,KAAK,eAAeF,CAAO,EAEvCL,EAEJ,GAAI,CACAA,EAAS,MAAMO,EAAQ,EAEvBP,EAAO,YAAcA,EAAO,aAAeK,CAC/C,OAAS1B,EAAO,CACZqB,EAAS,CACL,YAAaK,EACb,OAAQ,CAAE,QAAS,GAAO,QAAU1B,EAAgB,QAAS,UAAW,IAAI,KAAK,EAAE,YAAY,CAAE,EACjG,KAAM,CAAE,MAAO,EAAK,CACxB,CACJ,CAGA,OAAA2B,EAAYD,CAAO,EAAIL,EAEhBA,EAAO,OAAO,OACzB,CAEO,WAAWK,EAAiBE,EAAwB,CAEvD,KAAK,eAAeF,CAAO,EAAIE,CACnC,CAMA,MAAa,WAAiE,CAC1E,IAAMP,EAAuB,CAAC,EAG9B,aAAM,QAAQ,IAAI,OAAO,KAAK,KAAK,cAAc,EAAE,IAAI,MAAOK,GAAY,MAAM,KAAK,cAAcA,EAASL,CAAM,CAAC,CAAC,EAQ7G,CAAE,QAAS,CAFO,OAAO,KAAKA,CAAM,EAAE,KAAMK,GAAY,CAAEL,EAAOK,CAAO,EAAwB,OAAO,OAAO,EAEhF,OAAAL,CAAO,CAChD,CAEA,MAAa,QAA2B,CACpC,GAAM,CAAE,QAAAD,CAAQ,EAAI,MAAM,KAAK,UAAU,EAEzC,OAAOA,CACX,CAKA,IAAW,cAAyB,CAChC,OAAO,OAAO,KAAK,KAAK,cAAc,CAC1C,CACJ,EAEOJ,EAAQS","sourcesContent":["import type { IPFamily, Options } from \"cacheable-lookup\";\nimport CacheableLookup from \"cacheable-lookup\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"DNS check for\";\n\n/**\n * Register the `dns` checker to ensure that a domain is reachable.\n */\nconst dnsCheck =\n (\n host: string,\n expectedAddresses?: string[],\n options?: Options & {\n family?: IPFamily | \"all\";\n hints?: number;\n },\n ): Checker =>\n async () => {\n const { family = \"all\", hints, ...config } = options ?? {};\n\n const cacheable = new CacheableLookup(config);\n\n try {\n const meta = await cacheable.lookupAsync(host.replace(/^https?:\\/\\//, \"\"), {\n hints,\n ...(family === \"all\" ? { all: true } : { family }),\n });\n\n if (Array.isArray(expectedAddresses) && !expectedAddresses.includes(meta.address)) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `${DISPLAY_NAME} ${host} returned address ${meta.address} instead of ${expectedAddresses.join(\", \")}.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n addresses: meta,\n host,\n },\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} were resolved.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n addresses: meta,\n host,\n },\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n },\n };\n }\n };\n\nexport default dnsCheck;\n","import { deepStrictEqual } from \"node:assert\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"HTTP check for\";\n\n/**\n * Register the `http` checker to ensure http body and status is correct.\n */\nconst httpCheck =\n (\n host: RequestInfo | URL,\n options?: {\n expected?: { body?: string; status?: number };\n fetchOptions?: RequestInit;\n },\n ): Checker =>\n async () => {\n try {\n // eslint-disable-next-line compat/compat\n const response = await fetch(host, options?.fetchOptions ?? {});\n\n if (options?.expected?.status !== undefined && options.expected.status !== response.status) {\n throw new Error(`${DISPLAY_NAME} ${host as string} returned status ${response.status} instead of ${options.expected.status}`);\n }\n\n if (options?.expected?.body !== undefined) {\n const textBody = await response.text();\n\n try {\n deepStrictEqual(textBody, options.expected.body);\n } catch {\n throw new Error(\n `${DISPLAY_NAME} ${host as string} returned body ${JSON.stringify(textBody)} instead of ${JSON.stringify(options.expected.body)}`,\n );\n }\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host as string}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host as string} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n status: response.status,\n },\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host as string}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n meta: {\n host,\n method: options?.fetchOptions?.method ?? \"GET\",\n },\n };\n }\n };\n\nexport default httpCheck;\n","import type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Node Environment Check\";\n\n/**\n * Register the `env` checker to ensure that `NODE_ENV` environment\n * variable is defined.\n */\nconst nodeEnvironmentCheck =\n (expectedEnvironment?: string): Checker =>\n async () => {\n const environment: string | undefined = process.env[\"NODE_ENV\"];\n\n let errorMessage: string | undefined;\n\n if (environment !== undefined && expectedEnvironment !== undefined && environment !== expectedEnvironment) {\n errorMessage = `NODE_ENV environment variable is set to \"${environment}\" instead of \"${expectedEnvironment}\".`;\n } else if (!environment) {\n errorMessage = [\"Missing NODE_ENV environment variable.\", \"It can make some parts of the application misbehave\"].join(\" \");\n }\n\n if (errorMessage !== undefined) {\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: false,\n message: errorMessage,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n return {\n displayName: DISPLAY_NAME,\n health: {\n healthy: true,\n timestamp: new Date().toISOString(),\n },\n meta: {\n env: environment,\n },\n };\n };\n\nexport default nodeEnvironmentCheck;\n","import type { extendedPingOptions } from \"pingman\";\nimport ping from \"pingman\";\n\nimport type { Checker } from \"../types\";\n\nconst DISPLAY_NAME = \"Ping check for\";\n\n/**\n * Register the `ping` checker to ensure that a domain is reachable.\n */\nconst pingCheck =\n (host: string, options?: extendedPingOptions): Checker =>\n async () => {\n try {\n const response = await ping(host.replace(/^https?:\\/\\//, \"\"), options);\n\n if (!response.alive) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: `Ping failed for ${host}.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n }\n\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: true,\n message: `${DISPLAY_NAME} ${host} was successful.`,\n timestamp: new Date().toISOString(),\n },\n meta: response,\n };\n } catch (error) {\n return {\n displayName: `${DISPLAY_NAME} ${host}`,\n health: {\n healthy: false,\n message: (error as Error).message,\n timestamp: new Date().toISOString(),\n },\n };\n }\n };\n\nexport default pingCheck;\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck, HealthReport } from \"../types\";\n\nexport interface HealthCheckApiPayload {\n appName: string;\n appVersion: string;\n message: string;\n reports: HealthReport;\n status: \"error\" | \"ok\";\n timestamp: string;\n}\n\nexport default (healthCheck: HealthCheck, sendHeader: boolean | undefined = true) =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(_: Request, response: Response): Promise<void> => {\n const { healthy, report } = await healthCheck.getReport();\n\n const payload: HealthCheckApiPayload = {\n appName: process.env[\"APP_NAME\"] ?? \"unknown\",\n appVersion: process.env[\"APP_VERSION\"] ?? \"unknown\",\n message: healthy ? \"Health check successful\" : \"Health check failed\",\n reports: report,\n status: healthy ? \"ok\" : \"error\",\n timestamp: new Date().toISOString(),\n };\n\n response.statusCode = healthy ? StatusCodes.OK : StatusCodes.SERVICE_UNAVAILABLE;\n\n if (sendHeader) {\n response.setHeader(\"Content-Type\", \"application/json\");\n }\n\n response.end(JSON.stringify(payload, null, 2));\n };\n","import { StatusCodes } from \"http-status-codes\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { HealthCheck } from \"../types\";\n\nexport default <Request extends IncomingMessage, Response extends ServerResponse>(healthCheck: HealthCheck) =>\n async (_request: Request, response: Response): Promise<void> => {\n const { healthy } = await healthCheck.getReport();\n\n response.statusCode = healthy ? StatusCodes.NO_CONTENT : StatusCodes.SERVICE_UNAVAILABLE;\n response.end();\n };\n","import type { Checker, HealthReport, HealthReportEntry, HealthCheck as HealthcheckInterface } from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: Record<string, Checker> = {};\n\n /**\n * Invokes a given checker to collect the report metrics.\n */\n private async invokeChecker(service: string, reportSheet: HealthReport): Promise<boolean> {\n // eslint-disable-next-line security/detect-object-injection\n const checker = this.healthCheckers[service] as Checker;\n\n let report: HealthReportEntry;\n\n try {\n report = await checker();\n\n report.displayName = report.displayName || service;\n } catch (error) {\n report = {\n displayName: service,\n health: { healthy: false, message: (error as Error).message, timestamp: new Date().toISOString() },\n meta: { fatal: true },\n };\n }\n\n // eslint-disable-next-line no-param-reassign,security/detect-object-injection\n reportSheet[service] = report;\n\n return report.health.healthy;\n }\n\n public addChecker(service: string, checker: Checker): void {\n // eslint-disable-next-line security/detect-object-injection\n this.healthCheckers[service] = checker;\n }\n\n /**\n * Returns the health check reports. The health checks are performed when\n * this method is invoked.\n */\n public async getReport(): Promise<{ healthy: boolean; report: HealthReport }> {\n const report: HealthReport = {};\n\n // eslint-disable-next-line compat/compat\n await Promise.all(Object.keys(this.healthCheckers).map(async (service) => await this.invokeChecker(service, report)));\n\n /**\n * Finding unhealthy service to know if system is healthy or not\n */\n // eslint-disable-next-line security/detect-object-injection\n const unhealthyService = Object.keys(report).find((service) => !(report[service] as HealthReportEntry).health.healthy);\n\n return { healthy: !unhealthyService, report };\n }\n\n public async isLive(): Promise<boolean> {\n const { healthy } = await this.getReport();\n\n return healthy;\n }\n\n /**\n * Returns an array of registered services names\n */\n public get servicesList(): string[] {\n return Object.keys(this.healthCheckers);\n }\n}\n\nexport default Healthcheck;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/health-check",
3
- "version": "1.0.6",
3
+ "version": "1.0.9",
4
4
  "description": "A library built to provide support for defining service health for node services. It allows you to register async health checks for your dependencies and the service itself, provides a health endpoint that exposes their status, and health metrics.",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -61,8 +61,11 @@
61
61
  "clean": "rimraf node_modules dist .eslintcache",
62
62
  "coverage": "vitest run --coverage",
63
63
  "dev": "pnpm run build --watch",
64
- "lint:eslint": "cross-env NO_LOGS=true eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.cjs --cache --cache-strategy content .",
64
+ "lint:eslint": "eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.js --cache --cache-strategy content .",
65
65
  "lint:eslint:fix": "pnpm run lint:eslint --fix",
66
+ "lint:prettier": "prettier --config=.prettierrc.js --check .",
67
+ "lint:prettier:fix": "prettier --config=.prettierrc.js --write .",
68
+ "lint:types": "tsc --noEmit",
66
69
  "test": "vitest run",
67
70
  "test:watch": "vitest"
68
71
  },
@@ -72,51 +75,29 @@
72
75
  "pingman": "^2.0.0"
73
76
  },
74
77
  "devDependencies": {
75
- "@anolilab/eslint-config": "^5.0.5",
76
- "@anolilab/semantic-release-preset": "^2.2.1",
78
+ "@anolilab/eslint-config": "^11.0.2",
79
+ "@anolilab/prettier-config": "^5.0.1",
80
+ "@anolilab/semantic-release-preset": "^6.0.2",
77
81
  "@rushstack/eslint-plugin-security": "^0.6.0",
78
- "@types/node": "18.16.16",
79
- "@types/react": "^18.2.8",
80
- "@types/react-dom": "^18.2.4",
81
- "@typescript-eslint/eslint-plugin": "^5.59.9",
82
- "@typescript-eslint/parser": "^5.59.9",
83
- "@vitest/coverage-v8": "^0.32.0",
82
+ "@types/node": "18.16.18",
83
+ "@vitest/coverage-v8": "^0.33.0",
84
84
  "cross-env": "^7.0.3",
85
- "cross-fetch": "^3.1.6",
86
- "eslint": "^8.42.0",
87
- "eslint-plugin-compat": "^4.1.4",
88
- "eslint-plugin-eslint-comments": "^3.2.0",
89
- "eslint-plugin-import": "^2.27.5",
90
- "eslint-plugin-json": "^3.1.0",
91
- "eslint-plugin-jsonc": "^2.8.0",
92
- "eslint-plugin-jsx-a11y": "^6.7.1",
93
- "eslint-plugin-markdown": "^3.0.0",
94
- "eslint-plugin-no-loops": "^0.3.0",
95
- "eslint-plugin-no-secrets": "^0.8.9",
96
- "eslint-plugin-node": "^11.1.0",
97
- "eslint-plugin-optimize-regex": "^1.2.1",
98
- "eslint-plugin-promise": "^6.1.1",
99
- "eslint-plugin-react": "7.32.2",
100
- "eslint-plugin-react-hooks": "4.6.0",
101
- "eslint-plugin-simple-import-sort": "^10.0.0",
102
- "eslint-plugin-sort-keys-fix": "^1.1.2",
103
- "eslint-plugin-testing-library": "^5.11.0",
104
- "eslint-plugin-unicorn": "^47.0.0",
105
- "eslint-plugin-you-dont-need-lodash-underscore": "^6.12.0",
106
- "eslint-plugin-you-dont-need-momentjs": "^1.6.0",
107
- "next": "^13.4.4",
85
+ "cross-fetch": "^4.0.0",
86
+ "eslint": "^8.46.0",
87
+ "eslint-plugin-etc": "^2.0.3",
88
+ "eslint-plugin-mdx": "^2.1.0",
89
+ "eslint-plugin-vitest": "^0.2.8",
90
+ "next": "^13.4.6",
108
91
  "node-mocks-http": "^1.12.2",
109
- "prettier": "^2.8.8",
110
- "react": "^18.2.0",
111
- "react-dom": "^18.2.0",
92
+ "prettier": "^3.0.0",
112
93
  "rimraf": "^5.0.1",
113
- "semantic-release": "^21.0.3",
114
- "tsup": "^6.7.0",
115
- "typescript": "^5.1.3",
116
- "vitest": "^0.32.0"
94
+ "semantic-release": "^21.0.7",
95
+ "tsup": "^7.1.0",
96
+ "typescript": "^5.1.6",
97
+ "vitest": "^0.33.0"
117
98
  },
118
99
  "optionalDependencies": {
119
- "next": "^13.4.4"
100
+ "next": "^13.4.5"
120
101
  },
121
102
  "engines": {
122
103
  "node": ">=16.18.0 <=20.*"
@@ -124,5 +105,16 @@
124
105
  "publishConfig": {
125
106
  "access": "public",
126
107
  "provenance": true
108
+ },
109
+ "anolilab": {
110
+ "eslint-config": {
111
+ "plugin": {
112
+ "tsdoc": false
113
+ },
114
+ "warn_on_unsupported_typescript_version": false,
115
+ "info_on_disabling_jsx_react_rule": false,
116
+ "info_on_disabling_prettier_conflict_rule": false,
117
+ "info_on_disabling_jsonc_sort_keys_rule": false
118
+ }
127
119
  }
128
120
  }