@visulima/health-check 2.0.2 → 2.0.3

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,11 @@
1
+ ## @visulima/health-check [2.0.3](https://github.com/visulima/visulima/compare/@visulima/health-check@2.0.2...@visulima/health-check@2.0.3) (2023-10-11)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * update all deps ([#215](https://github.com/visulima/visulima/issues/215)) ([c077ad8](https://github.com/visulima/visulima/commit/c077ad88a8a9427831b077bb729edd5b7e590ee8))
7
+ * updated deps ([b5a74f6](https://github.com/visulima/visulima/commit/b5a74f6bb8d7bf133e1df39cc67a80f93b287d1e))
8
+
1
9
  ## @visulima/health-check [2.0.2](https://github.com/visulima/visulima/compare/@visulima/health-check@2.0.1...@visulima/health-check@2.0.2) (2023-09-05)
2
10
 
3
11
 
package/dist/index.d.mts CHANGED
@@ -57,7 +57,6 @@ declare const _default: <Request_1 extends IncomingMessage, Response_1 extends S
57
57
 
58
58
  declare class Healthcheck implements HealthCheck {
59
59
  private healthCheckers;
60
- private invokeChecker;
61
60
  addChecker(service: string, checker: Checker): void;
62
61
  getReport(): Promise<{
63
62
  healthy: boolean;
@@ -65,6 +64,7 @@ declare class Healthcheck implements HealthCheck {
65
64
  }>;
66
65
  isLive(): Promise<boolean>;
67
66
  get servicesList(): string[];
67
+ private invokeChecker;
68
68
  }
69
69
 
70
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
@@ -57,7 +57,6 @@ declare const _default: <Request_1 extends IncomingMessage, Response_1 extends S
57
57
 
58
58
  declare class Healthcheck implements HealthCheck {
59
59
  private healthCheckers;
60
- private invokeChecker;
61
60
  addChecker(service: string, checker: Checker): void;
62
61
  getReport(): Promise<{
63
62
  healthy: boolean;
@@ -65,6 +64,7 @@ declare class Healthcheck implements HealthCheck {
65
64
  }>;
66
65
  isLive(): Promise<boolean>;
67
66
  get servicesList(): string[];
67
+ private invokeChecker;
68
68
  }
69
69
 
70
70
  export { Checker, Healthcheck as HealthCheck, dnsCheck, _default$1 as healthCheckHandler, _default as healthReadyHandler, httpCheck, nodeEnvironmentCheck as nodeEnvCheck, pingCheck };
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
10
  var u__default = /*#__PURE__*/_interopDefault(u);
11
11
  var R__default = /*#__PURE__*/_interopDefault(R);
12
12
 
13
- var h="DNS check for",g=(t,e,a)=>async()=>{let{family:r="all",hints:s,...i}=a??{},c=new u__default.default(i);try{let o=await c.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(o.address)?{displayName:`${h} ${t}`,health:{healthy:!1,message:`${h} ${t} returned address ${o.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:o,host:t}}:{displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:o,host:t}}}catch(o){return {displayName:`${h} ${t}`,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{host:t}}}},k=g;var p="HTTP check for",S=(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(`${p} ${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(`${p} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},N=S;var d="Node Environment Check",$=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:d,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:d,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},O=$;var l="Ping check for",w=(t,e)=>async()=>{try{let a=await R__default.default(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${l} ${t}`,health:{healthy:!0,message:`${l} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${l} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${l} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},E=w;var I=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:i}=await t.getReport(),c={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:i,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(c,null,2));};var x=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?httpStatusCodes.StatusCodes.NO_CONTENT:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,a.end();};var m=class{constructor(){this.healthCheckers={};}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(i){s={displayName:e,health:{healthy:!1,message:i.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)}},v=m;
13
+ var h="DNS check for",g=(t,e,a)=>async()=>{let{family:r="all",hints:s,...i}=a??{},c=new u__default.default(i);try{let o=await c.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(o.address)?{displayName:`${h} ${t}`,health:{healthy:!1,message:`${h} ${t} returned address ${o.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:o,host:t}}:{displayName:`${h} ${t}`,health:{healthy:!0,message:`${h} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:o,host:t}}}catch(o){return {displayName:`${h} ${t}`,health:{healthy:!1,message:o.message,timestamp:new Date().toISOString()},meta:{host:t}}}},k=g;var p="HTTP check for",S=(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(`${p} ${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(`${p} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${p} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},N=S;var d="Node Environment Check",$=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:d,health:{healthy:!1,message:a,timestamp:new Date().toISOString()}}:{displayName:d,health:{healthy:!0,timestamp:new Date().toISOString()},meta:{env:e}}},O=$;var l="Ping check for",w=(t,e)=>async()=>{try{let a=await R__default.default(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${l} ${t}`,health:{healthy:!0,message:`${l} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${l} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${l} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},E=w;var I=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:i}=await t.getReport(),c={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:i,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(c,null,2));};var x=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?httpStatusCodes.StatusCodes.NO_CONTENT:httpStatusCodes.StatusCodes.SERVICE_UNAVAILABLE,a.end();};var m=class{constructor(){this.healthCheckers={};}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)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(i){s={displayName:e,health:{healthy:!1,message:i.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}},v=m;
14
14
 
15
15
  exports.HealthCheck = v;
16
16
  exports.dnsCheck = k;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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,MAAM,QAAQF,CAAiB,GAAK,CAACA,EAAkB,SAASM,EAAK,OAAO,EACrE,CACH,YAAa,GAAGT,CAAY,IAAIE,CAAI,GACpC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,CAAY,IAAIE,CAAI,qBAAqBO,EAAK,OAAO,eAAeN,EAAkB,KAAK,IAAI,CAAC,IAC5G,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,UAAWM,EACX,KAAAP,CACJ,CACJ,EAGG,CACH,YAAa,GAAGF,CAAY,IAAIE,CAAI,GACpC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,CAAY,IAAIE,CAAI,kBAChC,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,UA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2B,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 type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { StatusCodes } from \"http-status-codes\";\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 type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { StatusCodes } from \"http-status-codes\";\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"]}
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","checker","reportSheet"],"mappings":"AACA,OAAOA,MAAqB,mBAI5B,IAAMC,EAAe,gBAKfC,EACF,CACIC,EACAC,EACAC,IAKJ,SAAY,CACR,GAAM,CAAE,OAAAC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ACjG,KAAM,CAAE,MAAO,EAAK,CACxB,CACJ,CAGA,OAAA4B,EAAYF,CAAO,EAAIL,EAEhBA,EAAO,OAAO,OACzB,CACJ,EAEOL,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 // eslint-disable-next-line require-unicode-regexp\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 // eslint-disable-next-line require-unicode-regexp\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 type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { StatusCodes } from \"http-status-codes\";\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 type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { StatusCodes } from \"http-status-codes\";\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, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry } from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: Record<string, Checker> = {};\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 /**\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\nexport default Healthcheck;\n"]}
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { deepStrictEqual } from 'assert';
3
3
  import w from 'pingman';
4
4
  import { StatusCodes } from 'http-status-codes';
5
5
 
6
- var p="DNS check for",k=(t,e,a)=>async()=>{let{family:r="all",hints:s,...h}=a??{},m=new g(h);try{let i=await m.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(i.address)?{displayName:`${p} ${t}`,health:{healthy:!1,message:`${p} ${t} returned address ${i.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:i,host:t}}:{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:i,host:t}}}catch(i){return {displayName:`${p} ${t}`,health:{healthy:!1,message:i.message,timestamp:new Date().toISOString()},meta:{host:t}}}},C=k;var l="HTTP check for",N=(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(`${l} ${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(`${l} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${l} ${t}`,health:{healthy:!0,message:`${l} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${l} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},$=N;var y="Node Environment Check",O=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}}},R=O;var c="Ping check for",E=(t,e)=>async()=>{try{let a=await w(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${c} ${t}`,health:{healthy:!0,message:`${c} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${c} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${c} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},I=E;var x=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:h}=await t.getReport(),m={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:h,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(m,null,2));};var v=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?StatusCodes.NO_CONTENT:StatusCodes.SERVICE_UNAVAILABLE,a.end();};var d=class{constructor(){this.healthCheckers={};}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(h){s={displayName:e,health:{healthy:!1,message:h.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)}},b=d;
6
+ var p="DNS check for",k=(t,e,a)=>async()=>{let{family:r="all",hints:s,...h}=a??{},m=new g(h);try{let i=await m.lookupAsync(t.replace(/^https?:\/\//,""),{hints:s,...r==="all"?{all:!0}:{family:r}});return Array.isArray(e)&&!e.includes(i.address)?{displayName:`${p} ${t}`,health:{healthy:!1,message:`${p} ${t} returned address ${i.address} instead of ${e.join(", ")}.`,timestamp:new Date().toISOString()},meta:{addresses:i,host:t}}:{displayName:`${p} ${t}`,health:{healthy:!0,message:`${p} ${t} were resolved.`,timestamp:new Date().toISOString()},meta:{addresses:i,host:t}}}catch(i){return {displayName:`${p} ${t}`,health:{healthy:!1,message:i.message,timestamp:new Date().toISOString()},meta:{host:t}}}},C=k;var l="HTTP check for",N=(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(`${l} ${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(`${l} ${t} returned body ${JSON.stringify(r)} instead of ${JSON.stringify(e.expected.body)}`)}}return {displayName:`${l} ${t}`,health:{healthy:!0,message:`${l} ${t} was successful.`,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET",status:a.status}}}catch(a){return {displayName:`${l} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()},meta:{host:t,method:e?.fetchOptions?.method??"GET"}}}},$=N;var y="Node Environment Check",O=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}}},R=O;var c="Ping check for",E=(t,e)=>async()=>{try{let a=await w(t.replace(/^https?:\/\//,""),e);return a.alive?{displayName:`${c} ${t}`,health:{healthy:!0,message:`${c} ${t} was successful.`,timestamp:new Date().toISOString()},meta:a}:{displayName:`${c} ${t}`,health:{healthy:!1,message:`Ping failed for ${t}.`,timestamp:new Date().toISOString()},meta:a}}catch(a){return {displayName:`${c} ${t}`,health:{healthy:!1,message:a.message,timestamp:new Date().toISOString()}}}},I=E;var x=(t,e=!0)=>async(a,r)=>{let{healthy:s,report:h}=await t.getReport(),m={appName:process.env.APP_NAME??"unknown",appVersion:process.env.APP_VERSION??"unknown",message:s?"Health check successful":"Health check failed",reports:h,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(m,null,2));};var v=t=>async(e,a)=>{let{healthy:r}=await t.getReport();a.statusCode=r?StatusCodes.NO_CONTENT:StatusCodes.SERVICE_UNAVAILABLE,a.end();};var d=class{constructor(){this.healthCheckers={};}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)}async invokeChecker(e,a){let r=this.healthCheckers[e],s;try{s=await r(),s.displayName=s.displayName||e;}catch(h){s={displayName:e,health:{healthy:!1,message:h.message,timestamp:new Date().toISOString()},meta:{fatal:!0}};}return a[e]=s,s.health.healthy}},b=d;
7
7
 
8
8
  export { b as HealthCheck, C as dnsCheck, x as healthCheckHandler, v as healthReadyHandler, $ as httpCheck, R as nodeEnvCheck, I as pingCheck };
9
9
  //# sourceMappingURL=out.js.map
@@ -1 +1 @@
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,MAAM,QAAQF,CAAiB,GAAK,CAACA,EAAkB,SAASM,EAAK,OAAO,EACrE,CACH,YAAa,GAAGT,CAAY,IAAIE,CAAI,GACpC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,CAAY,IAAIE,CAAI,qBAAqBO,EAAK,OAAO,eAAeN,EAAkB,KAAK,IAAI,CAAC,IAC5G,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,UAAWM,EACX,KAAAP,CACJ,CACJ,EAGG,CACH,YAAa,GAAGF,CAAY,IAAIE,CAAI,GACpC,OAAQ,CACJ,QAAS,GACT,QAAS,GAAGF,CAAY,IAAIE,CAAI,kBAChC,UAAW,IAAI,KAAK,EAAE,YAAY,CACtC,EACA,KAAM,CACF,UAAWO,EACX,KAAAP,CACJ,CACJ,CACJ,O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O,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 type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { StatusCodes } from \"http-status-codes\";\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 type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { StatusCodes } from \"http-status-codes\";\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"]}
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","checker","reportSheet"],"mappings":"AACA,OAAOA,MAAqB,mBAI5B,IAAMC,EAAe,gBAKfC,EACF,CACIC,EACAC,EACAC,IAKJ,SAAY,CACR,GAAM,CAAE,OAAAC,EAAS,MAAO,MAAAC,EAAO,GAAGC,CA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ACJ,CAGA,OAAA4B,EAAYF,CAAO,EAAIL,EAEhBA,EAAO,OAAO,OACzB,CACJ,EAEOL,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 // eslint-disable-next-line require-unicode-regexp\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 // eslint-disable-next-line require-unicode-regexp\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 type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { StatusCodes } from \"http-status-codes\";\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 type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { StatusCodes } from \"http-status-codes\";\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, HealthCheck as HealthcheckInterface, HealthReport, HealthReportEntry } from \"./types.d\";\n\nclass Healthcheck implements HealthcheckInterface {\n /**\n * A copy of registered checkers\n */\n private healthCheckers: Record<string, Checker> = {};\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 /**\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\nexport default Healthcheck;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/health-check",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
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",
@@ -77,32 +77,35 @@
77
77
  },
78
78
  "dependencies": {
79
79
  "cacheable-lookup": "^7.0.0",
80
- "http-status-codes": "^2.2.0",
80
+ "http-status-codes": "^2.3.0",
81
81
  "pingman": "^2.0.0"
82
82
  },
83
83
  "devDependencies": {
84
- "@anolilab/eslint-config": "^11.3.5",
85
- "@anolilab/prettier-config": "^5.0.4",
86
- "@anolilab/semantic-release-preset": "^6.0.5",
87
- "@rushstack/eslint-plugin-security": "^0.6.0",
84
+ "@anolilab/eslint-config": "^14.0.24",
85
+ "@anolilab/prettier-config": "^5.0.11",
86
+ "@anolilab/semantic-release-preset": "^8.0.0",
87
+ "@babel/core": "^7.23.0",
88
+ "@rushstack/eslint-plugin-security": "^0.7.1",
88
89
  "@types/node": "18.17.12",
89
- "@vitest/coverage-v8": "^0.34.3",
90
+ "@vitest/coverage-v8": "^0.34.6",
90
91
  "cross-env": "^7.0.3",
91
92
  "cross-fetch": "^4.0.0",
92
- "eslint": "^8.48.0",
93
+ "eslint": "^8.51.0",
94
+ "eslint-plugin-deprecation": "^2.0.0",
93
95
  "eslint-plugin-etc": "^2.0.3",
96
+ "eslint-plugin-import": "npm:eslint-plugin-i@^2.28.1",
94
97
  "eslint-plugin-mdx": "^2.2.0",
95
- "eslint-plugin-vitest": "^0.2.8",
98
+ "eslint-plugin-vitest": "^0.3.2",
96
99
  "eslint-plugin-vitest-globals": "^1.4.0",
97
100
  "next": "^13.4.19",
98
101
  "node-mocks-http": "^1.13.0",
99
102
  "prettier": "^3.0.3",
100
- "rimraf": "^5.0.1",
101
- "semantic-release": "^21.1.1",
102
- "sort-package-json": "^2.5.1",
103
+ "rimraf": "^5.0.5",
104
+ "semantic-release": "^22.0.5",
105
+ "sort-package-json": "^2.6.0",
103
106
  "tsup": "^7.2.0",
104
107
  "typescript": "^5.2.2",
105
- "vitest": "^0.34.3"
108
+ "vitest": "^0.34.6"
106
109
  },
107
110
  "optionalDependencies": {
108
111
  "next": "^13.4.19"
@@ -122,7 +125,8 @@
122
125
  "warn_on_unsupported_typescript_version": false,
123
126
  "info_on_disabling_jsx_react_rule": false,
124
127
  "info_on_disabling_prettier_conflict_rule": false,
125
- "info_on_disabling_jsonc_sort_keys_rule": false
128
+ "info_on_disabling_jsonc_sort_keys_rule": false,
129
+ "info_on_disabling_etc_no_deprecated": false
126
130
  }
127
131
  }
128
132
  }