UNPKG

@dmhsq_monitor/processor

Version:
3 lines (2 loc) 8.81 kB
import{EventType as t}from"@dmhsq_monitor/core";const e="DMHSQMonitorProcessor",o="1.0.22",n=18e5,r=.85;var i,a;!function(t){t.IPAPI="ipapi",t.IPINFO="ipinfo",t.CUSTOM="custom"}(i||(i={})),function(t){t.SUCCESS="success",t.FILTERED="filtered",t.DUPLICATE="duplicate",t.FAILED="failed"}(a||(a={}));class s{constructor(){this.config={enableDeduplicate:!0,deduplicateWindow:n,collectUserIp:!0,collectGeoInfo:!1,mergeSimilarErrors:!0,customProcessors:[]}}init(t){this.config={...this.config,...t}}updateConfig(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}isDeduplicateEnabled(){return!!this.config.enableDeduplicate}getDeduplicateWindow(){return this.config.deduplicateWindow||n}shouldCollectUserIp(){return!!this.config.collectUserIp}shouldCollectGeoInfo(){return!!this.config.collectGeoInfo}shouldMergeSimilarErrors(){return!!this.config.mergeSimilarErrors}getCustomProcessors(){return this.config.customProcessors||[]}}const c=new Map;function l(e){var o;let n="";switch(e.type){case t.ERROR:n=`${e.type}_${e.data.errorType}_${e.data.message}_${(null===(o=e.data.stack)||void 0===o?void 0:o.substring(0,100))||""}`;break;case t.PERFORMANCE:n=`${e.type}_${e.data.url||""}_${e.name}`;break;case t.BEHAVIOR:n=`${e.type}_${e.name}_${e.data.element||""}`;break;default:n=`${e.type}_${e.name}`}return function(t){let e=0;if(0===t.length)return e.toString();for(let o=0;o<t.length;o++){e=(e<<5)-e+t.charCodeAt(o),e|=0}return e.toString()}(n)}function h(t,e=18e5){const o=l(t),n=Date.now();if(c.has(o)){if(n-(c.get(o)||0)<e){c.set(o,n);try{const t=JSON.parse(localStorage.getItem("dmhsq_monitor_hashes")||"{}");t[o]=n,localStorage.setItem("dmhsq_monitor_hashes",JSON.stringify(t))}catch(t){}return!0}}c.set(o,n);try{const t=JSON.parse(localStorage.getItem("dmhsq_monitor_hashes")||"{}");t[o]=n,localStorage.setItem("dmhsq_monitor_hashes",JSON.stringify(t))}catch(t){}return!1}function f(t=36e5){const e=Date.now();for(const[o,n]of c.entries())e-n>t&&c.delete(o);try{const o=JSON.parse(localStorage.getItem("dmhsq_monitor_hashes")||"{}");let n=!1;for(const r in o)e-o[r]>t&&(delete o[r],n=!0);n&&localStorage.setItem("dmhsq_monitor_hashes",JSON.stringify(o))}catch(t){}}function u(){try{const t=JSON.parse(localStorage.getItem("dmhsq_monitor_hashes")||"{}"),e=Date.now();for(const o in t){const n=t[o];e-n<36e5&&c.set(o,n)}}catch(t){}}function m(){u(),setInterval((()=>{f()}),6e4)}const g={ip:null,timestamp:0,isPrivate:!0};async function p(){const t=Date.now();if(g.ip&&t-g.timestamp<432e5)return{ip:g.ip,isPrivate:g.isPrivate};try{const e=await Promise.race([d(),y(),w()]);g.ip=e.ip,g.isPrivate=e.isPrivate,g.timestamp=t;try{localStorage.setItem("dmhsq_monitor_ip",JSON.stringify(g))}catch(t){}return e}catch(t){try{const t=localStorage.getItem("dmhsq_monitor_ip");if(t){const e=JSON.parse(t);return{ip:e.ip,isPrivate:e.isPrivate}}}catch(t){}return function(){try{const t=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});t.createDataChannel(""),t.createOffer().then((e=>t.setLocalDescription(e))),t.onicecandidate=e=>{if(!e.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/.exec(e.candidate.candidate);if(o&&o[1]){const e=o[1];g.ip=e,g.isPrivate=I(e),g.timestamp=Date.now(),t.close()}},setTimeout((()=>t.close()),3e3)}catch(t){}return{ip:"0.0.0.0",isPrivate:!0}}()}}async function d(){const t=await fetch("https://api.ipify.org?format=json",{method:"GET",mode:"cors",cache:"no-cache",timeout:3e3});if(!t.ok)throw new Error("ipify服务失败");const e=await t.json();return{ip:e.ip,isPrivate:I(e.ip)}}async function y(){const t=await fetch("https://checkip.amazonaws.com/",{method:"GET",mode:"cors",cache:"no-cache",timeout:3e3});if(!t.ok)throw new Error("Amazon服务失败");const e=(await t.text()).trim();return{ip:e,isPrivate:I(e)}}async function w(){const t=await fetch("https://ipinfo.io/json",{method:"GET",mode:"cors",cache:"no-cache",timeout:3e3});if(!t.ok)throw new Error("ipinfo服务失败");const e=await t.json();return{ip:e.ip,isPrivate:I(e.ip)}}function I(t){if("127.0.0.1"===t||"localhost"===t||"::1"===t)return!0;const e=t.split(".").map((t=>parseInt(t,10)));return 10===e[0]||(172===e[0]&&e[1]>=16&&e[1]<=31||192===e[0]&&168===e[1])}const S=new Map;async function _(t,e=i.IPAPI){if(!t||"0.0.0.0"===t||I(t))return{country:"Local",region:"Local",city:"Local",isp:"Local",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone};const o=S.get(t);if(o&&Date.now()-o.timestamp<864e5)return o.data;try{let o;switch(e){case i.IPAPI:o=await async function(t){const e=await fetch(`https://ip-api.com/json/${t}?fields=country,regionName,city,isp,timezone`,{method:"GET",mode:"cors",cache:"no-cache",timeout:3e3});if(!e.ok)throw new Error("ip-api.com服务失败");const o=await e.json();return{country:o.country,region:o.regionName,city:o.city,isp:o.isp,timezone:o.timezone}}(t);break;case i.IPINFO:o=await async function(t){const e=await fetch(`https://ipinfo.io/${t}/json`,{method:"GET",mode:"cors",cache:"no-cache",timeout:3e3});if(!e.ok)throw new Error("ipinfo.io服务失败");const o=await e.json();return{country:o.country,region:o.region,city:o.city,isp:o.org,timezone:o.timezone}}(t);break;default:throw new Error(`Unsupported provider: ${e}`)}S.set(t,{data:o,timestamp:Date.now()});try{const e=JSON.parse(localStorage.getItem("dmhsq_monitor_geo_cache")||"{}");e[t]={data:o,timestamp:Date.now()},localStorage.setItem("dmhsq_monitor_geo_cache",JSON.stringify(e))}catch(t){}return o}catch(e){try{const e=JSON.parse(localStorage.getItem("dmhsq_monitor_geo_cache")||"{}");if(e[t]&&Date.now()-e[t].timestamp<6048e5)return e[t].data}catch(t){}return{}}}function v(t,e){const o=function(t,e){const o=t.length,n=e.length,r=Array(o+1).fill(0).map((()=>Array(n+1).fill(0)));for(let t=0;t<=o;t++)r[t][0]=t;for(let t=0;t<=n;t++)r[0][t]=t;for(let i=1;i<=o;i++)for(let o=1;o<=n;o++){const n=t[i-1]===e[o-1]?0:1;r[i][o]=Math.min(r[i-1][o]+1,r[i][o-1]+1,r[i-1][o-1]+n)}return r[o][n]}(t,e),n=Math.max(t.length,e.length);return 0===n?1:1-o/n}function P(e,o,n=.85){if(e.type!==t.ERROR||o.type!==t.ERROR)return!1;if(e.data.errorType!==o.data.errorType)return!1;return v(e.data.message||"",o.data.message||"")>=n}function E(e,o=.85){if(e.length<=1)return e;const n=e.filter((e=>e.type===t.ERROR)),r=e.filter((e=>e.type!==t.ERROR)),i=[];for(const t of n){let e=!1;for(const n of i){if(P(n[0],t,o)){n.push(t),e=!0;break}}e||i.push([t])}return[...i.map((t=>{const e={...t[0]};return t.length>1&&(e.data={...e.data,occurrences:t.length,firstOccurrence:t[0].timestamp,lastOccurrence:t[t.length-1].timestamp}),e})),...r]}class ${constructor(){this._cleanupEventHashes=f,this.configManager=new s,m(),setInterval((()=>{f()}),36e5)}init(t){this.configManager.init(t),console.log(`[${e}] 初始化完成,版本: ${o}`)}async process(t,o){if(this.configManager.isDeduplicateEnabled()&&h(t,this.configManager.getDeduplicateWindow()))return console.log(`[${e}] 检测到重复事件,已过滤: ${t.type} - ${t.name}`),null;const n=this.configManager.getCustomProcessors();let r={...t};for(const t of n)try{const n=t(r,o);if(!n)return console.log(`[${e}] 事件被自定义处理器过滤: ${r.type} - ${r.name}`),null;r=n}catch(t){console.error(`[${e}] 自定义处理器执行失败:`,t)}return r=await this.enrichEvent(r,o),r}async batchProcess(t,o){const n=t.length;let r=[],i=0;for(const e of t){const t=await this.process(e,o);t?r.push(t):i++}if(this.configManager.shouldMergeSimilarErrors()){const t=r.length;r=E(r);const o=t-r.length;console.log(`[${e}] 合并了 ${o} 个相似错误`)}return console.log(`[${e}] 批量处理完成: 原始=${n}, 处理后=${r.length}, 去重=${i}`),r}getConfig(){return this.configManager.getConfig()}updateConfig(t){this.configManager.updateConfig(t)}cleanupCache(t){f(t)}async enrichEvent(t,n){var r;const i={...t},a={};if(this.configManager.shouldCollectUserIp())try{const t=await p();if(a.userIp=t.ip,a.isPrivateIp=t.isPrivate,this.configManager.shouldCollectGeoInfo()&&!t.isPrivate){const e=await _(t.ip);a.geo=e}}catch(t){console.error(`[${e}] 获取IP信息失败:`,t)}return"undefined"!=typeof navigator&&(a.browser={userAgent:navigator.userAgent,language:navigator.language,platform:navigator.platform}),i.data={...i.data,metadata:{...null===(r=i.data)||void 0===r?void 0:r.metadata,...a,processor:{name:e,version:o,processedAt:(new Date).toISOString()}}},i}}export{n as DEFAULT_DEDUPLICATE_WINDOW,r as DEFAULT_ERROR_SIMILARITY_THRESHOLD,i as GeoProvider,e as PROCESSOR_NAME,o as PROCESSOR_VERSION,a as ProcessStatus,$ as Processor,P as areErrorsSimilar,v as calculateErrorSimilarity,f as cleanupEventHashes,l as generateEventHash,_ as getGeoInfo,p as getUserIp,E as groupSimilarErrors,m as initDeduplication,h as isDuplicateEvent,I as isPrivateIp,u as loadStoredHashes}; //# sourceMappingURL=index.esm.js.map