UNPKG

wizinsight

Version:

A lightweight performance monitoring & health tracking library for hyperwiz with Discord alerts and smart request optimization. Track API requests, monitor endpoint health, and get instant alerts when issues arise.

23 lines (20 loc) 5.83 kB
'use strict';/* Copyright (c) 2025 Parth Tyagi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var x=Object.defineProperty;var A=(s,t)=>()=>(s&&(t=s(s=0)),t);var C=(s,t)=>{for(var o in t)x(s,o,{get:t[o],enumerable:true});};var E={};C(E,{getHealthStatus:()=>k,initHealthMonitor:()=>b,stopHealthMonitor:()=>T});function b(s){h&&h.stop(),h=new w(s),h.start();}function k(){return h?h.getHealthStatus():{}}function T(){h&&(h.stop(),h=null);}var w,h,S=A(()=>{w=class{constructor(t){this.state={};this.lastAlert=0;this.options={interval:t.interval||6e4,alertCooldown:t.alertCooldown||9e5,...t};}start(){this.intervalId||(this.checkAllTargets(),this.intervalId=setInterval(()=>{this.checkAllTargets();},this.options.interval));}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0);}getHealthStatus(){return {...this.state}}async checkAllTargets(){let t=this.options.targets.map(o=>this.checkTarget(o));await Promise.allSettled(t);}async checkTarget(t){let o=t.method||"GET",u=t.expectedStatus||200,n=Date.now(),c={method:o,headers:{"User-Agent":"wizinsight-health-monitor",...t.headers}};t.body&&(typeof t.body=="string"?c.body=t.body:(c.body=JSON.stringify(t.body),t.headers?.["Content-Type"]||(c.headers={...c.headers,"Content-Type":"application/json"})));try{let i;t.timeout?i=await Promise.race([fetch(t.url,c),new Promise((p,f)=>setTimeout(()=>f(new Error("timeout")),t.timeout))]):i=await fetch(t.url,c);let e=Date.now()-n,a=i.status===u;this.state[t.url]={lastChecked:n,lastStatus:i.status,isHealthy:a,lastError:a?void 0:`Expected ${u}, got ${i.status}`},!a&&this.shouldSendAlert()&&(await this.sendAlert(t,i.status,e),this.lastAlert=Date.now());}catch(i){let e=Date.now()-n,a="Unknown error";i instanceof Error&&(i.message==="timeout"?a=`Request timeout after ${t.timeout}ms`:i.message.includes("fetch")?a="Network error":a=i.message),this.state[t.url]={lastChecked:n,lastStatus:0,isHealthy:false,lastError:a},this.shouldSendAlert()&&(await this.sendAlert(t,0,e,a),this.lastAlert=Date.now());}}shouldSendAlert(){return this.options.discordWebhook?Date.now()-this.lastAlert>this.options.alertCooldown:false}async sendAlert(t,o,u,n){if(!this.options.discordWebhook)return;let i=[`**Method:** ${t.method||"GET"}`,`**URL:** ${t.url}`,`**Duration:** ${u}ms`,`**Expected Status:** ${t.expectedStatus||200}`],e="";n?n.includes("timeout")?e=`\u23F0 **Timeout Error:** Request timed out after ${t.timeout}ms`:n.includes("Network error")?e="\u{1F310} **Network Error:** Unable to reach the server. Check if the service is running.":n.includes("fetch")?e="\u{1F310} **Fetch Error:** Network request failed. Check connectivity.":n.includes("JSON")?e="\u{1F4C4} **JSON Error:** Invalid JSON response from server.":o!==0?e=`\u{1F4CA} **HTTP Error:** Server returned status ${o}`:e=`\u274C **Error:** ${n}`:o!==t.expectedStatus&&(e=`\u{1F4CA} **Status Mismatch:** Expected ${t.expectedStatus||200}, got ${o}`);let p={embeds:[{title:`\u{1F6A8} Health Check Failed: ${t.name}`,description:"API endpoint is not responding as expected",color:16711680,fields:[{name:"\u{1F50D} Request Details",value:i.join(` `),inline:false},{name:"\u274C Error Details",value:e,inline:false}],timestamp:new Date().toISOString(),footer:{text:"wizinsight health monitor"}}]};try{await fetch(this.options.discordWebhook,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});}catch{}}},h=null;});var O=s=>s.name==="AbortError"?"Timeout":s.message?.includes("fetch")?"Network error":s.message?.includes("JSON")?"Invalid response":s.message||"Error";function v(s={}){let{onRequestStart:t,onRequestEnd:o,onRequestError:u,unhealthyStrategy:n="skip_body",fallbackUrl:c}=s;return function(e){return ["get","post","put","patch","delete","head","options"].forEach(p=>{if(typeof e[p]=="function"){let f=e[p];e[p]=async function(m,M={}){let H=Date.now(),l={url:m,method:p.toUpperCase(),duration:0},y=null;try{let{getHealthStatus:r}=await Promise.resolve().then(()=>(S(),E));y=r()[m];}catch{}let d={...M},I=m;if(y&&!y.isHealthy)switch(n){case "skip_body":delete d.body,delete d.headers?.["Content-Type"],d.headers={...d.headers,"X-Health-Warning":"API marked as unhealthy"};break;case "skip_request":throw new Error("API unhealthy - request skipped");case "fallback":I=c||m;break}t&&t(l);try{let r=await f.call(e,I,d);return l.duration=Date.now()-H,r&&typeof r=="object"&&("status"in r?l.status=r.status:"_response"in r&&r._response?.status?l.status=r._response.status:"response"in r&&r.response?.status?l.status=r.response.status:l.status=200),o&&o(l),r}catch(r){throw l.duration=Date.now()-H,l.error=O(r),u&&u(l),r}};}}),e}}S();function N(s,t){return v(t)(s)}exports.createMetricsInterceptor=v;exports.getHealthStatus=k;exports.initHealthMonitor=b;exports.initMetricsInterceptor=N;exports.stopHealthMonitor=T;