reporting-lib 0.4.4 → 0.4.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/api/fetch.js"],"names":[],"mappings":"AA0EA,sCAEC"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/api/fetch.js"],"names":[],"mappings":"AAuFA,sCAEC"}
package/dist/api/fetch.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { lazyReportCache } from '../report/index.js';
2
- import { isValidOssVideoUrl, getRequestBodySize } from '../util/tool.js';
2
+ import { isValidOssVideoUrl, getRequestBodySize, normalizeMaterialResourceUrl } from '../util/tool.js';
3
3
  const originalFetch = window.fetch;
4
4
  function overWriteFetch() {
5
5
  window.fetch = function newFetch(url, config) {
6
6
  const startTime = Date.now();
7
7
  let request_url = url;
8
8
  const reportData = {
9
- request_url,
9
+ request_url: normalizeMaterialResourceUrl(request_url),
10
10
  method: config?.method || 'GET',
11
11
  // sub_type: 'fetch',
12
12
  };
@@ -20,44 +20,66 @@ function overWriteFetch() {
20
20
  }
21
21
  return originalFetch(url, config)
22
22
  .then(res => {
23
- const endTime = Date.now();
24
- if (isValidOssVideoUrl(request_url)) {
23
+ // 把上报逻辑整体包一层 try/catch,避免内部任何异常冒泡到业务的 .then/.catch
24
+ try {
25
+ const endTime = Date.now();
25
26
  reportData.duration = (endTime - startTime);
26
- }
27
- reportData.status = res.status;
28
- const clonedRes = res.clone();
29
- if (fiterUrl(url)) {
30
- if (!clonedRes.ok) {
31
- reportData.code = reportData.status;
32
- lazyReportCache('api', reportData);
33
- }
34
- else {
35
- clonedRes.json().then(data => {
36
- reportData.code = data.code;
27
+ reportData.status = res.status;
28
+ const clonedRes = res.clone();
29
+ if (fiterUrl(url)) {
30
+ if (!clonedRes.ok) {
31
+ reportData.code = reportData.status;
37
32
  lazyReportCache('api', reportData);
38
- });
33
+ }
34
+ else {
35
+ clonedRes.json().then(data => {
36
+ reportData.code = data && typeof data === 'object' ? data.code : undefined;
37
+ lazyReportCache('api', reportData);
38
+ }).catch(() => {
39
+ // 响应非 JSON 时静默忽略,仅上报基础信息
40
+ lazyReportCache('api', reportData);
41
+ });
42
+ }
39
43
  }
40
44
  }
45
+ catch (e) {
46
+ // 上报失败不能影响业务
47
+ }
41
48
  return res;
42
49
  })
43
50
  .catch(err => {
44
- const endTime = Date.now();
45
- if (isValidOssVideoUrl(request_url)) {
51
+ try {
52
+ const endTime = Date.now();
46
53
  reportData.duration = (endTime - startTime);
54
+ reportData.status = 0;
55
+ reportData.code = reportData.status;
56
+ lazyReportCache('api', reportData);
57
+ }
58
+ catch (e) {
59
+ // 上报失败不能影响业务
47
60
  }
48
- reportData.status = 0;
49
- reportData.code = reportData.status;
50
- lazyReportCache('api', reportData);
51
61
  return err;
52
62
  });
53
63
  };
54
64
  }
55
65
  function fiterUrl(url) {
56
- let bool = true;
57
- if (url.indexOf('.js.map') !== -1 || url.indexOf('.log.aliyuncs.com') !== -1) {
58
- bool = false;
66
+ // 入参可能是 string / URL / Request,统一转成 string 再判断,避免 indexOf 报错
67
+ let str = '';
68
+ try {
69
+ if (typeof url === 'string')
70
+ str = url;
71
+ else if (url && typeof url.url === 'string')
72
+ str = url.url; // Request 对象
73
+ else
74
+ str = String(url);
75
+ }
76
+ catch (e) {
77
+ return true;
78
+ }
79
+ if (str.indexOf('.js.map') !== -1 || str.indexOf('.log.aliyuncs.com') !== -1) {
80
+ return false;
59
81
  }
60
- return bool;
82
+ return true;
61
83
  }
62
84
  export default function fetch() {
63
85
  overWriteFetch();
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/api/fetch.js"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAC,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,kBAAkB,EAAC,kBAAkB,EAAC,MAAM,iBAAiB,CAAC;AAEt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,GAAG,KAAK,QAAQ;YAAE,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,aAAa;;YACpE,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QAC7E,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,OAAO,UAAU,KAAK;IAC3B,cAAc,EAAE,CAAC;AACnB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"xhr.d.ts","sourceRoot":"","sources":["../../src/api/xhr.js"],"names":[],"mappings":"AAgEA,oCAEC"}
1
+ {"version":3,"file":"xhr.d.ts","sourceRoot":"","sources":["../../src/api/xhr.js"],"names":[],"mappings":"AA8EA,oCAEC"}
package/dist/api/xhr.js CHANGED
@@ -1,51 +1,77 @@
1
1
  import { lazyReportCache } from '../report/index.js';
2
- import { isValidOssVideoUrl, getRequestBodySize } from '../util/tool.js';
2
+ import { isValidOssVideoUrl, getRequestBodySize, normalizeMaterialResourceUrl } from '../util/tool.js';
3
3
  const originalPrototype = XMLHttpRequest.prototype;
4
4
  const originalOpen = originalPrototype.open;
5
5
  const originalSend = originalPrototype.send;
6
6
  function overWriteOpenAndSend() {
7
7
  originalPrototype.open = function newOpen(...args) {
8
- this.url = args[1];
9
- this.method = args[0];
8
+ try {
9
+ this.url = args[1];
10
+ this.method = args[0];
11
+ }
12
+ catch (e) {
13
+ // ignore
14
+ }
10
15
  originalOpen.apply(this, args);
11
16
  };
12
17
  originalPrototype.send = function newSend(...args) {
13
- this.startTime = Date.now();
14
- const body = args[0];
15
- this.requestSize = getRequestBodySize(body);
18
+ // 注意:本段所有埋点逻辑都要保证不抛错,否则会让 originalSend 不被执行、请求发不出去
19
+ try {
20
+ this.startTime = Date.now();
21
+ const body = args[0];
22
+ this.requestSize = getRequestBodySize(body);
23
+ }
24
+ catch (e) {
25
+ // ignore
26
+ }
16
27
  const onLoadEnd = () => {
17
- this.endTime = Date.now();
18
- this.duration = this.endTime - this.startTime;
19
- const { status, duration, startTime, endTime, method, response, requestSize } = this;
20
- let { url } = this;
21
- let code = status;
22
- let request_url = url;
28
+ // 整个回调包一层兜底,避免任何异常污染 console / 触发 window.onerror
23
29
  try {
24
- code = JSON.parse(response).code;
30
+ this.endTime = Date.now();
31
+ this.duration = this.endTime - this.startTime;
32
+ const { status, duration, startTime, endTime, method, response, requestSize } = this;
33
+ let { url } = this;
34
+ let code = status;
35
+ let request_url = url;
36
+ try {
37
+ const parsed = JSON.parse(response);
38
+ code = parsed && typeof parsed === 'object' ? parsed.code : status;
39
+ }
40
+ catch {
41
+ }
42
+ let reportData = {
43
+ status,
44
+ request_url: normalizeMaterialResourceUrl(request_url),
45
+ method: method || 'GET',
46
+ code,
47
+ duration,
48
+ // sub_type: 'xhr',
49
+ };
50
+ if (isValidOssVideoUrl(request_url)) {
51
+ reportData.request_url = `https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video`;
52
+ try {
53
+ reportData.request_size = parseInt(requestSize / 1000);
54
+ }
55
+ catch (error) {
56
+ }
57
+ }
58
+ lazyReportCache('api', reportData);
25
59
  }
26
- catch {
60
+ catch (e) {
61
+ // 上报失败不能影响业务
27
62
  }
28
- let reportData = {
29
- status,
30
- request_url,
31
- method: method || 'GET',
32
- code,
33
- // sub_type: 'xhr',
34
- };
35
- if (isValidOssVideoUrl(request_url)) {
36
- reportData.request_url = `https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video`;
63
+ finally {
37
64
  try {
38
- reportData.request_size = parseInt(requestSize / 1000);
39
- reportData.duration = duration;
40
- }
41
- catch (error) {
65
+ this.removeEventListener('loadend', onLoadEnd, true);
42
66
  }
67
+ catch (e) { }
43
68
  }
44
- lazyReportCache('api', reportData);
45
- this.removeEventListener('loadend', onLoadEnd, true);
46
69
  };
47
70
  //当请求结束时触发,无论请求成功 (load) 还是失败 (abort 或 error)
48
- this.addEventListener('loadend', onLoadEnd, true);
71
+ try {
72
+ this.addEventListener('loadend', onLoadEnd, true);
73
+ }
74
+ catch (e) { }
49
75
  originalSend.apply(this, args);
50
76
  };
51
77
  }
@@ -1 +1 @@
1
- {"version":3,"file":"xhr.js","sourceRoot":"","sources":["../../src/api/xhr.js"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAC,kBAAkB,EAAC,kBAAkB,EAAC,MAAM,iBAAiB,CAAC;AAEtE,MAAM,iBAAiB,GAAG,cAAc,CAAC,SAAS,CAAC;AACnD,MAAM,YAAY,GAAG,iBAAiB,CAAC,IAAI,CAAC;AAC5C,MAAM,YAAY,GAAG,iBAAiB,CAAC,IAAI,CAAC;AAE5C,SAAS,oBAAoB;IAC3B,iBAAiB,CAAC,IAAI,GAAG,SAAS,OAAO,CAAC,GAAG,IAAI;QAC/C,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACtB,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC,CAAA;IACD,iBAAiB,CAAC,IAAI,GAAG,SAAS,OAAO,CAAC,GAAG,IAAI;QAC/C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAE5B,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAE5C,MAAM,SAAS,GAAG,GAAG,EAAE;YACrB,IAAI,CAAC,OAAO,GAA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S,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;gBAAC,CAAC;gBAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;YAC5E,CAAC;QACH,CAAC,CAAA;QAED,6CAA6C;QAC7C,IAAI,CAAC;YAAC,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QAAC,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;QACvE,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC,CAAA;AAGH,CAAC;AAED,MAAM,CAAC,OAAO,UAAU,GAAG;IACzB,oBAAoB,EAAE,CAAC;AACzB,CAAC"}
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var j={source:"mbp",userId:"",reportUrl:"http://localhost:3001/report/actions",trackerAll:false,slsProject:"",slsEndpoint:"",slsLogstore:"",history:null},E="",f=j;function he(e){for(let t in j)e[t]&&(j[t]=e[t]);e.version&&(E=e.version);}var D=new Map,O=new Map;function ge(){return D}function Te(e,t){D.get(e)?D.get(e).push(t):D.set(e,[t]);}function ve(){D.clear();}function ye(){return O}function we(e,t){O.get(e)?O.get(e).push(t):O.set(e,[t]);}function Se(){O.clear();}function Ze(e,t,r=false){if(f.reportUrl===null){console.error("\u8BF7\u5148\u914D\u7F6E\u4E0A\u62A5\u5730\u5740");return}let n=JSON.stringify({user_id:Number(f.userId)||0,source:f.source,type:e,url:window.location.pathname,data:t});if(r){V(f.reportUrl,n);return}window.requestIdleCallback?window.requestIdleCallback(()=>{V(f.reportUrl,n);},{timeout:3e3}):setTimeout(()=>{V(f.reportUrl,n);});}var Pe=null;function p(e,t,r=3e3){Te(e,t),clearTimeout(Pe),Pe=setTimeout(()=>{let n=ge();if(n.size){for(let[o,i]of n)Ze(o,i);ve();}},r);}function V(e,t){navigator.sendBeacon?navigator.sendBeacon(e,t):et(e,t);}function et(e,t){let r=new XMLHttpRequest;r.open("POST",e,true),r.setRequestHeader("Content-Type","application/json"),r.send(t);}var tt=({samplePoints:e=6,whiteTags:t=["HTML","BODY","IFRAME"],onDetected:r=(o,i)=>{},threshold:n=.9}={})=>{let o=window.innerWidth,i=window.innerHeight,a=[];for(let u=1;u<=e;u++)a.push([o/2,i/(e+1)*u]);let s=0,c=[];a.forEach(([u,h])=>{let g=document.elementFromPoint(u,h),w=g?.tagName||"NULL";c.push({x:u,y:h,tag:w}),(!g||t.includes(w))&&s++;});let l=s/e>=n;r(l,c);},nt=(e,t=300,r=false)=>{let n=null;return function(...o){let i=this;n&&clearTimeout(n),r&&!n&&e.apply(i,o),n=setTimeout(()=>{r||e.apply(i,o),n=null;},t);}},rt=nt(e=>{tt({onDetected:(t,r)=>{e(t),B=null;}});},1e3),B=null,Le=()=>(B||(B=new Promise(e=>{setTimeout(()=>{rt(e);},3e3);})),B),be=()=>{let e=navigator.userAgent,t="Unknown",r="Unknown";return /edg/i.test(e)?(t="Edge",r=e.match(/edg\/([\d\.]+)/i)?.[1]):/opr/i.test(e)?(t="Opera",r=e.match(/opr\/([\d\.]+)/i)?.[1]):/chrome/i.test(e)?(t="Chrome",r=e.match(/chrome\/([\d\.]+)/i)?.[1]):/firefox/i.test(e)?(t="Firefox",r=e.match(/firefox\/([\d\.]+)/i)?.[1]):/safari/i.test(e)&&!/chrome/i.test(e)?(t="Safari",r=e.match(/version\/([\d\.]+)/i)?.[1]):(/msie/i.test(e)||/trident/i.test(e))&&(t="Internet Explorer",r=e.match(/(msie\s|rv:)([\d\.]+)/i)?.[2]),{name:t,version:r}},xe=()=>{let e=navigator.userAgent||navigator.vendor||window.opera;return /windows phone/i.test(e)?"Windows Phone":/win/i.test(e)?"Windows":/android/i.test(e)?"Android":/iPad|iPhone|iPod/.test(e)&&!window.MSStream?"iOS":/Macintosh|MacIntel|MacPPC|Mac68K/.test(e)?"macOS":/Linux/.test(e)?"Linux":"Unknown OS"},x=e=>{try{let t=new URL(e.indexOf("http")===-1?`https:${e}`:e);return /^\/mbp\/\d+\/video\/[^/?#]+\.[^/?#]+$/i.test(t.pathname)}catch{return false}},F=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},N=e=>{if(!e)return 0;try{if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(e instanceof FormData){let t=0;for(let[r,n]of e.entries())t+=new TextEncoder().encode(r).length,typeof n=="string"?t+=new TextEncoder().encode(n).length:n instanceof Blob&&(t+=n.size);return t}}catch{return 0}return 0};var ot={browserInfo:be(),platform:xe()},k=ot;var Ce=k.browserInfor,J={user_agent:Ce?.name+Ce?.version,platform:k.platform},it=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,at=10;function st(e){let t=e.match(it);if(!t)return {};let r=t[2]||"<anonymous>",n=t[1]||"",o=parseInt(t[3],10)||void 0,i=parseInt(t[4],10)||void 0;return {filename:r,functionName:n,lineno:o,colno:i}}function Ie(e){let{stack:t}=e;if(!t)return [];let r=[];for(let n of t.split(`
2
- `).slice(1)){let o=st(n);o.filename&&r.push(o);}return r.slice(0,at)}function X(){window.addEventListener("error",async function(e){let t=e.target;if(t&&(t.src||t.href)){let r={error_type:"resource",...J,msg:F(`\u52A0\u8F7D${t.tagName}\u5931\u8D25\uFF1A${t.src||t.href}`),version:E};p("error",r);}else {let r=Ie(e.error),n=e.message;if(r?.[0]){let{filename:a,functionName:s,lineno:c,colno:l}=r[0];n=`${e.message},${a},line:${c}:${l}`;}let o={error_type:"js",msg:F(n),...J,version:E};p("error",o),await Le()&&p("error",{...o,error_type:"whiteScreen"});}},true),window.addEventListener("unhandledrejection",function(e){let t=e.reason,r=Ie(t),n=t;if(r?.[0]){let{filename:i,functionName:a,lineno:s,colno:c}=r[0];n=`${e?.reason?.message||e?.reason},${i},line:${s}:${c}`;}let o={error_type:"js",msg:F(n),...J,version:E};p("error",o);});}var Be=-1,I=e=>{addEventListener("pageshow",t=>{t.persisted&&(Be=t.timeStamp,e(t));},true);},T=(e,t,r,n)=>{let o,i;return a=>{t.value>=0&&(a||n)&&(i=t.value-(o??0),(i||o===void 0)&&(o=t.value,t.delta=i,t.rating=((s,c)=>s>c[1]?"poor":s>c[0]?"needs-improvement":"good")(t.value,r),e(t)));}},re=e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()));},oe=()=>{let e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},R=()=>oe()?.activationStart??0,v=(e,t=-1)=>{let r=oe(),n="navigate";return Be>=0?n="back-forward-cache":r&&(document.prerendering||R()>0?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},G=new WeakMap;function ie(e,t){return G.get(e)||G.set(e,new t),G.get(e)}var Y=class{t;i=0;o=[];h(t){if(t.hadRecentInput)return;let r=this.o[0],n=this.o.at(-1);this.i&&r&&n&&t.startTime-n.startTime<1e3&&t.startTime-r.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t);}},_=(e,t,r={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let n=new PerformanceObserver(o=>{Promise.resolve().then(()=>{t(o.getEntries());});});return n.observe({type:e,buffered:!0,...r}),n}}catch{}},ae=e=>{let t=false;return ()=>{t||(e(),t=true);}},C=-1,Fe=new Set,Ee=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,Q=e=>{if(document.visibilityState==="hidden"){if(e.type==="visibilitychange")for(let t of Fe)t();isFinite(C)||(C=e.type==="visibilitychange"?e.timeStamp:0,removeEventListener("prerenderingchange",Q,true));}},H=()=>{if(C<0){let e=R();C=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(r=>r.name==="hidden"&&r.startTime>e)[0]?.startTime)??Ee(),addEventListener("visibilitychange",Q,true),addEventListener("prerenderingchange",Q,true),I(()=>{setTimeout(()=>{C=Ee();});});}return {get firstHiddenTime(){return C},onHidden(e){Fe.add(e);}}},$=e=>{document.prerendering?addEventListener("prerenderingchange",()=>e(),true):e();},Me=[1800,3e3],se=(e,t={})=>{$(()=>{let r=H(),n,o=v("FCP"),i=_("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(i.disconnect(),s.startTime<r.firstHiddenTime&&(o.value=Math.max(s.startTime-R(),0),o.entries.push(s),n(true)));});i&&(n=T(e,o,Me,t.reportAllChanges),I(a=>{o=v("FCP"),n=T(e,o,Me,t.reportAllChanges),re(()=>{o.value=performance.now()-a.timeStamp,n(true);});}));});},De=[.1,.25],Ne=(e,t={})=>{let r=H();se(ae(()=>{let n,o=v("CLS",0),i=ie(t,Y),a=c=>{for(let l of c)i.h(l);i.i>o.value&&(o.value=i.i,o.entries=i.o,n());},s=_("layout-shift",a);s&&(n=T(e,o,De,t.reportAllChanges),r.onHidden(()=>{a(s.takeRecords()),n(true);}),I(()=>{i.i=0,o=v("CLS",0),n=T(e,o,De,t.reportAllChanges),re(()=>n());}),setTimeout(n));}));},qe=0,K=1/0,q=0,ct=e=>{for(let t of e)t.interactionId&&(K=Math.min(K,t.interactionId),q=Math.max(q,t.interactionId),qe=q?(q-K)/7+1:0);},Z,Oe=()=>Z?qe:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||Z||(Z=_("event",ct,{type:"event",buffered:true,durationThreshold:0}));},ke=0,ee=class{u=[];l=new Map;m;p;v(){ke=Oe(),this.u.length=0,this.l.clear();}L(){let t=Math.min(this.u.length-1,Math.floor((Oe()-ke)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let r=this.u.at(-1),n=this.l.get(t.interactionId);if(n||this.u.length<10||t.duration>r.P){if(n?t.duration>n.P?(n.entries=[t],n.P=t.duration):t.duration===n.P&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],P:t.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort((o,i)=>i.P-o.P),this.u.length>10){let o=this.u.splice(10);for(let i of o)this.l.delete(i.id);}this.p?.(n);}}},He=e=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?e():(e=ae(e),addEventListener("visibilitychange",e,{once:true,capture:true}),t(()=>{e(),removeEventListener("visibilitychange",e,{capture:true});}));},Re=[200,500],$e=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let r=H();$(()=>{lt();let n,o=v("INP"),i=ie(t,ee),a=c=>{He(()=>{for(let u of c)i.h(u);let l=i.L();l&&l.P!==o.value&&(o.value=l.P,o.entries=l.entries,n());});},s=_("event",a,{durationThreshold:t.durationThreshold??40});n=T(e,o,Re,t.reportAllChanges),s&&(s.observe({type:"first-input",buffered:true}),r.onHidden(()=>{a(s.takeRecords()),n(true);}),I(()=>{i.v(),o=v("INP"),n=T(e,o,Re,t.reportAllChanges);}));});},te=class{m;h(t){this.m?.(t);}},_e=[2500,4e3],ze=(e,t={})=>{$(()=>{let r=H(),n,o=v("LCP"),i=ie(t,te),a=c=>{t.reportAllChanges||(c=c.slice(-1));for(let l of c)i.h(l),l.startTime<r.firstHiddenTime&&(o.value=Math.max(l.startTime-R(),0),o.entries=[l],n());},s=_("largest-contentful-paint",a);if(s){n=T(e,o,_e,t.reportAllChanges);let c=ae(()=>{a(s.takeRecords()),s.disconnect(),n(true);}),l=u=>{u.isTrusted&&(He(c),removeEventListener(u.type,l,{capture:true}));};for(let u of ["keydown","click","visibilitychange"])addEventListener(u,l,{capture:true});I(u=>{o=v("LCP"),n=T(e,o,_e,t.reportAllChanges),re(()=>{o.value=performance.now()-u.timeStamp,n(true);});});}});},Ae=[800,1800],ne=e=>{document.prerendering?$(()=>ne(e)):document.readyState!=="complete"?addEventListener("load",()=>ne(e),true):setTimeout(e);},Ue=(e,t={})=>{let r=v("TTFB"),n=T(e,r,Ae,t.reportAllChanges);ne(()=>{let o=oe();o&&(r.value=Math.max(o.responseStart-R(),0),r.entries=[o],n(true),I(()=>{r=v("TTFB",0),n=T(e,r,Ae,t.reportAllChanges),n(true);}));});};function ce(){Ne(A),$e(A),ze(A),se(A),Ue(A);}function A(e){let t={name:e.name,value:e.value};p("performance",t);}var z=XMLHttpRequest.prototype,ut=z.open,dt=z.send;function mt(){z.open=function(...t){this.url=t[1],this.method=t[0],ut.apply(this,t);},z.send=function(...t){this.startTime=Date.now();let r=t[0];this.requestSize=N(r);let n=()=>{this.endTime=Date.now(),this.duration=this.endTime-this.startTime;let{status:o,duration:i,startTime:a,endTime:s,method:c,response:l,requestSize:u}=this,{url:h}=this,g=o,w=h;try{g=JSON.parse(l).code;}catch{}let P={status:o,request_url:w,method:c||"GET",code:g};if(x(w)){P.request_url="https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video";try{P.request_size=parseInt(u/1e3),P.duration=i;}catch{}}p("api",P),this.removeEventListener("loadend",n,true);};this.addEventListener("loadend",n,true),dt.apply(this,t);};}function le(){mt();}var ft=window.fetch;function pt(){window.fetch=function(t,r){let n=Date.now(),o=t,i={request_url:o,method:r?.method||"GET"};if(x(o)){i.request_url="https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video";try{i.request_size=parseInt(N(r?.body)/1e3);}catch{}}return ft(t,r).then(a=>{let s=Date.now();x(o)&&(i.duration=s-n),i.status=a.status;let c=a.clone();return ht(t)&&(c.ok?c.json().then(l=>{i.code=l.code,p("api",i);}):(i.code=i.status,p("api",i))),a}).catch(a=>{let s=Date.now();return x(o)&&(i.duration=s-n),i.status=0,i.code=i.status,p("api",i),a})};}function ht(e){let t=true;return (e.indexOf(".js.map")!==-1||e.indexOf(".log.aliyuncs.com")!==-1)&&(t=false),t}function ue(){pt();}function de(){le(),ue();}async function We(e,{project:t,endpoint:r,logstore:n}){if(!t||!r||!n)return;let o=Math.floor(Date.now()/1e3),i={__logs__:e.map(u=>({__time__:o,...Object.keys(u).reduce((h,g)=>(h[g]=String(u[g]),h),{})})),__topic__:"default",__source__:"frontend"},a=JSON.stringify(i),s=`https://${t}.${r}/logstores/${n}/track?APIVersion=0.6.0`,c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-log-apiversion":"0.6.0","x-log-bodyrawsize":a.length.toString()},body:a}),l=await c.text();if(!c.ok)throw new Error(`SLS API error: ${c.status} ${c.statusText} - ${l}`);return c}function gt(e,t,r=false){if(f.reportUrl===null){console.error("\u8BF7\u5148\u914D\u7F6E\u4E0A\u62A5\u5730\u5740");return}let n=[{user_id:Number(f.userId)||0,source:f.source,type:e,url:window.location.pathname,data:t}];if(r){me(n);return}window.requestIdleCallback?window.requestIdleCallback(()=>{me(n);},{timeout:3e3}):me(n);}var je=null;function U(e,t,r,n=3e3){if(t=JSON.stringify({...k,...t}),we(e,t),r){Ve(r);return}clearTimeout(je),je=setTimeout(()=>{Ve();},n);}function Ve(e=false){let t=ye();if(t.size){for(let[r,n]of t)gt(r,n,e);Se();}}function me(e){We(e,{project:f.slsProject,endpoint:f.slsEndpoint,logstore:f.slsLogstore}).catch(t=>{console.error("[reporting-lib] SLS\u4E0A\u62A5\u5931\u8D25:",t);});}function Je(e,t={}){let{minDuration:r=1e3,debounceMs:n=300}=t,o=false,i=null,a=Date.now(),s=(()=>{try{return window.location?.pathname||"/"}catch{return "/"}})(),c,l=false,u=(d,m,S)=>{o||(i&&clearTimeout(i),i=setTimeout(()=>{if(!o&&m>=r)try{e(m,d,S),o=!0;}catch(b){console.error("[trackPageStayTime] onLeave callback error:",b);}},n));},h=()=>{if(document.visibilityState==="hidden"){let d=Date.now(),m=d-a;u("visibilitychange-hidden",m,{startTime:a,endTime:d,pagePath:s,pageTag:c});}else if(document.visibilityState==="visible"){a=Date.now();try{s=window.location?.pathname||s;}catch{}o=false;}};document.addEventListener("visibilitychange",h);let g=d=>{let m=Date.now(),S=m-a,b={startTime:a,endTime:m,pagePath:s,pageTag:c};d.persisted?u("pagehide-bfcache",S,b):u("pagehide",S,b);};window.addEventListener("pagehide",g);let w=()=>{if(!o){let d=Date.now(),m=d-a,S={startTime:a,endTime:d,pagePath:s,pageTag:c};if(m>=r)try{e(m,"beforeunload",S),o=!0;}catch(b){console.error("[trackPageStayTime] onLeave callback error:",b);}}};window.addEventListener("beforeunload",w);let P=()=>{let d=Date.now(),m=d-a;u("popstate",m,{startTime:a,endTime:d,pagePath:s,pageTag:c});};window.addEventListener("popstate",P);let W=()=>{a=Date.now();try{s=window.location?.pathname||s;}catch{}o=false,i&&(clearTimeout(i),i=null);},fe=(d="manual")=>{let m=Date.now(),S=m-a;u(d,S,{startTime:a,endTime:m,pagePath:s,pageTag:c}),d==="route-change"&&setTimeout(()=>{W();},n+50);},pe=d=>{c=d||void 0,d&&(l=true);};return {manualLeave:fe,reset:W,stop:()=>{i&&(clearTimeout(i),i=null),document.removeEventListener("visibilitychange",h),window.removeEventListener("pagehide",g),window.removeEventListener("beforeunload",w),window.removeEventListener("popstate",P);},getCurrentDuration:()=>{let d=Date.now();return document.visibilityState==="visible"?d-a:0},setPageTag:pe,switchPageTag:(d,m="page-tag-change")=>{c&&c!==d?(o=false,fe(m),a=Date.now()):l||(a=Date.now(),o=false),pe(d);}}}var Tt=e=>{try{if(e)return e||"/";let{pathname:t="/"}=window.location||{};return t||"/"}catch{return "/"}},Xe=(e,t,r,n={})=>{let{startTime:o,endTime:i,pagePath:a,pageTag:s}=r,c=Tt(a),l=s?`${c}#${s}`:c,{formatPageName:u}=n;return {pageName:typeof u=="function"?u(l,{duration:e,reason:t,...r}):l,duration:e,startTime:o,endTime:i}};var y=null,L=null;function vt(e={},t,r){let{enabled:n,minDuration:o,debounceMs:i,onLeave:a}=e;n?(y&&(y.stop(),y=null),y=Je(a||r||((c,l,u)=>{}),{minDuration:o,debounceMs:i}),t&&t.listen&&(L&&(L(),L=null),L=t.listen(({location:c,action:l})=>{y&&(l==="PUSH"||l==="REPLACE")&&y.manualLeave("route-change");}))):y&&(y.stop(),y=null,L&&(L(),L=null));}function Ge(e,t){y?.switchPageTag(e,t);}function Ke(e,t){if(!e)return;vt(e,t,(n,o,i)=>{let a=Xe(n,o,i||{startTime:0,endTime:0},{formatPageName:e?.formatPageName});U("pd",a);});}function Ye(e,t){let r=t||f.history;return !r||!r.listen?(console.warn("[reporting-lib] No history instance available. Please provide history in init() or pass it as parameter."),()=>{}):r.listen(e)}var Qe=false,yt={init(e={}){he(e),Ke(e.trackPageStayTime,e.history),Qe||(X(),ce(),de(),Qe=true);},reportToSLS(e,t={},r={}){let{immediate:n=false,timeout:o=3e3}=r;U(e,t,n,o);},switchPageTag(e,t="page-tag-change"){Ge(e,t);},listenRouteChange(e,t){return Ye(e,t)}},Cn=yt;
3
- module.exports=Cn;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var j={source:"mbp",userId:"",reportUrl:"http://localhost:3001/report/actions",trackerAll:false,slsProject:"",slsEndpoint:"",slsLogstore:"",history:null},I="",f=j;function ge(e){for(let t in j)e[t]&&(j[t]=e[t]);e.version&&(I=e.version);}var M=new Map,D=new Map;function Te(){return M}function ye(e,t){M.get(e)?M.get(e).push(t):M.set(e,[t]);}function ve(){M.clear();}function we(){return D}function Se(e,t){D.get(e)?D.get(e).push(t):D.set(e,[t]);}function Pe(){D.clear();}function et(e,t,r=false){if(f.reportUrl===null){console.error("\u8BF7\u5148\u914D\u7F6E\u4E0A\u62A5\u5730\u5740");return}let n=JSON.stringify({user_id:Number(f.userId)||0,source:f.source,type:e,url:window.location.pathname,data:t});if(r){V(f.reportUrl,n);return}window.requestIdleCallback?window.requestIdleCallback(()=>{V(f.reportUrl,n);},{timeout:3e3}):setTimeout(()=>{V(f.reportUrl,n);});}var Le=null;function p(e,t,r=3e3){ye(e,t),clearTimeout(Le),Le=setTimeout(()=>{let n=Te();if(n.size){for(let[o,i]of n)et(o,i);ve();}},r);}function V(e,t){navigator.sendBeacon?navigator.sendBeacon(e,t):tt(e,t);}function tt(e,t){let r=new XMLHttpRequest;r.open("POST",e,true),r.setRequestHeader("Content-Type","application/json"),r.send(t);}var nt=({samplePoints:e=6,whiteTags:t=["HTML","BODY","IFRAME"],onDetected:r=(o,i)=>{},threshold:n=.9}={})=>{let o=window.innerWidth,i=window.innerHeight,a=[];for(let u=1;u<=e;u++)a.push([o/2,i/(e+1)*u]);let s=0,c=[];a.forEach(([u,h])=>{let g=document.elementFromPoint(u,h),w=g?.tagName||"NULL";c.push({x:u,y:h,tag:w}),(!g||t.includes(w))&&s++;});let l=s/e>=n;r(l,c);},rt=(e,t=300,r=false)=>{let n=null;return function(...o){let i=this;n&&clearTimeout(n),r&&!n&&e.apply(i,o),n=setTimeout(()=>{r||e.apply(i,o),n=null;},t);}},ot=rt(e=>{nt({onDetected:(t,r)=>{e(t),$=null;}});},1e3),$=null,be=()=>($||($=new Promise(e=>{setTimeout(()=>{ot(e);},3e3);})),$),xe=()=>{let e=navigator.userAgent,t="Unknown",r="Unknown";return /edg/i.test(e)?(t="Edge",r=e.match(/edg\/([\d\.]+)/i)?.[1]):/opr/i.test(e)?(t="Opera",r=e.match(/opr\/([\d\.]+)/i)?.[1]):/chrome/i.test(e)?(t="Chrome",r=e.match(/chrome\/([\d\.]+)/i)?.[1]):/firefox/i.test(e)?(t="Firefox",r=e.match(/firefox\/([\d\.]+)/i)?.[1]):/safari/i.test(e)&&!/chrome/i.test(e)?(t="Safari",r=e.match(/version\/([\d\.]+)/i)?.[1]):(/msie/i.test(e)||/trident/i.test(e))&&(t="Internet Explorer",r=e.match(/(msie\s|rv:)([\d\.]+)/i)?.[2]),{name:t,version:r}},Ce=()=>{let e=navigator.userAgent||navigator.vendor||window.opera;return /windows phone/i.test(e)?"Windows Phone":/win/i.test(e)?"Windows":/android/i.test(e)?"Android":/iPad|iPhone|iPod/.test(e)&&!window.MSStream?"iOS":/Macintosh|MacIntel|MacPPC|Mac68K/.test(e)?"macOS":/Linux/.test(e)?"Linux":"Unknown OS"},A=e=>{try{let t=String(e),r=t.match(/^(https?:\/\/[^/]+)\/material_resource\/([^/?#]+)\/\d+\/[^/?#]+(?:[/?#].*)?$/i);if(r)return `${r[1]}/material_resource/${r[2]}`;let n=t.match(/^(https?:\/\/[^/]+)\/mbp\/\d+\/([^/?#]+)\/[^/?#]+(?:[/?#].*)?$/i);return n?`${n[1]}/mbp/${n[2]}`:e}catch{return e}},B=e=>{try{let t=new URL(e.indexOf("http")===-1?`https:${e}`:e);return /^\/mbp\/\d+\/video\/[^/?#]+\.[^/?#]+$/i.test(t.pathname)}catch{return false}},F=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},N=e=>{if(!e)return 0;try{if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(e instanceof FormData){let t=0;for(let[r,n]of e.entries())t+=new TextEncoder().encode(r).length,typeof n=="string"?t+=new TextEncoder().encode(n).length:n instanceof Blob&&(t+=n.size);return t}}catch{return 0}return 0};var it={browserInfo:xe(),platform:Ce()},R=it;var Ie=R.browserInfor,J={user_agent:Ie?.name+Ie?.version,platform:R.platform},at=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,st=10;function ct(e){let t=e.match(at);if(!t)return {};let r=t[2]||"<anonymous>",n=t[1]||"",o=parseInt(t[3],10)||void 0,i=parseInt(t[4],10)||void 0;return {filename:r,functionName:n,lineno:o,colno:i}}function Ee(e){let{stack:t}=e;if(!t)return [];let r=[];for(let n of t.split(`
2
+ `).slice(1)){let o=ct(n);o.filename&&r.push(o);}return r.slice(0,st)}function X(){window.addEventListener("error",async function(e){let t=e.target;if(t&&(t.src||t.href)){let r={error_type:"resource",...J,msg:F(`\u52A0\u8F7D${t.tagName}\u5931\u8D25\uFF1A${t.src||t.href}`),version:I};p("error",r);}else {let r=Ee(e.error),n=e.message;if(r?.[0]){let{filename:a,functionName:s,lineno:c,colno:l}=r[0];n=`${e.message},${a},line:${c}:${l}`;}let o={error_type:"js",msg:F(n),...J,version:I};p("error",o),await be()&&p("error",{...o,error_type:"whiteScreen"});}},true),window.addEventListener("unhandledrejection",function(e){let t=e.reason,r=Ee(t),n=t;if(r?.[0]){let{filename:i,functionName:a,lineno:s,colno:c}=r[0];n=`${e?.reason?.message||e?.reason},${i},line:${s}:${c}`;}let o={error_type:"js",msg:F(n),...J,version:I};p("error",o);});}var Be=-1,C=e=>{addEventListener("pageshow",t=>{t.persisted&&(Be=t.timeStamp,e(t));},true);},T=(e,t,r,n)=>{let o,i;return a=>{t.value>=0&&(a||n)&&(i=t.value-(o??0),(i||o===void 0)&&(o=t.value,t.delta=i,t.rating=((s,c)=>s>c[1]?"poor":s>c[0]?"needs-improvement":"good")(t.value,r),e(t)));}},re=e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()));},oe=()=>{let e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},O=()=>oe()?.activationStart??0,y=(e,t=-1)=>{let r=oe(),n="navigate";return Be>=0?n="back-forward-cache":r&&(document.prerendering||O()>0?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},G=new WeakMap;function ie(e,t){return G.get(e)||G.set(e,new t),G.get(e)}var Y=class{t;i=0;o=[];h(t){if(t.hadRecentInput)return;let r=this.o[0],n=this.o.at(-1);this.i&&r&&n&&t.startTime-n.startTime<1e3&&t.startTime-r.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t);}},k=(e,t,r={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let n=new PerformanceObserver(o=>{Promise.resolve().then(()=>{t(o.getEntries());});});return n.observe({type:e,buffered:!0,...r}),n}}catch{}},ae=e=>{let t=false;return ()=>{t||(e(),t=true);}},x=-1,Fe=new Set,Me=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,Q=e=>{if(document.visibilityState==="hidden"){if(e.type==="visibilitychange")for(let t of Fe)t();isFinite(x)||(x=e.type==="visibilitychange"?e.timeStamp:0,removeEventListener("prerenderingchange",Q,true));}},z=()=>{if(x<0){let e=O();x=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(r=>r.name==="hidden"&&r.startTime>e)[0]?.startTime)??Me(),addEventListener("visibilitychange",Q,true),addEventListener("prerenderingchange",Q,true),C(()=>{setTimeout(()=>{x=Me();});});}return {get firstHiddenTime(){return x},onHidden(e){Fe.add(e);}}},H=e=>{document.prerendering?addEventListener("prerenderingchange",()=>e(),true):e();},De=[1800,3e3],se=(e,t={})=>{H(()=>{let r=z(),n,o=y("FCP"),i=k("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(i.disconnect(),s.startTime<r.firstHiddenTime&&(o.value=Math.max(s.startTime-O(),0),o.entries.push(s),n(true)));});i&&(n=T(e,o,De,t.reportAllChanges),C(a=>{o=y("FCP"),n=T(e,o,De,t.reportAllChanges),re(()=>{o.value=performance.now()-a.timeStamp,n(true);});}));});},Re=[.1,.25],Ne=(e,t={})=>{let r=z();se(ae(()=>{let n,o=y("CLS",0),i=ie(t,Y),a=c=>{for(let l of c)i.h(l);i.i>o.value&&(o.value=i.i,o.entries=i.o,n());},s=k("layout-shift",a);s&&(n=T(e,o,Re,t.reportAllChanges),r.onHidden(()=>{a(s.takeRecords()),n(true);}),C(()=>{i.i=0,o=y("CLS",0),n=T(e,o,Re,t.reportAllChanges),re(()=>n());}),setTimeout(n));}));},qe=0,K=1/0,q=0,lt=e=>{for(let t of e)t.interactionId&&(K=Math.min(K,t.interactionId),q=Math.max(q,t.interactionId),qe=q?(q-K)/7+1:0);},Z,Oe=()=>Z?qe:performance.interactionCount??0,ut=()=>{"interactionCount"in performance||Z||(Z=k("event",lt,{type:"event",buffered:true,durationThreshold:0}));},ke=0,ee=class{u=[];l=new Map;m;p;v(){ke=Oe(),this.u.length=0,this.l.clear();}L(){let t=Math.min(this.u.length-1,Math.floor((Oe()-ke)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let r=this.u.at(-1),n=this.l.get(t.interactionId);if(n||this.u.length<10||t.duration>r.P){if(n?t.duration>n.P?(n.entries=[t],n.P=t.duration):t.duration===n.P&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],P:t.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort((o,i)=>i.P-o.P),this.u.length>10){let o=this.u.splice(10);for(let i of o)this.l.delete(i.id);}this.p?.(n);}}},ze=e=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?e():(e=ae(e),addEventListener("visibilitychange",e,{once:true,capture:true}),t(()=>{e(),removeEventListener("visibilitychange",e,{capture:true});}));},_e=[200,500],He=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let r=z();H(()=>{ut();let n,o=y("INP"),i=ie(t,ee),a=c=>{ze(()=>{for(let u of c)i.h(u);let l=i.L();l&&l.P!==o.value&&(o.value=l.P,o.entries=l.entries,n());});},s=k("event",a,{durationThreshold:t.durationThreshold??40});n=T(e,o,_e,t.reportAllChanges),s&&(s.observe({type:"first-input",buffered:true}),r.onHidden(()=>{a(s.takeRecords()),n(true);}),C(()=>{i.v(),o=y("INP"),n=T(e,o,_e,t.reportAllChanges);}));});},te=class{m;h(t){this.m?.(t);}},$e=[2500,4e3],Ue=(e,t={})=>{H(()=>{let r=z(),n,o=y("LCP"),i=ie(t,te),a=c=>{t.reportAllChanges||(c=c.slice(-1));for(let l of c)i.h(l),l.startTime<r.firstHiddenTime&&(o.value=Math.max(l.startTime-O(),0),o.entries=[l],n());},s=k("largest-contentful-paint",a);if(s){n=T(e,o,$e,t.reportAllChanges);let c=ae(()=>{a(s.takeRecords()),s.disconnect(),n(true);}),l=u=>{u.isTrusted&&(ze(c),removeEventListener(u.type,l,{capture:true}));};for(let u of ["keydown","click","visibilitychange"])addEventListener(u,l,{capture:true});C(u=>{o=y("LCP"),n=T(e,o,$e,t.reportAllChanges),re(()=>{o.value=performance.now()-u.timeStamp,n(true);});});}});},Ae=[800,1800],ne=e=>{document.prerendering?H(()=>ne(e)):document.readyState!=="complete"?addEventListener("load",()=>ne(e),true):setTimeout(e);},We=(e,t={})=>{let r=y("TTFB"),n=T(e,r,Ae,t.reportAllChanges);ne(()=>{let o=oe();o&&(r.value=Math.max(o.responseStart-O(),0),r.entries=[o],n(true),C(()=>{r=y("TTFB",0),n=T(e,r,Ae,t.reportAllChanges),n(true);}));});};function ce(){Ne(_),He(_),Ue(_),se(_),We(_);}function _(e){let t={name:e.name,value:e.value};p("performance",t);}var U=XMLHttpRequest.prototype,dt=U.open,mt=U.send;function ft(){U.open=function(...t){try{this.url=t[1],this.method=t[0];}catch{}dt.apply(this,t);},U.send=function(...t){try{this.startTime=Date.now();let n=t[0];this.requestSize=N(n);}catch{}let r=()=>{try{this.endTime=Date.now(),this.duration=this.endTime-this.startTime;let{status:n,duration:o,startTime:i,endTime:a,method:s,response:c,requestSize:l}=this,{url:u}=this,h=n,g=u;try{let P=JSON.parse(c);h=P&&typeof P=="object"?P.code:n;}catch{}let w={status:n,request_url:A(g),method:s||"GET",code:h,duration:o};if(B(g)){w.request_url="https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video";try{w.request_size=parseInt(l/1e3);}catch{}}p("api",w);}catch{}finally{try{this.removeEventListener("loadend",r,!0);}catch{}}};try{this.addEventListener("loadend",r,!0);}catch{}mt.apply(this,t);};}function le(){ft();}var pt=window.fetch;function ht(){window.fetch=function(t,r){let n=Date.now(),o=t,i={request_url:A(o),method:r?.method||"GET"};if(B(o)){i.request_url="https://sd-cms-bmp.oss-accelerate.aliyuncs.com:443/mbp/video";try{i.request_size=parseInt(N(r?.body)/1e3);}catch{}}return pt(t,r).then(a=>{try{let s=Date.now();i.duration=s-n,i.status=a.status;let c=a.clone();gt(t)&&(c.ok?c.json().then(l=>{i.code=l&&typeof l=="object"?l.code:void 0,p("api",i);}).catch(()=>{p("api",i);}):(i.code=i.status,p("api",i)));}catch{}return a}).catch(a=>{try{let s=Date.now();i.duration=s-n,i.status=0,i.code=i.status,p("api",i);}catch{}return a})};}function gt(e){let t="";try{typeof e=="string"?t=e:e&&typeof e.url=="string"?t=e.url:t=String(e);}catch{return true}return !(t.indexOf(".js.map")!==-1||t.indexOf(".log.aliyuncs.com")!==-1)}function ue(){ht();}function de(){le(),ue();}async function je(e,{project:t,endpoint:r,logstore:n}){if(!t||!r||!n)return;let o=Math.floor(Date.now()/1e3),i={__logs__:e.map(u=>({__time__:o,...Object.keys(u).reduce((h,g)=>(h[g]=String(u[g]),h),{})})),__topic__:"default",__source__:"frontend"},a=JSON.stringify(i),s=`https://${t}.${r}/logstores/${n}/track?APIVersion=0.6.0`,c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-log-apiversion":"0.6.0","x-log-bodyrawsize":a.length.toString()},body:a}),l=await c.text();if(!c.ok)throw new Error(`SLS API error: ${c.status} ${c.statusText} - ${l}`);return c}function Tt(e,t,r=false){if(f.reportUrl===null){console.error("\u8BF7\u5148\u914D\u7F6E\u4E0A\u62A5\u5730\u5740");return}let n=[{user_id:Number(f.userId)||0,source:f.source,type:e,url:window.location.pathname,data:t}];if(r){me(n);return}window.requestIdleCallback?window.requestIdleCallback(()=>{me(n);},{timeout:3e3}):me(n);}var Ve=null;function W(e,t,r,n=3e3){if(t=JSON.stringify({...R,...t}),Se(e,t),r){Je(r);return}clearTimeout(Ve),Ve=setTimeout(()=>{Je();},n);}function Je(e=false){let t=we();if(t.size){for(let[r,n]of t)Tt(r,n,e);Pe();}}function me(e){je(e,{project:f.slsProject,endpoint:f.slsEndpoint,logstore:f.slsLogstore}).catch(t=>{console.error("[reporting-lib] SLS\u4E0A\u62A5\u5931\u8D25:",t);});}function Xe(e,t={}){let{minDuration:r=1e3,debounceMs:n=300}=t,o=false,i=null,a=Date.now(),s=(()=>{try{return window.location?.pathname||"/"}catch{return "/"}})(),c,l=false,u=(d,m,S)=>{o||(i&&clearTimeout(i),i=setTimeout(()=>{if(!o&&m>=r)try{e(m,d,S),o=!0;}catch(b){console.error("[trackPageStayTime] onLeave callback error:",b);}},n));},h=()=>{if(document.visibilityState==="hidden"){let d=Date.now(),m=d-a;u("visibilitychange-hidden",m,{startTime:a,endTime:d,pagePath:s,pageTag:c});}else if(document.visibilityState==="visible"){a=Date.now();try{s=window.location?.pathname||s;}catch{}o=false;}};document.addEventListener("visibilitychange",h);let g=d=>{let m=Date.now(),S=m-a,b={startTime:a,endTime:m,pagePath:s,pageTag:c};d.persisted?u("pagehide-bfcache",S,b):u("pagehide",S,b);};window.addEventListener("pagehide",g);let w=()=>{if(!o){let d=Date.now(),m=d-a,S={startTime:a,endTime:d,pagePath:s,pageTag:c};if(m>=r)try{e(m,"beforeunload",S),o=!0;}catch(b){console.error("[trackPageStayTime] onLeave callback error:",b);}}};window.addEventListener("beforeunload",w);let P=()=>{let d=Date.now(),m=d-a;u("popstate",m,{startTime:a,endTime:d,pagePath:s,pageTag:c});};window.addEventListener("popstate",P);let fe=()=>{a=Date.now();try{s=window.location?.pathname||s;}catch{}o=false,i&&(clearTimeout(i),i=null);},pe=(d="manual")=>{let m=Date.now(),S=m-a;u(d,S,{startTime:a,endTime:m,pagePath:s,pageTag:c}),d==="route-change"&&setTimeout(()=>{fe();},n+50);},he=d=>{c=d||void 0,d&&(l=true);};return {manualLeave:pe,reset:fe,stop:()=>{i&&(clearTimeout(i),i=null),document.removeEventListener("visibilitychange",h),window.removeEventListener("pagehide",g),window.removeEventListener("beforeunload",w),window.removeEventListener("popstate",P);},getCurrentDuration:()=>{let d=Date.now();return document.visibilityState==="visible"?d-a:0},setPageTag:he,switchPageTag:(d,m="page-tag-change")=>{c&&c!==d?(o=false,pe(m),a=Date.now()):l||(a=Date.now(),o=false),he(d);}}}var yt=e=>{try{if(e)return e||"/";let{pathname:t="/"}=window.location||{};return t||"/"}catch{return "/"}},Ge=(e,t,r,n={})=>{let{startTime:o,endTime:i,pagePath:a,pageTag:s}=r,c=yt(a),l=s?`${c}#${s}`:c,{formatPageName:u}=n;return {pageName:typeof u=="function"?u(l,{duration:e,reason:t,...r}):l,duration:e,startTime:o,endTime:i}};var v=null,L=null;function vt(e={},t,r){let{enabled:n,minDuration:o,debounceMs:i,onLeave:a}=e;n?(v&&(v.stop(),v=null),v=Xe(a||r||((c,l,u)=>{}),{minDuration:o,debounceMs:i}),t&&t.listen&&(L&&(L(),L=null),L=t.listen(({location:c,action:l})=>{v&&(l==="PUSH"||l==="REPLACE")&&v.manualLeave("route-change");}))):v&&(v.stop(),v=null,L&&(L(),L=null));}function Ke(e,t){v?.switchPageTag(e,t);}function Ye(e,t){if(!e)return;vt(e,t,(n,o,i)=>{let a=Ge(n,o,i||{startTime:0,endTime:0},{formatPageName:e?.formatPageName});W("pd",a);});}function Qe(e,t){let r=t||f.history;return !r||!r.listen?(console.warn("[reporting-lib] No history instance available. Please provide history in init() or pass it as parameter."),()=>{}):r.listen(e)}var Ze=false,wt={init(e={}){ge(e),Ye(e.trackPageStayTime,e.history),Ze||(X(),ce(),de(),Ze=true);},reportToSLS(e,t={},r={}){let{immediate:n=false,timeout:o=3e3}=r;W(e,t,n,o);},switchPageTag(e,t="page-tag-change"){Ke(e,t);},listenRouteChange(e,t){return Qe(e,t)}},In=wt;
3
+ module.exports=In;//# sourceMappingURL=index.cjs.map
4
4
  //# sourceMappingURL=index.cjs.map