@dmhsq_monitor/web
Version:
Web monitoring package for monitor system
3 lines (2 loc) • 9.82 kB
JavaScript
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@dmhsq_monitor/core"),require("@dmhsq_monitor/processor"),require("@dmhsq_monitor/utils")):"function"==typeof define&&define.amd?define(["exports","@dmhsq_monitor/core","@dmhsq_monitor/processor","@dmhsq_monitor/utils"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).DMHSQMonitorWeb={},e.DMHSQMonitorCore,e.DMHSQMonitorProcessor)}(this,(function(e,r,n){"use strict";const o={JS_ERROR:"js_error",RESOURCE_ERROR:"resource_error",UNHANDLED_REJECTION:"unhandled_rejection",HTTP_ERROR:"http_error",CONSOLE_ERROR:"console_error",PAGE_LOAD:"page_load",PAGE_VISIBILITY:"page_visibility",RESOURCE_PERFORMANCE:"resource_performance",LARGEST_CONTENTFUL_PAINT:"largest_contentful_paint",FIRST_INPUT_DELAY:"first_input_delay",CUMULATIVE_LAYOUT_SHIFT:"cumulative_layout_shift",CLICK:"click",PAGE_VIEW:"page_view",CUSTOM:"custom"},t={enableAutoErrorCapture:!0,enablePerformanceMonitoring:!0,enableRequestMonitoring:!0,enableBehaviorMonitoring:!1,enableRouteMonitoring:!0,enableConsoleMonitoring:!1,enablePerformance:!0,enableError:!0,errorSamplingRate:1,behaviorSamplingRate:.5,maxCache:100,reportInterval:5e3};function i(e){return Math.random()<=e}function s(e,r=[]){return!!e&&r.some((r=>r instanceof RegExp?r.test(e):e.includes(r)))}class a{constructor(e,r){this.isInstalled=!1,this.originalOnError=null,this.originalOnUnhandledRejection=null,this.monitor=e,this.config=r,this.originalOnError=null,this.originalOnUnhandledRejection=null,this.originalConsoleError=console.error}install(){this.isInstalled||(this.setupJsErrorHandler(),this.setupPromiseErrorHandler(),this.setupResourceErrorHandler(),this.config.enableConsoleMonitoring&&this.setupConsoleErrorHandler(),this.isInstalled=!0)}uninstall(){this.isInstalled&&(null!==this.originalOnError&&(window.onerror=this.originalOnError,this.originalOnError=null),null!==this.originalOnUnhandledRejection&&(window.removeEventListener("unhandledrejection",this.handleUnhandledRejection),this.originalOnUnhandledRejection=null),window.removeEventListener("error",this.handleResourceError,!0),this.config.enableConsoleMonitoring&&(console.error=this.originalConsoleError),this.isInstalled=!1)}setupJsErrorHandler(){this.originalOnError=window.onerror,window.onerror=(e,r,n,o,t)=>{this.originalOnError&&this.originalOnError.call(window,e,r,n,o,t),this.handleJsError(e,r,n,o,t)}}handleJsError(e,n,t,a,l){if(!i(this.config.errorSamplingRate||1))return;const c=(null==l?void 0:l.message)||("string"==typeof e?e:"Unknown error");if(s(c,this.config.ignoreErrors))return;if(n&&function(e,r=[]){return!!e&&r.some((r=>r.test(e)))}(n,this.config.ignoreUrls))return;const h={message:c,name:(null==l?void 0:l.name)||"Error",stack:null==l?void 0:l.stack,url:n||window.location.href,timestamp:Date.now(),userAgent:navigator.userAgent};this.monitor.report({type:r.EventType.ERROR,name:o.JS_ERROR,data:h})}setupPromiseErrorHandler(){this.handleUnhandledRejection=this.handleUnhandledRejection.bind(this),window.addEventListener("unhandledrejection",this.handleUnhandledRejection)}handleUnhandledRejection(e){if(!i(this.config.errorSamplingRate||1))return;e.preventDefault();const n=e.reason;let t="Promise rejected",a="",l="UnhandledRejection";if(n instanceof Error)t=n.message,a=n.stack||"",l=n.name;else if("string"==typeof n)t=n;else if(null!==n&&"object"==typeof n)try{t=JSON.stringify(n)}catch(e){t="Unserializable promise rejection reason"}if(s(t,this.config.ignoreErrors))return;const c={message:t,stack:a,name:l,type:"unhandledrejection",url:window.location.href,timestamp:Date.now()};this.monitor.report({type:r.EventType.ERROR,name:o.UNHANDLED_REJECTION,data:c})}setupResourceErrorHandler(){this.handleResourceError=this.handleResourceError.bind(this),window.addEventListener("error",this.handleResourceError,!0)}handleResourceError(e){if(!i(this.config.errorSamplingRate||1))return;if(!e.target||!e.target.tagName)return;const n=e.target,t=n.tagName.toLowerCase();if(!["img","link","script","audio","video"].includes(t))return;const s=n.src||n.href||"";if(this.shouldIgnoreUrl(s))return;const a={tagName:t,src:s,href:n.href,outerHTML:n.outerHTML.slice(0,200),url:window.location.href,timestamp:Date.now()};this.monitor.report({type:r.EventType.ERROR,name:o.RESOURCE_ERROR,data:a})}setupConsoleErrorHandler(){this.handleConsoleError=this.handleConsoleError.bind(this),this.originalConsoleError=console.error,console.error=(...e)=>{this.originalConsoleError.apply(console,e),this.handleConsoleError(...e)}}handleConsoleError(...e){if(!i(this.config.errorSamplingRate||1))return;const n=e.map((e=>{if(e instanceof Error)return e.message;if("object"!=typeof e)return String(e);try{return JSON.stringify(e)}catch(r){return String(e)}})).join(" ");s(n,this.config.ignoreErrors)||this.monitor.report({type:r.EventType.ERROR,name:o.CONSOLE_ERROR,data:{message:n,name:"ConsoleError",timestamp:Date.now(),args:e.map(String).join(", ")}})}shouldIgnoreUrl(e){return!!e&&(!(!this.config.ignoreUrls||!this.config.ignoreUrls.length)&&this.config.ignoreUrls.some((r=>r.test(e))))}}class l{constructor(e,r){this.isInstalled=!1,this.originalOnLoad=null,this.visibilityChangeHandler=null,this.monitor=e,this.config=r,this.originalOnLoad=null}install(){this.isInstalled||!1===this.config.enablePerformance&&!1===this.config.enablePerformanceMonitoring||(this.setupLoadPerformanceMonitor(),this.setupVisibilityChangeMonitor(),this.isInstalled=!0)}uninstall(){this.isInstalled&&(this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null),this.isInstalled=!1)}setupLoadPerformanceMonitor(){!1===this.config.enablePerformance&&!1===this.config.enablePerformanceMonitoring||("complete"===document.readyState?this.collectPageLoadPerformance():window.addEventListener("load",(()=>{setTimeout((()=>this.collectPageLoadPerformance()),0)})))}collectPageLoadPerformance(){if(!1===this.config.enablePerformance&&!1===this.config.enablePerformanceMonitoring)return;if(!i(this.config.errorSamplingRate||1))return;if(!window.performance||!window.performance.timing)return;const e=performance.getEntriesByType("navigation")[0];let n="";try{if(document.referrer){const e=new URL(document.referrer);n=e.hostname===window.location.hostname?e.pathname:document.referrer}}catch(e){n=document.referrer||""}const t={loadTime:Number((e.loadEventEnd-e.startTime).toFixed(3)),domReadyTime:Number((e.domComplete-e.domInteractive).toFixed(3)),redirectTime:Number((e.redirectEnd-e.redirectStart).toFixed(3)),dnsTime:Number((e.domainLookupEnd-e.domainLookupStart).toFixed(3)),tcpTime:Number((e.connectEnd-e.connectStart).toFixed(3)),ttfb:Number((e.responseStart-e.requestStart).toFixed(3)),responseTime:Number((e.responseEnd-e.responseStart).toFixed(3)),domContentLoadedTime:Number((e.domContentLoadedEventEnd-e.startTime).toFixed(3)),url:window.location.href,referrer:document.referrer||"direct",entryType:document.referrer?"navigation":"direct",sourceLink:n};this.collectPaintTimings(t),this.monitor.report({type:r.EventType.PERFORMANCE,name:o.PAGE_LOAD,data:t})}collectPaintTimings(e){if(window.performance&&"getEntriesByType"in window.performance){window.performance.getEntriesByType("paint").forEach((r=>{const{name:n,startTime:o}=r;"first-paint"===n?e.firstPaint=Math.round(o):"first-contentful-paint"===n&&(e.firstContentfulPaint=Math.round(o))}))}}setupVisibilityChangeMonitor(){this.config.enablePageVisibility&&(this.visibilityChangeHandler=()=>{const e="visible"===document.visibilityState;this.monitor.report({type:r.EventType.PERFORMANCE,name:o.PAGE_VISIBILITY,data:{isVisible:e,timestamp:Date.now(),url:window.location.href}})},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}}e.CONTENT_SAMPLING_RATES={ERROR_STACK:1,CONSOLE_LOGS:.1,REQUEST_BODY:.1,RESPONSE_BODY:.1,INPUT_VALUES:.1},e.DEFAULT_CONFIG=t,e.EVENT_TYPES=o,e.ErrorMonitor=a,e.MAX_CONTENT_LENGTH=2e3,e.PerformanceMonitor=l,e.WEB_MONITOR_VERSION="1.0.25",e.WebMonitor=class{constructor(e){this.errorMonitor=null,this.performanceMonitor=null,this.isStarted=!1;const o={...t,...e};!1===e.enablePerformance&&(o.enablePerformance=!1,o.enablePerformanceMonitoring=!1),!1===e.enableError&&(o.enableError=!1,o.enableAutoErrorCapture=!1),this.config=o,this.monitor=new r.Monitor,this.processor=new n.Processor,this.processor.updateConfig({enableDeduplicate:!1!==this.config.enableDeduplicate,collectGeoInfo:!0===this.config.collectGeoInfo,mergeSimilarErrors:!1!==this.config.mergeSimilarErrors,customProcessors:[]}),o.debug&&console.log("[WebMonitor] Processor initialized with config:",this.processor.getConfig())}start(){if(this.isStarted)return;this.monitor.init(this.config);const e=this.config.onReport;this.config.onReport=async(r,n)=>{try{const o=await this.processor.batchProcess(r,n);return"function"==typeof e?e(o,n):o}catch(o){return console.error("[WebMonitor] Error processing events:",o),"function"==typeof e?e(r,n):r}},this.monitor.start(),!1!==this.config.enableError&&!1!==this.config.enableAutoErrorCapture&&(this.errorMonitor=new a(this.monitor,this.config),this.errorMonitor.install()),!0===this.config.enablePerformance&&!1!==this.config.enablePerformanceMonitoring&&(this.performanceMonitor=new l(this.monitor,this.config),this.performanceMonitor.install()),this.isStarted=!0}stop(){this.isStarted&&(this.errorMonitor&&(this.errorMonitor.uninstall(),this.errorMonitor=null),this.performanceMonitor&&(this.performanceMonitor.uninstall(),this.performanceMonitor=null),this.monitor.stop(),this.isStarted=!1)}report(e){this.monitor.report(e)}getMonitor(){return this.monitor}getProcessor(){return this.processor}clearDeduplicationCache(){const e=this.processor._cleanupEventHashes;"function"==typeof e&&e()}}}));
//# sourceMappingURL=index.umd.js.map