@tengence/track-sdk-web 1.2.1 → 1.2.2
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/dist/client.d.ts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{status;constructor(e,t){super(t||`[TM]: Auth error ${e}`),this.name="AuthError",this.status=e}}const t=({method:e,url:t,data:r,headers:n={},withCredentials:o=!1,timeoutMs:i})=>new Promise(((a,s)=>{const c=new XMLHttpRequest;c.open(e,t,!0),i&&(c.timeout=i),Object.keys(n).forEach((e=>{c.setRequestHeader(e,n[e])})),c.withCredentials=!!o,c.onreadystatechange=()=>{if(4===c.readyState)if(c.status>=200&&c.status<300)try{const e=JSON.parse(c.responseText);a(e)}catch(e){s(e)}else{const e=new Error(`[TM]: Request failed with status ${c.status}`);e.status=c.status,s(e)}},c.onerror=()=>{s(new Error("[TM]: Network error"))},c.ontimeout=()=>{const e=new Error("[TM]: Request timeout");e.timeout=!0,s(e)},r?c.send(r):c.send()})),r=(e,t,r)=>{if(!r)return fetch(e,t);const n=new AbortController,o=setTimeout((()=>n.abort()),r);return fetch(e,{...t,signal:n.signal}).catch((e=>{if(e&&"AbortError"===e.name){const e=new Error("[TM]: Request timeout");throw e.timeout=!0,e}throw e})).finally((()=>clearTimeout(o)))},n=(n,o,i,a)=>{const s={"Content-Type":"application/json"};i&&(s.Authorization=`Bearer ${i}`);const c=()=>t({method:"POST",url:n,data:JSON.stringify(o),headers:s,withCredentials:!0,timeoutMs:a});return"function"!=typeof fetch?c():r(n,{method:"POST",keepalive:!0,credentials:"include",headers:s,body:JSON.stringify(o)},a).then((t=>{if(401===t.status||403===t.status)throw new e(t.status,`[TM]: Auth error ${t.status}`);if(429===t.status){const e=new Error("[TM]: Request throttled with status 429");e.status=429;const r=t.headers.get("Retry-After");if(r){const t=parseInt(r,10);isNaN(t)||(e.retryAfter=1e3*t)}throw e}if(!t.ok){const e=new Error(`[TM]: Request failed with status ${t.status}`);throw e.status=t.status,e}return t.json()})).catch((t=>{if(t instanceof e)throw t;if(t&&t.status)throw t;return c()}))},o=window.requestIdleCallback||window.requestAnimationFrame||(e=>setTimeout(e,17));function i(e,t=150,r=!1){let n=null;return function(...o){const i=this,a=r&&!n;n&&clearTimeout(n),n=setTimeout((()=>{n=null,r||e.apply(i,o)}),t),a&&e.apply(i,o)}}const a=(e,t=300)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}};function s(e,t=""){if(!e)return t;const r=e.parentElement,{id:n}=e,o=e.tagName.toLowerCase(),i=t?`>${t}`:"";return r&&r!==document.documentElement&&r!==document.body?n?`#${n}${i}`:s(r,`${o}${i}`):`${o}${i}`}const c=()=>{if(window.performance?.navigation)return performance.navigation.type;if(window.performance?.getEntriesByType){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type}return 255},l=e=>{"prerendering"in document&&document.prerendering?(e=>{"prerendering"in document&&document.prerendering?addEventListener("prerenderingchange",(()=>e()),!0):e()})((()=>l(e))):"complete"!==document?.readyState?addEventListener("load",(()=>l(e)),!0):setTimeout(e)};function d(e){return"number"!=typeof e||!isFinite(e)||e<0?null:Math.round(100*e)/100}function u(){const e=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;let t="";for(let r=0;r<16;r++)t+=(e[r]<16?"0":"")+e[r].toString(16);return t}const m=e=>e instanceof ErrorEvent?"Script error."===e.message?"cors":"js":"resource",p=e=>(e=>{let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)>>>0;return t.toString(16).padStart(8,"0")})(e)+(e=>{let t=5381;for(let r=e.length-1;r>=0;r--)t=((t<<5)+t^e.charCodeAt(r))>>>0;return t.toString(16).padStart(8,"0")})(e);const f={view:"#3b82f6",click:"#06b6d4",expose:"#8b5cf6",enter:"#10b981",leave:"#f59e0b",stay:"#84cc16",cart:"#ec4899",buy:"#ef4444",pay:"#dc2626",default:"#6b7280"},h={view:"👁️",click:"👆",expose:"✨",enter:"🚪",leave:"👋",stay:"⏱️",cart:"🛒",buy:"💰",pay:"💳",default:"📊"},g={common:"#3b82f6",behavior:"#10b981",performance:"#f59e0b",error:"#ef4444",custom:"#8b5cf6",default:"#6b7280"},y=(e,t)=>{t.forEach(((t,r)=>{const n=t.event_type||"unknown",o=t.data_type||"auto",i=(e=>f[e]||f.default)(n),a=(e=>g[e]||g.default)(o),s=(e=>h[e]||h.default)(n);let c=t.event_detail;if("string"==typeof c)try{c=JSON.parse(c)}catch(e){}console.groupCollapsed(`%c${s} [TM-${e}] %c${o.toUpperCase()}%c → %c${n.toUpperCase()}%c #${r+1}`,"color: #6b7280; font-weight: bold;",`color: ${a}; font-weight: bold; background: ${a}20; padding: 2px 6px; border-radius: 3px;`,"color: #6b7280;",`color: ${i}; font-weight: bold; background: ${i}20; padding: 2px 6px; border-radius: 3px;`,"color: #6b7280; font-weight: normal;");const l={...t,event_detail:c};console.log("%c"+JSON.stringify(l,null,2),"color: #6b7280; font-family: monospace; font-size: 11px; line-height: 1.5;"),console.groupEnd()})),console.log(`%c✅ [TM] 本次通过 ${e} 上报 ${t.length} 条埋点数据`,"color: #10b981; font-weight: bold; font-size: 12px; padding: 4px 8px; background: #10b98120; border-radius: 4px; border-left: 3px solid #10b981;")};let w;const v="TRACK_MONITOR_DATA",T="MONITOR_REAL_TIME_DATA",_="TRACK_MONITOR_USER",b="tengence_device_id",S="tengence_register_properties",E="TRACK_MONITOR_LOGGER",k="tengence_tracking_enabled",x=2e3,M="tengence_access_token";let A=null,L=null;const C=e=>((e,n,o)=>{const i={"Content-Type":"application/json"},a=()=>t({method:"POST",url:e,data:JSON.stringify(n),headers:i,withCredentials:!0,timeoutMs:o});return"function"!=typeof fetch?a():r(e,{method:"POST",credentials:"include",headers:i,body:JSON.stringify(n)},o).then((e=>{if(!e.ok){const t=new Error(`[TM]: Request failed with status ${e.status}`);throw t.status=e.status,t}return e.json()})).catch((e=>{if(e&&e.status)throw e;return a()}))})(e,{},w?.requestTimeout).then((e=>{const t=e&&e.data,r=t&&t.accessToken,n=t&&t.accessExpAt;if(!r||"number"!=typeof n)throw new Error("[TM]: authUrl 响应缺少 accessToken/accessExpAt");return((e,t)=>{A={token:e,expAt:t};try{localStorage.setItem(M,JSON.stringify({token:e,expAt:t}))}catch(e){}})(r,n),r})),R=e=>{const t=(()=>{if(A)return A;try{const e=localStorage.getItem(M);if(!e)return null;const t=JSON.parse(e);if(t&&"string"==typeof t.token&&t.token&&"number"==typeof t.expAt)return A={token:t.token,expAt:t.expAt},A}catch(e){}return null})();return(r=t)&&r.token.length>0&&r.expAt-6e4>Date.now()?Promise.resolve(t.token):(L||(L=C(e).catch((e=>{throw e})).finally((()=>{L=null}))),L);var r},I={timer:null,promise:null},$={timer:null,promise:null},q=e=>{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length/1024};let N=null;const P=()=>{if(N)return N;try{const e=localStorage.getItem(S),t=e?JSON.parse(e):{};return N=t,t}catch(e){return console.error("[TM]: get register properties fail: ",e),{}}},O=e=>{N=e;try{localStorage.setItem(S,JSON.stringify(e))}catch(e){console.error("[TM]: save register properties fail: ",e)}},U=e=>{if(!e||"object"!=typeof e||Array.isArray(e))return void console.error("[TM]: registerGlobalProperties props must be a plain object");const t={...P(),...e},r=Object.keys(t);if(r.length>50){const e={};return r.slice(0,50).forEach((r=>{e[r]=t[r]})),console.warn("[TM]: register properties exceed max 50 keys, extra keys dropped"),void O(e)}O(t)},B=e=>{const t=document.cookie.match(new RegExp("(?:^|;\\s*)"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):void 0},z=e=>{document.cookie=`${b}=${encodeURIComponent(e)}; Max-Age=63072000; Path=/; Secure; SameSite=Lax`};let D;const F=()=>{if(D)return D;try{let e=localStorage.getItem(b);if(e)return B(b)||z(e),D=e;const t=B(b);if(t){try{localStorage.setItem(b,t)}catch(e){}return D=t}e=u();try{localStorage.setItem(b,e)}catch(e){}return z(e),D=e}catch(e){return void console.error("[TM]: get or create device id fail: ",e)}},j="tengence_session_id",H=()=>{try{const e=sessionStorage.getItem(j);let t=e?JSON.parse(e):null;const r=Date.now();return!t||!t.id||r-t.lastActiveAt>18e5?(t={id:u(),lastActiveAt:r},sessionStorage.setItem(j,JSON.stringify(t))):(t.lastActiveAt=r,sessionStorage.setItem(j,JSON.stringify(t))),t.id}catch(e){return}},J=(e,t)=>{try{const r=new URL(e,location.href);if(!r.searchParams.toString())return e;if(t&&t.length){const e=[];for(const n of t){const t=r.searchParams.get(n);null!==t&&e.push(`${n}=${encodeURIComponent(t)}`)}r.search=e.length?`?${e.join("&")}`:""}else r.search="";return r.toString()}catch(t){return e}},K=(e,t,r)=>{if("string"==typeof e)return t>0&&e.length>t?e.slice(0,t)+"...[truncated]":e;if(Array.isArray(e))return e.map((e=>K(e,t,r)));if(e&&"object"==typeof e){const n={};for(const o of Object.keys(e)){const i=e[o];"string"==typeof i&&/(^|_)url$|(^|_)href$|^referrer$/i.test(o)&&/^https?:\/\//i.test(i)?n[o]=J(i,r):n[o]=K(i,t,r)}return n}return e},W=e=>{const t={page_url:location.href,hostname:window.location.hostname||window.location.host,os:window.navigator.platform,user_id:localStorage.getItem(_)||void 0,user_agent:window.navigator.userAgent,screen_width:window.screen.width,screen_height:window.screen.height,lib_version:"1.2.1",lib_type:"js",event_time:Date.now(),timezone_offset:(new Date).getTimezoneOffset().toString()},r=w?.sanitize;let n;try{n="string"==typeof e.event_detail?e.event_detail:JSON.stringify(r&&(r.maxTextLength>0||r.stripQuery)?K(e.event_detail,r.maxTextLength,r.preserveQueryKeys):e.event_detail)}catch(e){return Y("serialize_failed","事件 event_detail 序列化失败(循环引用/BigInt?),该事件丢弃",{error:e}),void console.warn("[TM]: event_detail 序列化失败,该事件丢弃",e)}return{session_id:e.session_id||(w?.enableAutoSessionId?H():void 0),request_id:e.request_id,event_id:e.event_id||u(),spm:e.spm,data_type:e.data_type||"behavior",event_type:e.event_type,event_detail:n,...t,page_url:r&&r.stripQuery?J(t.page_url,r.preserveQueryKeys):t.page_url,device_id:F(),register_properties:JSON.stringify(P()),platform:e.platform||X}};let X;const Q=()=>{try{return"true"===localStorage.getItem(E)}catch(e){return!1}},G=(e,t,r,n,o)=>void 0===e?t:"number"!=typeof e||Number.isNaN(e)||e<r||e>n?(console.warn(`[TM]: 配置 ${o}=${e} 非法,回退默认值 ${t}`),t):e,V=(e,t)=>{try{w?.onDrop?.(e,t)}catch(e){}},Y=(e,t,r)=>{w?.isLogger&&console.error(`[TM]: ${t}`);try{w?.onError?.({code:e,message:t,context:r})}catch(e){}},Z=()=>{try{const e=localStorage.getItem(k);return null===e||"1"===e}catch(e){return!0}},ee=t=>{const r=t.apiKey;let i;const a=/Android|iPhone|iPad|iPod|Mobile/i.test(window.navigator.userAgent);X=t.platform||(a?"h5":"web"),w={pushUrl:t.pushUrl||"https://api.tengence.com/v1/push/event",authUrl:t.authUrl,realTimeUrl:t.realTimeUrl,cacheNumber:G(t.cacheNumber,100,1,1/0,"cacheNumber"),reportInterval:G(t.reportInterval,5e3,100,1/0,"reportInterval"),realTimeReportInterval:G(t.realTimeReportInterval,200,100,1/0,"realTimeReportInterval"),maxCacheSize:G(t.maxCacheSize,56,1,1/0,"maxCacheSize"),maxRetries:G(t.maxRetries,10,0,1/0,"maxRetries"),isLogger:t.isLogger??Q(),errorTraceRate:G(t.errorTraceRate,.5,0,1,"errorTraceRate"),resourceFlowLimit:G(t.resourceFlowLimit,15,0,200,"resourceFlowLimit"),traceBehavior:t.traceBehavior??!0,tracePerformance:t.tracePerformance??!0,traceError:t.traceError??!0,sanitize:!1===t.sanitize?{stripQuery:!1,maxTextLength:0,preserveQueryKeys:[]}:{stripQuery:t.sanitize?.stripQuery??!1,maxTextLength:G(t.sanitize?.maxTextLength,0,0,1/0,"sanitize.maxTextLength"),preserveQueryKeys:t.sanitize?.preserveQueryKeys||[]},enableAutoSessionId:t.enableAutoSessionId??!1,enableTracking:t.enableTracking??Z(),respectGpc:t.respectGpc??!0,requestTimeout:G(t.requestTimeout,1e4,1e3,6e4,"requestTimeout"),beforeSend:t.beforeSend,onDrop:t.onDrop,onError:t.onError};let{pushUrl:s,authUrl:c,realTimeUrl:l,cacheNumber:d,reportInterval:u,realTimeReportInterval:m,maxCacheSize:p,maxRetries:f}=w;r||c||(console.error("[TM]: 未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"),Y("init_missing_credential","未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"));const h={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},g={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},b=e=>{try{localStorage.setItem(_,e)}catch(e){console.error("[TM]: monitor bind user fail: ",e)}},S=()=>{localStorage.removeItem(_)},L={},C={},N=new Set;let P=null;const O=()=>{null!==P&&(clearTimeout(P),P=null),N.size&&(N.forEach((e=>{try{localStorage.setItem(e,JSON.stringify(L[e]||[]))}catch(t){Y("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),本次数据仅保留内存",{key:e,error:t})}})),N.clear())},B=e=>{if(L[e])return L[e];let t=[];try{t=JSON.parse(localStorage.getItem(e)||"[]")}catch(t){Y("queue_read_failed","读取本地缓存队列失败,按空队列处理",{key:e,error:t})}return L[e]=t,C[e]=t.reduce(((e,t)=>e+q(t)),0),L[e]},z=(e,t)=>{N.delete(e),L[e]=t,C[e]=t.reduce(((e,t)=>e+q(t)),0);try{localStorage.setItem(e,JSON.stringify(t))}catch(t){Y("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),队列清空处理",{key:e,error:t});try{localStorage.setItem(e,"[]")}catch(t){Y("localstorage_unavailable","localStorage 不可用,本次数据仅保留内存",{key:e,error:t})}}},D=e=>{i=e},F=async(t,o,a=!1)=>{const d=t&&l?l:s;let u;try{u=r||i||(c?await R(c):void 0)}catch(e){throw Y("token_fetch_failed","从 authUrl 获取 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:c,error:e}),e}if(!u)throw Y("init_missing_credential","未配置 apiKey/authUrl 且未注入 accessToken,本次数据未上报(保留缓存队列待重试)"),new Error("[TM]: credential missing, skip report");w?.isLogger&&y(t?"RealTimeFetch":"Fetch",o);const m=w?.beforeSend?(()=>{let e;try{e=w.beforeSend(o)}catch(e){Y("before_send_failed","beforeSend 钩子抛错,本次按原始数据发送",{error:e})}return Array.isArray(e)?e:o})():o,p=a?void 0:w?.requestTimeout;return n(d,{data:m},u,p).catch((async t=>{const o=t?.status;if((t instanceof e||401===o||403===o)&&!r&&!i&&c){(()=>{A=null;try{localStorage.removeItem(M)}catch(e){}})();const e=await R(c).catch((()=>{}));if(e)return n(d,{data:m},e,p);Y("token_invalid","上报 401/403 且刷新 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:c})}throw t}))},j=(e,t)=>{const r=new Set(t.filter((e=>!!e)));if(!r.size)return;const n=B(e);if(!n.length)return;const o=n.filter((e=>e.event_id&&!r.has(e.event_id)));o.length!==n.length&&z(e,o)},H=(e,t,r=0)=>{const n=(t?m:u)*Math.pow(2,e)*(.8+.4*Math.random()),o=Math.min(n,6e4);return Math.max(o,r)},J=(e,t)=>{const r=q(t);if(r>=64)return V([t],"item_too_large"),void console.warn("[TM]: 单条事件超过体积上限(64KB),丢弃该条");const n=B(e);if(n.unshift(t),C[e]+=r,n.length>x){const t=n.length-x,r=n.splice(n.length-t,n.length);C[e]=n.reduce(((e,t)=>e+q(t)),0),V(r,"queue_overflow"),console.warn(`[TM]: 队列超过上限(2000条),丢弃最旧 ${t} 条`)}(e=>{N.add(e),null===P&&(P=setTimeout((()=>{P=null,O()}),200))})(e),K(e,C[e]>=p)},K=(e,t=!1,r=!1)=>{if(!w?.enableTracking)return;let n=B(e);if(!n.length)return;const o=(e=>e===T)(e),i=o?$:I,a=(e=>e?g:h)(o);if(a.halveBatch&&n.length>1&&(n=n.slice(0,Math.ceil(n.length/2))),a.retryExhausted)return;if(Date.now()<a.nextRetryAt)return void(null===i.timer&&(i.timer=setTimeout((()=>{i.timer=null,K(e)}),a.nextRetryAt-Date.now())));if(0!==a.retryCount||(n.length>=d||t)){if(null!==i.timer&&(clearTimeout(i.timer),i.timer=null),i.promise)return;i.promise=(async(e,t,r,n,o=!1)=>{const i=[];let a=[],s=0;for(const e of t){const t=1024*q(e);a.length&&s+t>65536&&(i.push(a),a=[],s=0),a.push(e),s+=t}a.length&&i.push(a);for(const t of i){const n=await F(r,t,o),i=n?.data?.accepted_ids,a=n?.data?.rejected_ids;if(Array.isArray(i)){if(j(e,i),Array.isArray(a)&&a.length){const r=new Set(a);j(e,a);const n=t.filter((e=>e.event_id&&r.has(e.event_id)));n.length&&V(n,"server_rejected"),console.warn(`[TM]: 服务端校验拒绝 ${a.length} 条(永久性拒绝),已从队列移除并通知 onDrop`)}}else j(e,t.map((e=>e.event_id))),w?.isLogger&&console.warn("[TM]: 响应缺少 accepted_ids,按整批成功清理")}n.retryCount=0,n.nextRetryAt=0,n.halveBatch=!1})(e,n,o,a,r).catch((e=>{((e,t,r,n,o)=>{t?.timeout&&Y("request_timeout","上报请求超时,数据保留队列按退避重试",{url:r&&l?l:s,timeoutMs:w?.requestTimeout});const i=t?.status;if(413===i)return void(o.length>1?(n.halveBatch=!0,n.retryCount++,n.nextRetryAt=Date.now()+H(n.retryCount,r,0),console.warn(`[TM]: 批次过大(HTTP 413),降容半批重发(本批 ${o.length} 条)`)):(n.retryExhausted=!0,V(o,"rejected_4xx"),console.warn("[TM]: 单条事件仍超限(HTTP 413),数据保留在队列")));if(i&&i>=400&&i<500&&401!==i&&403!==i&&408!==i&&410!==i&&429!==i)return n.retryExhausted=!0,V(o,"rejected_4xx"),void console.warn(`[TM]: 批次提交被服务端拒绝(HTTP ${i}),数据保留在队列并暂停自动重试`);if(n.retryCount++,n.retryCount>f)return n.retryExhausted=!0,V(o,"retries_exhausted"),void console.warn(`[TM]: 重试次数已达上限(${f}),数据保留在队列(不丢弃),待下次会话或手动触发重试`);const a=429===i&&t?.retryAfter||0;n.nextRetryAt=Date.now()+H(n.retryCount,r,a),console.error(`[TM]: send report fail, retryCount: ${n.retryCount}, next retry after ${Math.round((n.nextRetryAt-Date.now())/1e3)}s`)})(0,e,o,a,n)})).finally((()=>{i.timer=null,i.promise=null,K(e)}))}else if(null===i.timer){const t=o?m:u;i.timer=setTimeout((()=>{i.timer=null,K(e,!0)}),t)}},ee=e=>{if(!w?.enableTracking||w?.respectGpc&&function(){const e="undefined"!=typeof navigator?navigator:void 0;return!0===e?.globalPrivacyControl}())return void(w?.isLogger&&console.warn("[TM]: 用户已选择退出采集(enableTracking=false 或 GPC 信号开启),本事件忽略"));if(!e||"object"!=typeof e)return void console.error("[TM]: track data must be an object");const t=!0===e.track_real_time,r=W(e);if(r)try{J(t&&l?T:v,r)}catch(e){Y("enqueue_failed","事件入队失败",{error:e})}},te=(e,t,r)=>{ee("string"==typeof e?{event_type:e,event_detail:t,...r}:e)},re=()=>{K(v,!0),K(T,!0);const e=[I.promise,$.promise].filter((e=>!!e));return Promise.all(e).then((()=>{}))},ne=()=>{w.isLogger=!0;try{localStorage.setItem(E,"true")}catch(e){console.error("[TM]: enable logger fail:",e)}},oe=()=>{w.isLogger=!1;try{localStorage.setItem(E,"false")}catch(e){console.error("[TM]: disable logger fail:",e)}};o((()=>{K(v,!0),K(T,!0)}));const ie=e=>("boolean"==typeof e&&(w.enableTracking=e,(e=>{try{localStorage.setItem(k,e?"1":"0")}catch(e){}})(e),e?w?.isLogger&&console.warn("[TM]: 恢复采集"):(z(v,[]),z(T,[]),w?.isLogger&&console.warn("[TM]: 用户已选择退出采集,已清空未上报队列"))),!0===w?.enableTracking);return window.trackMonitor={track:te,flush:re,bindUser:b,unBindUser:S,enableLogger:ne,disableLogger:oe,setToken:D,registerGlobalProperties:U,enableTracking:ie},{client:{track:te,flush:re,bindUser:b,unBindUser:S,enableLogger:ne,disableLogger:oe,setToken:D,registerGlobalProperties:U,enableTracking:ie},beforeClose:()=>{const e=()=>{O(),K(v,!0,!0),K(T,!0,!0)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&e()})),window.addEventListener("online",e)}}},te=(re=16,function(){const e=new Uint8Array(re);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<re;t++)e[t]=Math.floor(256*Math.random());let t="";for(let r=0;r<re;r++)t+=(e[r]<16?"0":"")+e[r].toString(16);return t})();var re;const ne=e=>{const t=history[e];return function(){const r=t.apply(this,arguments),n=new Event(e);return window.dispatchEvent(n),r}},oe=e=>{window.addEventListener("replaceState",(t=>e(t)),!0),window.addEventListener("pushState",(t=>e(t)),!0)},ie=e=>{window.addEventListener("popstate",(t=>e(t)),!0)},ae=[25,50,75,90],se=e=>{history.pushState=ne("pushState"),history.replaceState=ne("replaceState"),(()=>{let e="";const t=()=>{const t=window.location.href;if(t===e)return;const{host:r,hostname:n,href:o,protocol:i,origin:a,port:s,pathname:l,search:d,hash:u}=window.location,m={host:r,hostname:n,href:o,protocol:i,origin:a,port:s,pathname:l,search:d,hash:u,title:document.title,language:navigator.language.substring(0,2),user_agent:navigator.userAgent,win_screen:`${window.screen.width}x${window.screen.height}`,doc_screen:`${document.documentElement.clientWidth}x${document.documentElement.clientHeight}`,referrer:document.referrer,type:c()};window.trackMonitor.track({data_type:"auto",event_type:"page_view",event_detail:m}),e=t},r=i(t,200);t(),ie((()=>{r()})),oe((()=>{r()})),window.addEventListener("popstate",(()=>{r()}))})(),(()=>{let e=document.referrer,t=window.location.href,r=Date.now(),n=!0;const o=(n=!1)=>{if(window.location.href!==t||n){const n=Date.now()-r;n>200&&window.trackMonitor.track({data_type:"auto",event_type:"page_leave",event_detail:{url:t,referrer:e,duration:n}}),r=Date.now(),e=t,t=window.location.href}},a=i(o);o(),ie((()=>{a()})),oe((()=>{a()})),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?n&&(n=!1,o(!0)):(n=!0,r=Date.now())})),window.addEventListener("beforeunload",(()=>{n&&(n=!1,o(!0))}),!0)})(),(()=>{const e=a((e=>{const t=function(e){if(!e)return;if(["A","INPUT","TEXTAREA","BUTTON"].includes(e.tagName))return e;if(e.hasAttribute("track-click"))return e;return e.closest("a, button, [track-click]")||void 0}(e.target);if(!t)return;const r={element_id:t.id,element_content:t.textContent?.trim().slice(0,200)||null,element_class_name:t.className||null,element_name:t.getAttribute("name")||null,element_type:t.tagName.toLowerCase(),element_path:s(t),scroll_width:document.documentElement.scrollWidth,scroll_height:document.documentElement.scrollHeight,pageX:e.pageX,pageY:e.pageY,ratio:window.devicePixelRatio||1};window.trackMonitor.track({data_type:"auto",event_type:"click",event_detail:r})}));window.addEventListener("click",e,!0)})(),!1!==e?.enableScroll&&(()=>{const e=new Set,t=a((()=>{const r=document.documentElement,n=r.scrollHeight-r.clientHeight;if(n<=0)return;const o=Math.round((window.scrollY||r.scrollTop)/n*100),i=ae.filter((t=>o>=t&&!e.has(t)));i.length&&(i.forEach((t=>{e.add(t),window.trackMonitor.track({data_type:"auto",event_type:"scroll",event_detail:{scroll_depth:t}})})),e.has(90)&&window.removeEventListener("scroll",t))}),300);window.addEventListener("scroll",t,{passive:!0})})()};let ce=null,le=null;const de="track-expose",ue="track-view",me=e=>{try{le=new WeakMap}catch(e){console.error("[TM]: create WeakMap fail: ",e)}const t=(e,t=!1)=>{const n=le?.get(e);if(n&&!t)return;n&&(n.viewTimer&&clearTimeout(n.viewTimer),n.exposeTimer&&clearTimeout(n.exposeTimer));const o=e.dataset.durationView||500,i=e.dataset.durationExpose||500;le?.set(e,{duration_view:o,duration_expose:i,viewTimer:null,exposeTimer:null}),ce?.observe(e),t&&function(e){if(!(e instanceof Element))return!1;if(!function e(t){if(!t)return!0;const r=window.getComputedStyle(t);return"none"!==r.display&&"hidden"!==r.visibility&&0!==parseFloat(r.opacity)&&e(t.parentElement)}(e))return!1;const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}(e)&&r(e)},r=t=>{const r=le?.get(t);if(!r)return;const o=t.dataset.eventDetail,i=t.dataset.traceid??void 0,a=t.dataset.spm,s=t.hasAttribute("track-real-time"),c=t.hasAttribute(ue),l=t.hasAttribute(de);c&&l?r.exposeTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"view_expose",event_detail:o,track_real_time:s}),t.removeAttribute(ue),r.exposeTimer=null}),parseInt(r.duration_expose,10)):(c&&(r.viewTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"view",event_detail:o,track_real_time:s}),t.removeAttribute(ue),l&&r.exposeTimer||n(t),r.viewTimer=null}),parseInt(r.duration_view,10))),l&&(r.exposeTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"expose",event_detail:o,track_real_time:s}),r.exposeTimer=null}),parseInt(r.duration_expose,10))))},n=e=>{const t=le?.get(e);t&&(ce?.unobserve(e),t.viewTimer&&clearTimeout(t.viewTimer),t.exposeTimer&&clearTimeout(t.exposeTimer),le?.delete(e))},o=e=>{e.forEach((e=>{const t=e.target,o=le?.get(t);o&&(o.viewTimer&&(clearTimeout(o.viewTimer),o.viewTimer=null),o.exposeTimer&&(clearTimeout(o.exposeTimer),o.exposeTimer=null),e.isIntersecting&&(r(t),t.hasAttribute(ue)||t.hasAttribute(de)||n(t)))}))};ce=(()=>{let e=null;try{e=new IntersectionObserver(o,{root:null,threshold:.5})}catch(e){console.error("[TM]: create IntersectionObserver fail: ",e)}return e})();new Set([...document.querySelectorAll(`[${de}]`),...document.querySelectorAll(`[${ue}]`)]).forEach((e=>t(e))),new MutationObserver((e=>{e.forEach((e=>{if("attributes"===e.type&&e.target instanceof HTMLElement){const r=e.target,o=e.attributeName,i=["data-event-detail","data-traceid","data-spm","data-duration-view","data-duration-expose"];r.hasAttribute(de)||r.hasAttribute(ue)?i.includes(o)?t(r,!0):o!==de&&o!==ue||t(r,!1):n(r)}else"childList"===e.type&&(e.addedNodes.forEach((e=>{if(e instanceof HTMLElement)if(e.hasAttribute(de)||e.hasAttribute(ue))t(e);else{new Set([...e.querySelectorAll(`[${de}]`),...e.querySelectorAll(`[${ue}]`)]).forEach((e=>t(e)))}})),e.removedNodes.forEach((e=>{if(e instanceof HTMLElement){const t=le?.get(e);if(t)n(e);else{new Set([...e.querySelectorAll(`[${de}]`),...e.querySelectorAll(`[${ue}]`)]).forEach((e=>n(e)))}}})))}))})).observe(document.body||document.documentElement,{attributes:!0,childList:!0,subtree:!0})},pe=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;function fe(e){const t=e.match(pe);if(!t)return{};return{filename:t[2],functionName:t[1]||"",lineno:parseInt(t[3],10)||void 0,colno:parseInt(t[4],10)||void 0}}function he(e){try{const{stack:t}=e;if(!t)return[];const r=[];for(const e of t.split("\n").slice(1)){const t=fe(e);!t||t.filename?.includes("chrome-extension://")||t.filename?.includes("node_modules")||t.filename?.includes("<anonymous>")||r.push(t)}return r.slice(0,10)}catch(e){return[]}}const ge=new Set,ye=(e,t)=>{if((r=w?.errorTraceRate??.5)<0||r>1?(console.warn("[TM]: probability should be between 0 and 1"),0):Math.random()<r){if(window.trackMonitor.track(t),ge.size>=1e3){const e=ge.values().next().value;void 0!==e&&ge.delete(e)}ge.add(e)}var r},we=()=>{window.addEventListener("error",(e=>{(e=>{if(e instanceof ErrorEvent&&"Script error."===e.message){const t=p("js-Script error.");if(ge.has(t))return;return void ye(t,{data_type:"error",event_type:"js",event_detail:{traceId:te,msg:'Script error.(跨域脚本未加载 crossorigin 属性,无法获取堆栈;建议脚本加 crossorigin="anonymous")',target:"",stack:[],errorUuid:t,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno,crossorigin_missing:!0}}})}if("js"!==m(e))return;if((e=>{const t=e.error?.stack||"";return/chrome-extension:\/\//.test(t)})(e))return;const t=p(`js-${e.message}-${e.filename}`);if(ge.has(t))return;const r=he(e.error),n={traceId:te,msg:e.message,target:r[0]?`${r[0].filename?.split("?")[0]}:${r[0].lineno}:${r[0].colno}`:"",stack:r,errorUuid:t,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno}};ye(t,{data_type:"error",event_type:"js",event_detail:n})})(e)}),!0)},ve=()=>{window.addEventListener("error",(e=>{(e=>{if("resource"!==m(e))return;const t=e.target,r=p(`resource-${t.src}-${t.tagName}`);if(ge.has(r))return;const n={traceId:te,msg:`加载${t.tagName}失败`,target:t.src?.split("?")[0],errorUuid:r,meta:{url:t.src,html:t.outerHTML,tagName:t.tagName}};ye(r,{data_type:"error",event_type:"resource",event_detail:n})})(e)}),!0)},Te=()=>{window.addEventListener("unhandledrejection",(e=>(e=>{const t=e.reason?.message||e.reason,r=p(`unhandledrejection-${t}`);if(ge.has(r))return;const n={traceId:te,msg:t,stack:he(e.reason),errorUuid:r};ye(r,{data_type:"error",event_type:"unhandledrejection",event_detail:n})})(e)),!0)},_e=()=>{const e=(e,t,r)=>{var n;if("string"!=typeof(n=e.url)||![w?.pushUrl,w?.authUrl,w?.realTimeUrl].filter((e=>!!e)).some((e=>0===n.indexOf(e))))if(t){const n=p(`http-${t}-${e.url}-${r}`);if(ge.has(n))return;const o={traceId:te,errorType:t,msg:r,target:e.url.split("?")[0],errorUuid:n,request:e};ye(n,{data_type:"error",event_type:"http",event_detail:o})}else if(e.status>=400){let r=e.statusText;const n=p(`http-${t="http_error"}-${e.url}-${r}`);if(ge.has(n))return;const o={traceId:te,errorUuid:n,errorType:t,target:e.url.split("?")[0],msg:r,request:e};ye(n,{data_type:"error",event_type:"http",event_detail:o})}};((e,t)=>{if("XMLHttpRequest"in window&&"function"==typeof window.XMLHttpRequest){const e=window.XMLHttpRequest;window.oXMLHttpRequest||(window.oXMLHttpRequest=e),window.XMLHttpRequest=function(){const r=new e,{open:n,send:o}=r;let i={};r.open=(e,t,o,a,s)=>{void 0===o&&(o=!0),i.method=e,i.url=t,n.call(r,e,t,o,a,s)},r.send=e=>{i.requestTime=(new Date).getTime(),o.call(r,e)};const a=(e,n)=>{const{status:o,statusText:a}=r,s=(new Date).getTime();i={...i,status:o,statusText:a,responseTime:s,duration:s-i.requestTime},"function"==typeof t&&t(i,e,n)};return r.addEventListener("loadend",(()=>a())),r.addEventListener("error",(()=>a("net_error","ERR_NETWORK"))),r.addEventListener("abort",(()=>a("cannel_request","ERR_CANCELED"))),r.addEventListener("timeout",(()=>a("timeout","ERR_NETWORK"))),r}}})(0,e),((e,t)=>{if("fetch"in window&&"function"==typeof window.fetch){const e=window.fetch;window.oFetch||(window.oFetch=e),window.fetch=async(r,n)=>{let o={};return o.method=n?.method||"",o.url=(r&&"string"!=typeof r?r?.url:r)||"",o.requestTime=(new Date).getTime(),e.call(window,r,n).then((async e=>{if("function"==typeof t){const r=e.clone(),n=(new Date).getTime();o={...o,status:r.status,statusText:r.statusText,responseTime:n,duration:n-o.requestTime},t(o)}return e})).catch((e=>{if("function"==typeof t){const r=(new Date).getTime();o={...o,responseTime:r,duration:r-o.requestTime},"AbortError"===e.name?t(o,"cannel_request","ERR_CANCELED"):t(o,"net_error","ERR_NETWORK")}return Promise.reject(e)}))}}})(0,e)};const be=new WeakSet,Se=e=>({form_id:e.id||null,form_class:"string"==typeof e.className?e.className:null,form_name:e.getAttribute("name")||null,form_action:e.getAttribute("action")||null,form_text:(e.textContent||"").trim().slice(0,200)||null});let Ee=-1;const ke=e=>{addEventListener("pageshow",(t=>{t.persisted&&(Ee=t.timeStamp,e(t))}),!0)},xe=(e,t,r,n)=>{let o,i;return a=>{t.value>=0&&(a||n)&&(i=t.value-(o??0),(i||void 0===o)&&(o=t.value,t.delta=i,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,r),e(t)))}},Me=e=>{requestAnimationFrame((()=>requestAnimationFrame((()=>e()))))},Ae=()=>{const e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},Le=()=>{const e=Ae();return e?.activationStart??0},Ce=(e,t=-1)=>{const r=Ae();let n="navigate";return Ee>=0?n="back-forward-cache":r&&(document.prerendering||Le()>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}},Re=new WeakMap;function Ie(e,t){return Re.get(e)||Re.set(e,new t),Re.get(e)}class $e{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const qe=(e,t,r={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){const n=new PerformanceObserver((e=>{Promise.resolve().then((()=>{t(e.getEntries())}))}));return n.observe({type:e,buffered:!0,...r}),n}}catch{}},Ne=e=>{let t=!1;return()=>{t||(e(),t=!0)}};let Pe=-1;const Oe=new Set,Ue=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,Be=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(const e of Oe)e();isFinite(Pe)||(Pe="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",Be,!0))}},ze=()=>{if(Pe<0){const e=Le(),t=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>"hidden"===t.name&&t.startTime>e))[0]?.startTime;Pe=t??Ue(),addEventListener("visibilitychange",Be,!0),addEventListener("prerenderingchange",Be,!0),ke((()=>{setTimeout((()=>{Pe=Ue()}))}))}return{get firstHiddenTime(){return Pe},onHidden(e){Oe.add(e)}}},De=e=>{document.prerendering?addEventListener("prerenderingchange",(()=>e()),!0):e()},Fe=[1800,3e3],je=(e,t={})=>{De((()=>{const r=ze();let n,o=Ce("FCP");const i=qe("paint",(e=>{for(const t of e)"first-contentful-paint"===t.name&&(i.disconnect(),t.startTime<r.firstHiddenTime&&(o.value=Math.max(t.startTime-Le(),0),o.entries.push(t),n(!0)))}));i&&(n=xe(e,o,Fe,t.reportAllChanges),ke((r=>{o=Ce("FCP"),n=xe(e,o,Fe,t.reportAllChanges),Me((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))})))}))},He=[.1,.25];let Je=0,Ke=1/0,We=0;const Xe=e=>{for(const t of e)t.interactionId&&(Ke=Math.min(Ke,t.interactionId),We=Math.max(We,t.interactionId),Je=We?(We-Ke)/7+1:0)};let Qe;const Ge=()=>Qe?Je:performance.interactionCount??0;let Ve=0;class Ye{u=[];l=new Map;m;p;v(){Ve=Ge(),this.u.length=0,this.l.clear()}L(){const e=Math.min(this.u.length-1,Math.floor((Ge()-Ve)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&"first-input"!==e.entryType)return;const t=this.u.at(-1);let r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((e,t)=>t.P-e.P)),this.u.length>10){const e=this.u.splice(10);for(const t of e)this.l.delete(t.id)}this.p?.(r)}}}const Ze=e=>{const t=globalThis.requestIdleCallback||setTimeout;"hidden"===document.visibilityState?e():(e=Ne(e),addEventListener("visibilitychange",e,{once:!0,capture:!0}),t((()=>{e(),removeEventListener("visibilitychange",e,{capture:!0})})))},et=[200,500],tt=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const r=ze();De((()=>{"interactionCount"in performance||Qe||(Qe=qe("event",Xe,{type:"event",buffered:!0,durationThreshold:0}));let n,o=Ce("INP");const i=Ie(t,Ye),a=e=>{Ze((()=>{for(const t of e)i.h(t);const t=i.L();t&&t.P!==o.value&&(o.value=t.P,o.entries=t.entries,n())}))},s=qe("event",a,{durationThreshold:t.durationThreshold??40});n=xe(e,o,et,t.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),r.onHidden((()=>{a(s.takeRecords()),n(!0)})),ke((()=>{i.v(),o=Ce("INP"),n=xe(e,o,et,t.reportAllChanges)})))}))};class rt{m;h(e){this.m?.(e)}}const nt=[2500,4e3],ot=[800,1800],it=e=>{document.prerendering?De((()=>it(e))):"complete"!==document.readyState?addEventListener("load",(()=>it(e)),!0):setTimeout(e)};function at(){const e={ttfb:null,lcp:null,fp:null,fcp:null,connectionRtt:null,ttfbRequestTime:null,inp:null,cls:null,dcl:null,loadTime:null};((e,t={})=>{De((()=>{const r=ze();let n,o=Ce("LCP");const i=Ie(t,rt),a=e=>{t.reportAllChanges||(e=e.slice(-1));for(const t of e)i.h(t),t.startTime<r.firstHiddenTime&&(o.value=Math.max(t.startTime-Le(),0),o.entries=[t],n())},s=qe("largest-contentful-paint",a);if(s){n=xe(e,o,nt,t.reportAllChanges);const r=Ne((()=>{a(s.takeRecords()),s.disconnect(),n(!0)})),i=e=>{e.isTrusted&&(Ze(r),removeEventListener(e.type,i,{capture:!0}))};for(const e of["keydown","click","visibilitychange"])addEventListener(e,i,{capture:!0});ke((r=>{o=Ce("LCP"),n=xe(e,o,nt,t.reportAllChanges),Me((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))}))}}))})((t=>{e.lcp=d(t.value)}),{reportAllChanges:!0}),((e,t={})=>{const r=ze();je(Ne((()=>{let n,o=Ce("CLS",0);const i=Ie(t,$e),a=e=>{for(const t of e)i.h(t);i.i>o.value&&(o.value=i.i,o.entries=i.o,n())},s=qe("layout-shift",a);s&&(n=xe(e,o,He,t.reportAllChanges),r.onHidden((()=>{a(s.takeRecords()),n(!0)})),ke((()=>{i.i=0,o=Ce("CLS",0),n=xe(e,o,He,t.reportAllChanges),Me((()=>n()))})),setTimeout(n))})))})((t=>{e.cls=Math.round(1e4*t.value)/1e4}),{reportAllChanges:!0}),tt((t=>{e.inp=d(t.value)}),{reportAllChanges:!0}),((e,t={})=>{let r=Ce("TTFB"),n=xe(e,r,ot,t.reportAllChanges);it((()=>{const o=Ae();o&&(r.value=Math.max(o.responseStart-Le(),0),r.entries=[o],n(!0),ke((()=>{r=Ce("TTFB",0),n=xe(e,r,ot,t.reportAllChanges),n(!0)})))}))})((t=>{e.ttfb=d(t.value)})),je((t=>{e.fcp=d(t.value)}));const t=()=>{(()=>{try{performance.getEntriesByType("paint").forEach((t=>{"first-paint"===t.name&&(e.fp=d(t.startTime))}))}catch(e){console.warn("[TM]: Failed to collect FP:",e)}try{const t=navigator.connection||navigator.mozConnection||navigator.webkitConnection;t&&void 0!==t.rtt&&(e.connectionRtt=t.rtt)}catch(e){console.warn("[TM]: Failed to collect Connection RTT:",e)}try{const t=performance.getEntriesByType("navigation")[0];if(t){const{responseStart:r,requestStart:n}=t;r>0&&n>0&&n<=r&&(e.ttfbRequestTime=d(r-n))}}catch(e){console.warn("[TM]: Failed to collect TTFB Request Time:",e)}try{const t=performance.getEntriesByType("navigation")[0];if(t){const{domContentLoadedEventEnd:r,loadEventEnd:n,fetchStart:o}=t;r>0&&o>0&&(e.dcl=d(r-o)),n>0&&o>0&&(e.loadTime=d(n-o))}}catch(e){console.warn("[TM]: Failed to collect DCL and Load Time:",e)}})(),window.trackMonitor.track({data_type:"performance",event_type:"metrics",event_detail:{traceId:te,data:e}})};let r=0;const n=()=>{const e=Date.now();e-r<3e4||(r=e,t())};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",n),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&n()}))}const st="__tengence_sdk",ct=e=>{if("undefined"!=typeof window&&window.trackMonitor&&window.trackMonitor[st])return console.warn("[TM]: init 已调用过,复用现有实例(如需重建请刷新页面)"),window.trackMonitor;const{client:t,beforeClose:r}=ee(e);var n;return me(t.track),!1!==e.traceBehavior&&se({enableScroll:e.enableScroll}),!1!==e.enableFormTrack&&(n=t.track,document.addEventListener("focusin",(e=>{const t=e.target;if(!(r=t)||"INPUT"!==r.tagName&&"SELECT"!==r.tagName&&"TEXTAREA"!==r.tagName)return;var r;const o=t.closest("form");o&&!be.has(o)&&(be.add(o),n({data_type:"auto",event_type:"form_start",event_detail:Se(o)}))}),!0),document.addEventListener("submit",(e=>{const t=e.target;if(!t||"FORM"!==t.tagName)return;const r=e.submitter;n({data_type:"auto",event_type:"form_submit",event_detail:{...Se(t),submitter_id:r?.id||null,submitter_text:(r?.textContent||"").trim().slice(0,200)||null}})}),!0)),!1!==e.traceError&&(we(),ve(),Te(),_e()),!1!==e.tracePerformance&&l((()=>{!function(){const e=window.performance||window.msPerformance;if(!e)return{dnsLookupTime:null,tcpConnectTime:null,ttfb:null,transferTime:null,domParseTime:null,domCompleteTime:null,loadEventTime:null,totalPageLoad:null};const t=e.getEntriesByType&&"function"==typeof e.getEntriesByType?e.getEntriesByType("navigation"):void 0,r=Array.isArray(t)?t[0]:void 0;let n=null;if(r)n=r;else{const t=e.timing;t&&(n={startTime:0,domainLookupStart:t.domainLookupStart,domainLookupEnd:t.domainLookupEnd,connectStart:t.connectStart,connectEnd:t.connectEnd,requestStart:t.requestStart,responseStart:t.responseStart,responseEnd:t.responseEnd,domInteractive:t.domInteractive,domComplete:t.domComplete,loadEventEnd:t.loadEventEnd,fetchStart:t.fetchStart},!n.requestStart&&t.fetchStart&&(n.requestStart=t.fetchStart))}const o={dnsLookupTime:n?d(n.domainLookupEnd-n.domainLookupStart):null,tcpConnectTime:n?d(n.connectEnd-n.connectStart):null,ttfb:n?d(n.responseStart-(n.requestStart??n.fetchStart??0)):null,transferTime:n?d(n.responseEnd-n.responseStart):null,domParseTime:n?d(n.domInteractive-n.responseEnd):null,domCompleteTime:n?d(n.domComplete-n.domInteractive):null,loadEventTime:n?d(n.loadEventEnd-(n.domComplete??0)):null,totalPageLoad:n?d((n.loadEventEnd??performance.now())-(n.startTime??0)):null};window.trackMonitor.track({data_type:"performance",event_type:"navigation_timing",event_detail:{traceId:te,data:o}})}(),function(){const e=window.performance||window.msPerformance;if(!e)return[];const t=[];if(e.getEntriesByType){const r=(e.getEntriesByType("resource")||[]).map((e=>{const t="number"==typeof e.redirectEnd&&"number"==typeof e.redirectStart?d(e.redirectEnd-e.redirectStart):null,r="number"==typeof e.domainLookupEnd&&"number"==typeof e.domainLookupStart?d(e.domainLookupEnd-e.domainLookupStart):null,n="number"==typeof e.connectEnd&&"number"==typeof e.connectStart?d(e.connectEnd-e.connectStart):null,o="number"==typeof e.requestStart&&"number"==typeof e.fetchStart?d(e.requestStart-e.fetchStart):null,i="number"==typeof e.responseStart&&"number"==typeof e.requestStart?d(e.responseStart-e.requestStart):null,a="number"==typeof e.responseEnd&&"number"==typeof e.responseStart?d(e.responseEnd-e.responseStart):null,s="number"==typeof e.duration?d(e.duration):null,c="number"==typeof e.startTime?d(e.startTime):null,l="number"==typeof e.transferSize&&isFinite(e.transferSize)&&e.transferSize>=0?Math.round(e.transferSize):null,u="number"==typeof e.encodedBodySize&&isFinite(e.encodedBodySize)&&e.encodedBodySize>=0?Math.round(e.encodedBodySize):null,m="number"==typeof e.decodedBodySize&&isFinite(e.decodedBodySize)&&e.decodedBodySize>=0?Math.round(e.decodedBodySize):null;return{name:e.name,initiatorType:e.initiatorType||"",startTime:c,duration:s,redirectTime:t,cacheTime:o,dnsTime:r,connectTime:n,requestTime:i,responseTime:a,transferSize:l,encodedBodySize:u,decodedBodySize:m}}));r.sort(((e,t)=>(t.duration??0)-(e.duration??0)));const n=w?.resourceFlowLimit??15;if(0===n)return;for(let e=0;e<Math.min(n,r.length);e++)t.push(r[e]);if(!t.length)return}window.trackMonitor.track({data_type:"performance",event_type:"resource_flow",event_detail:{traceId:te,data:t}})}(),at()})),l((()=>{r()})),window.trackMonitor[st]=!0,window.trackMonitor};export{ct as default};
|
|
1
|
+
class e extends Error{status;constructor(e,t){super(t||`[TM]: Auth error ${e}`),this.name="AuthError",this.status=e}}const t=({method:e,url:t,data:r,headers:n={},withCredentials:o=!1,timeoutMs:i})=>new Promise(((a,s)=>{const c=new XMLHttpRequest;c.open(e,t,!0),i&&(c.timeout=i),Object.keys(n).forEach((e=>{c.setRequestHeader(e,n[e])})),c.withCredentials=!!o,c.onreadystatechange=()=>{if(4===c.readyState)if(c.status>=200&&c.status<300)try{const e=JSON.parse(c.responseText);a(e)}catch(e){s(e)}else{const e=new Error(`[TM]: Request failed with status ${c.status}`);e.status=c.status,s(e)}},c.onerror=()=>{s(new Error("[TM]: Network error"))},c.ontimeout=()=>{const e=new Error("[TM]: Request timeout");e.timeout=!0,s(e)},"POST"===e&&r?c.send(r):c.send()})),r=(e,t,r)=>{if(!r)return fetch(e,t);const n=new AbortController,o=setTimeout((()=>n.abort()),r);return fetch(e,{...t,signal:n.signal}).catch((e=>{if(e&&"AbortError"===e.name){const e=new Error("[TM]: Request timeout");throw e.timeout=!0,e}throw e})).finally((()=>clearTimeout(o)))},n=(n,o,i,a)=>{const s={"Content-Type":"application/json"};i&&(s.Authorization=`Bearer ${i}`);const c=()=>t({method:"POST",url:n,data:JSON.stringify(o),headers:s,withCredentials:!0,timeoutMs:a});return"function"!=typeof fetch?c():r(n,{method:"POST",keepalive:!0,credentials:"include",headers:s,body:JSON.stringify(o)},a).then((t=>{if(401===t.status||403===t.status)throw new e(t.status,`[TM]: Auth error ${t.status}`);if(429===t.status){const e=new Error("[TM]: Request throttled with status 429");e.status=429;const r=t.headers.get("Retry-After");if(r){const t=parseInt(r,10);isNaN(t)||(e.retryAfter=1e3*t)}throw e}if(!t.ok){const e=new Error(`[TM]: Request failed with status ${t.status}`);throw e.status=t.status,e}return t.json()})).catch((t=>{if(t instanceof e)throw t;if(t&&t.status)throw t;return c()}))},o=window.requestIdleCallback||window.requestAnimationFrame||(e=>setTimeout(e,17));function i(e,t=150,r=!1){let n=null;return function(...o){const i=this,a=r&&!n;n&&clearTimeout(n),n=setTimeout((()=>{n=null,r||e.apply(i,o)}),t),a&&e.apply(i,o)}}const a=(e,t=300)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}};function s(e,t=""){if(!e)return t;const r=e.parentElement,{id:n}=e,o=e.tagName.toLowerCase(),i=t?`>${t}`:"";return r&&r!==document.documentElement&&r!==document.body?n?`#${n}${i}`:s(r,`${o}${i}`):`${o}${i}`}const c=()=>{if(window.performance?.navigation)return performance.navigation.type;if(window.performance?.getEntriesByType){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type}return 255},l=e=>{"prerendering"in document&&document.prerendering?(e=>{"prerendering"in document&&document.prerendering?addEventListener("prerenderingchange",(()=>e()),!0):e()})((()=>l(e))):"complete"!==document?.readyState?addEventListener("load",(()=>l(e)),!0):setTimeout(e)};function u(e){return"number"!=typeof e||!isFinite(e)||e<0?null:Math.round(100*e)/100}function d(){const e=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;let t="";for(let r=0;r<16;r++)t+=(e[r]<16?"0":"")+e[r].toString(16);return t}const m=e=>e instanceof ErrorEvent?"Script error."===e.message?"cors":"js":"resource",p=e=>(e=>{let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)>>>0;return t.toString(16).padStart(8,"0")})(e)+(e=>{let t=5381;for(let r=e.length-1;r>=0;r--)t=((t<<5)+t^e.charCodeAt(r))>>>0;return t.toString(16).padStart(8,"0")})(e);const f={view:"#3b82f6",click:"#06b6d4",expose:"#8b5cf6",enter:"#10b981",leave:"#f59e0b",stay:"#84cc16",cart:"#ec4899",buy:"#ef4444",pay:"#dc2626",default:"#6b7280"},h={view:"👁️",click:"👆",expose:"✨",enter:"🚪",leave:"👋",stay:"⏱️",cart:"🛒",buy:"💰",pay:"💳",default:"📊"},g={common:"#3b82f6",behavior:"#10b981",performance:"#f59e0b",error:"#ef4444",custom:"#8b5cf6",default:"#6b7280"},y=(e,t)=>{t.forEach(((t,r)=>{const n=t.event_type||"unknown",o=t.data_type||"auto",i=(e=>f[e]||f.default)(n),a=(e=>g[e]||g.default)(o),s=(e=>h[e]||h.default)(n);let c=t.event_detail;if("string"==typeof c)try{c=JSON.parse(c)}catch(e){}console.groupCollapsed(`%c${s} [TM-${e}] %c${o.toUpperCase()}%c → %c${n.toUpperCase()}%c #${r+1}`,"color: #6b7280; font-weight: bold;",`color: ${a}; font-weight: bold; background: ${a}20; padding: 2px 6px; border-radius: 3px;`,"color: #6b7280;",`color: ${i}; font-weight: bold; background: ${i}20; padding: 2px 6px; border-radius: 3px;`,"color: #6b7280; font-weight: normal;");const l={...t,event_detail:c};console.log("%c"+JSON.stringify(l,null,2),"color: #6b7280; font-family: monospace; font-size: 11px; line-height: 1.5;"),console.groupEnd()})),console.log(`%c✅ [TM] 本次通过 ${e} 上报 ${t.length} 条埋点数据`,"color: #10b981; font-weight: bold; font-size: 12px; padding: 4px 8px; background: #10b98120; border-radius: 4px; border-left: 3px solid #10b981;")},w=["auto","behavior","performance","error"],v="tengence_sdk_config";let T=null;const _=(e,t)=>{if(t)return t;if(e){const t=/^(https?:\/\/[^/]+)/.exec(e);if(t)return`${t[1]}/v1/track/config`}return"https://api.tengence.com/v1/track/config"},b=async(n,o,i)=>{try{const a=await((n,o,i)=>{const a={};o&&(a.Authorization=`Bearer ${o}`);const s=()=>t({method:"GET",url:n,headers:a,withCredentials:!0,timeoutMs:i});return"function"!=typeof fetch?s():r(n,{method:"GET",credentials:"include",headers:a},i).then((t=>{if(401===t.status||403===t.status)throw new e(t.status,`[TM]: Auth error ${t.status}`);if(!t.ok){const e=new Error(`[TM]: Request failed with status ${t.status}`);throw e.status=t.status,e}return t.json()})).catch((t=>{if(t instanceof e)throw t;if(t&&t.status)throw t;return s()}))})(n,o,i),s=a?.data??a;if(!s||!Array.isArray(s.dataTypes)||0===s.dataTypes.length)return"undefined"!=typeof console&&console.warn("[TM]: 远程配置返回空,沿用缓存/默认配置"),null;const c={appId:s.appId,dataTypes:s.dataTypes.filter((e=>w.includes(e))),idFieldName:"string"==typeof s.idFieldName&&s.idFieldName?s.idFieldName:"event_id",configVersion:s.configVersion,updatedAt:s.updatedAt,fetchedAt:Date.now()};return(e=>{try{localStorage.setItem(v,JSON.stringify(e))}catch{}})(c),T=c,c}catch(e){return"undefined"!=typeof console&&console.warn("[TM]: 拉取远程配置失败,沿用缓存/默认配置",e),null}};let S;const E="TRACK_MONITOR_DATA",k="MONITOR_REAL_TIME_DATA",M="TRACK_MONITOR_USER",x="tengence_device_id",A="tengence_register_properties",L="TRACK_MONITOR_LOGGER",C="tengence_tracking_enabled",R=2e3,I="tengence_access_token";let $=null,N=null;const q=e=>((e,n,o)=>{const i={"Content-Type":"application/json"},a=()=>t({method:"POST",url:e,data:JSON.stringify(n),headers:i,withCredentials:!0,timeoutMs:o});return"function"!=typeof fetch?a():r(e,{method:"POST",credentials:"include",headers:i,body:JSON.stringify(n)},o).then((e=>{if(!e.ok){const t=new Error(`[TM]: Request failed with status ${e.status}`);throw t.status=e.status,t}return e.json()})).catch((e=>{if(e&&e.status)throw e;return a()}))})(e,{},S?.requestTimeout).then((e=>{const t=e&&e.data,r=t&&t.accessToken,n=t&&t.accessExpAt;if(!r||"number"!=typeof n)throw new Error("[TM]: authUrl 响应缺少 accessToken/accessExpAt");return((e,t)=>{$={token:e,expAt:t};try{localStorage.setItem(I,JSON.stringify({token:e,expAt:t}))}catch(e){}})(r,n),r})),P=e=>{const t=(()=>{if($)return $;try{const e=localStorage.getItem(I);if(!e)return null;const t=JSON.parse(e);if(t&&"string"==typeof t.token&&t.token&&"number"==typeof t.expAt)return $={token:t.token,expAt:t.expAt},$}catch(e){}return null})();return(r=t)&&r.token.length>0&&r.expAt-6e4>Date.now()?Promise.resolve(t.token):(N||(N=q(e).catch((e=>{throw e})).finally((()=>{N=null}))),N);var r},O={timer:null,promise:null},U={timer:null,promise:null},B=e=>{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length/1024};let z=null;const D=()=>{if(z)return z;try{const e=localStorage.getItem(A),t=e?JSON.parse(e):{};return z=t,t}catch(e){return console.error("[TM]: get register properties fail: ",e),{}}},F=e=>{z=e;try{localStorage.setItem(A,JSON.stringify(e))}catch(e){console.error("[TM]: save register properties fail: ",e)}},j=e=>{if(!e||"object"!=typeof e||Array.isArray(e))return void console.error("[TM]: registerGlobalProperties props must be a plain object");const t={...D(),...e},r=Object.keys(t);if(r.length>50){const e={};return r.slice(0,50).forEach((r=>{e[r]=t[r]})),console.warn("[TM]: register properties exceed max 50 keys, extra keys dropped"),void F(e)}F(t)},H=e=>{const t=document.cookie.match(new RegExp("(?:^|;\\s*)"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):void 0},J=e=>{document.cookie=`${x}=${encodeURIComponent(e)}; Max-Age=63072000; Path=/; Secure; SameSite=Lax`};let K;const G=()=>{if(K)return K;try{let e=localStorage.getItem(x);if(e)return H(x)||J(e),K=e;const t=H(x);if(t){try{localStorage.setItem(x,t)}catch(e){}return K=t}e=d();try{localStorage.setItem(x,e)}catch(e){}return J(e),K=e}catch(e){return void console.error("[TM]: get or create device id fail: ",e)}},W="tengence_session_id",X=()=>{try{const e=sessionStorage.getItem(W);let t=e?JSON.parse(e):null;const r=Date.now();return!t||!t.id||r-t.lastActiveAt>18e5?(t={id:d(),lastActiveAt:r},sessionStorage.setItem(W,JSON.stringify(t))):(t.lastActiveAt=r,sessionStorage.setItem(W,JSON.stringify(t))),t.id}catch(e){return}},Q=(e,t)=>{try{const r=new URL(e,location.href);if(!r.searchParams.toString())return e;if(t&&t.length){const e=[];for(const n of t){const t=r.searchParams.get(n);null!==t&&e.push(`${n}=${encodeURIComponent(t)}`)}r.search=e.length?`?${e.join("&")}`:""}else r.search="";return r.toString()}catch(t){return e}},V=(e,t,r)=>{if("string"==typeof e)return t>0&&e.length>t?e.slice(0,t)+"...[truncated]":e;if(Array.isArray(e))return e.map((e=>V(e,t,r)));if(e&&"object"==typeof e){const n={};for(const o of Object.keys(e)){const i=e[o];"string"==typeof i&&/(^|_)url$|(^|_)href$|^referrer$/i.test(o)&&/^https?:\/\//i.test(i)?n[o]=Q(i,r):n[o]=V(i,t,r)}return n}return e},Y=e=>{const t={page_url:location.href,hostname:window.location.hostname||window.location.host,os:window.navigator.platform,user_id:localStorage.getItem(M)||void 0,user_agent:window.navigator.userAgent,screen_width:window.screen.width,screen_height:window.screen.height,lib_version:"1.2.2",lib_type:"js",event_time:Date.now(),timezone_offset:(new Date).getTimezoneOffset().toString()},r=S?.sanitize;let n;try{n="string"==typeof e.event_detail?e.event_detail:JSON.stringify(r&&(r.maxTextLength>0||r.stripQuery)?V(e.event_detail,r.maxTextLength,r.preserveQueryKeys):e.event_detail)}catch(e){return ne("serialize_failed","事件 event_detail 序列化失败(循环引用/BigInt?),该事件丢弃",{error:e}),void console.warn("[TM]: event_detail 序列化失败,该事件丢弃",e)}return{session_id:e.session_id||(S?.enableAutoSessionId?X():void 0),request_id:e.request_id,event_id:e.event_id||d(),spm:e.spm,data_type:e.data_type||"behavior",event_type:e.event_type,event_detail:n,...t,page_url:r&&r.stripQuery?Q(t.page_url,r.preserveQueryKeys):t.page_url,device_id:G(),register_properties:JSON.stringify(D()),platform:e.platform||Z}};let Z;const ee=()=>{try{return"true"===localStorage.getItem(L)}catch(e){return!1}},te=(e,t,r,n,o)=>void 0===e?t:"number"!=typeof e||Number.isNaN(e)||e<r||e>n?(console.warn(`[TM]: 配置 ${o}=${e} 非法,回退默认值 ${t}`),t):e,re=(e,t)=>{try{S?.onDrop?.(e,t)}catch(e){}},ne=(e,t,r)=>{S?.isLogger&&console.error(`[TM]: ${t}`);try{S?.onError?.({code:e,message:t,context:r})}catch(e){}},oe=()=>{try{const e=localStorage.getItem(C);return null===e||"1"===e}catch(e){return!0}},ie=t=>{const r=t.apiKey;let i;const a=/Android|iPhone|iPad|iPod|Mobile/i.test(window.navigator.userAgent);Z=t.platform||(a?"h5":"web"),S={pushUrl:t.pushUrl||"https://api.tengence.com/v1/push/event",authUrl:t.authUrl,realTimeUrl:t.realTimeUrl,cacheNumber:te(t.cacheNumber,100,1,1/0,"cacheNumber"),reportInterval:te(t.reportInterval,5e3,100,1/0,"reportInterval"),realTimeReportInterval:te(t.realTimeReportInterval,200,100,1/0,"realTimeReportInterval"),maxCacheSize:te(t.maxCacheSize,56,1,1/0,"maxCacheSize"),maxRetries:te(t.maxRetries,10,0,1/0,"maxRetries"),isLogger:t.isLogger??ee(),errorTraceRate:te(t.errorTraceRate,.5,0,1,"errorTraceRate"),resourceFlowLimit:te(t.resourceFlowLimit,15,0,200,"resourceFlowLimit"),traceBehavior:t.traceBehavior??!0,tracePerformance:t.tracePerformance??!0,traceError:t.traceError??!0,sanitize:!1===t.sanitize?{stripQuery:!1,maxTextLength:0,preserveQueryKeys:[]}:{stripQuery:t.sanitize?.stripQuery??!1,maxTextLength:te(t.sanitize?.maxTextLength,0,0,1/0,"sanitize.maxTextLength"),preserveQueryKeys:t.sanitize?.preserveQueryKeys||[]},enableAutoSessionId:t.enableAutoSessionId??!1,enableTracking:t.enableTracking??oe(),respectGpc:t.respectGpc??!0,requestTimeout:te(t.requestTimeout,1e4,1e3,6e4,"requestTimeout"),configUrl:_(t.pushUrl,t.configUrl),configTtl:te(t.configTtl,3e5,6e4,864e5,"configTtl"),beforeSend:t.beforeSend,onDrop:t.onDrop,onError:t.onError};let{pushUrl:s,authUrl:c,realTimeUrl:l,cacheNumber:u,reportInterval:d,realTimeReportInterval:m,maxCacheSize:p,maxRetries:f}=S;r||c||(console.error("[TM]: 未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"),ne("init_missing_credential","未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"));const h=(()=>{try{const e=localStorage.getItem(v);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t.dataTypes)&&0!==t.dataTypes.length?t:null}catch{return null}})();h&&(T=h),o((async()=>{try{const e=r||i||(c?await P(c):void 0);e&&await b(S.configUrl,e,S.requestTimeout)}catch{}}));const g={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},w={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},x=e=>{try{localStorage.setItem(M,e)}catch(e){console.error("[TM]: monitor bind user fail: ",e)}},A=()=>{localStorage.removeItem(M)},N={},q={},z=new Set;let D=null;const F=()=>{null!==D&&(clearTimeout(D),D=null),z.size&&(z.forEach((e=>{try{localStorage.setItem(e,JSON.stringify(N[e]||[]))}catch(t){ne("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),本次数据仅保留内存",{key:e,error:t})}})),z.clear())},H=e=>{if(N[e])return N[e];let t=[];try{t=JSON.parse(localStorage.getItem(e)||"[]")}catch(t){ne("queue_read_failed","读取本地缓存队列失败,按空队列处理",{key:e,error:t})}return N[e]=t,q[e]=t.reduce(((e,t)=>e+B(t)),0),N[e]},J=(e,t)=>{z.delete(e),N[e]=t,q[e]=t.reduce(((e,t)=>e+B(t)),0);try{localStorage.setItem(e,JSON.stringify(t))}catch(t){ne("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),队列清空处理",{key:e,error:t});try{localStorage.setItem(e,"[]")}catch(t){ne("localstorage_unavailable","localStorage 不可用,本次数据仅保留内存",{key:e,error:t})}}},K=e=>{i=e},G=async(t,o,a=!1)=>{const u=t&&l?l:s;let d;try{d=r||i||(c?await P(c):void 0)}catch(e){throw ne("token_fetch_failed","从 authUrl 获取 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:c,error:e}),e}if(!d)throw ne("init_missing_credential","未配置 apiKey/authUrl 且未注入 accessToken,本次数据未上报(保留缓存队列待重试)"),new Error("[TM]: credential missing, skip report");S?.isLogger&&y(t?"RealTimeFetch":"Fetch",o);const m=S?.beforeSend?(()=>{let e;try{e=S.beforeSend(o)}catch(e){ne("before_send_failed","beforeSend 钩子抛错,本次按原始数据发送",{error:e})}return Array.isArray(e)?e:o})():o,p=a?void 0:S?.requestTimeout;return n(u,{data:m},d,p).catch((async t=>{const o=t?.status;if((t instanceof e||401===o||403===o)&&!r&&!i&&c){(()=>{$=null;try{localStorage.removeItem(I)}catch(e){}})();const e=await P(c).catch((()=>{}));if(e)return n(u,{data:m},e,p);ne("token_invalid","上报 401/403 且刷新 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:c})}throw t}))},W=(e,t)=>{const r=new Set(t.filter((e=>!!e)));if(!r.size)return;const n=H(e);if(!n.length)return;const o=n.filter((e=>e.event_id&&!r.has(e.event_id)));o.length!==n.length&&J(e,o)},X=(e,t,r=0)=>{const n=(t?m:d)*Math.pow(2,e)*(.8+.4*Math.random()),o=Math.min(n,6e4);return Math.max(o,r)},Q=(e,t)=>{const r=B(t);if(r>=64)return re([t],"item_too_large"),void console.warn("[TM]: 单条事件超过体积上限(64KB),丢弃该条");const n=H(e);if(n.unshift(t),q[e]+=r,n.length>R){const t=n.length-R,r=n.splice(n.length-t,n.length);q[e]=n.reduce(((e,t)=>e+B(t)),0),re(r,"queue_overflow"),console.warn(`[TM]: 队列超过上限(2000条),丢弃最旧 ${t} 条`)}(e=>{z.add(e),null===D&&(D=setTimeout((()=>{D=null,F()}),200))})(e),V(e,q[e]>=p)},V=(e,t=!1,r=!1)=>{if(!S?.enableTracking)return;let n=H(e);if(!n.length)return;const o=(e=>e===k)(e),i=o?U:O,a=(e=>e?w:g)(o);if(a.halveBatch&&n.length>1&&(n=n.slice(0,Math.ceil(n.length/2))),a.retryExhausted)return;if(Date.now()<a.nextRetryAt)return void(null===i.timer&&(i.timer=setTimeout((()=>{i.timer=null,V(e)}),a.nextRetryAt-Date.now())));if(0!==a.retryCount||(n.length>=u||t)){if(null!==i.timer&&(clearTimeout(i.timer),i.timer=null),i.promise)return;i.promise=(async(e,t,r,n,o=!1)=>{const i=[];let a=[],s=0;for(const e of t){const t=1024*B(e);a.length&&s+t>65536&&(i.push(a),a=[],s=0),a.push(e),s+=t}a.length&&i.push(a);for(const t of i){const n=await G(r,t,o),i=n?.data?.accepted_ids,a=n?.data?.rejected_ids;if(Array.isArray(i)){if(W(e,i),Array.isArray(a)&&a.length){const r=new Set(a);W(e,a);const n=t.filter((e=>e.event_id&&r.has(e.event_id)));n.length&&re(n,"server_rejected"),console.warn(`[TM]: 服务端校验拒绝 ${a.length} 条(永久性拒绝),已从队列移除并通知 onDrop`)}}else W(e,t.map((e=>e.event_id))),S?.isLogger&&console.warn("[TM]: 响应缺少 accepted_ids,按整批成功清理")}n.retryCount=0,n.nextRetryAt=0,n.halveBatch=!1})(e,n,o,a,r).catch((e=>{((e,t,r,n,o)=>{t?.timeout&&ne("request_timeout","上报请求超时,数据保留队列按退避重试",{url:r&&l?l:s,timeoutMs:S?.requestTimeout});const i=t?.status;if(413===i)return void(o.length>1?(n.halveBatch=!0,n.retryCount++,n.nextRetryAt=Date.now()+X(n.retryCount,r,0),console.warn(`[TM]: 批次过大(HTTP 413),降容半批重发(本批 ${o.length} 条)`)):(n.retryExhausted=!0,re(o,"rejected_4xx"),console.warn("[TM]: 单条事件仍超限(HTTP 413),数据保留在队列")));if(i&&i>=400&&i<500&&401!==i&&403!==i&&408!==i&&410!==i&&429!==i)return n.retryExhausted=!0,re(o,"rejected_4xx"),void console.warn(`[TM]: 批次提交被服务端拒绝(HTTP ${i}),数据保留在队列并暂停自动重试`);if(n.retryCount++,n.retryCount>f)return n.retryExhausted=!0,re(o,"retries_exhausted"),void console.warn(`[TM]: 重试次数已达上限(${f}),数据保留在队列(不丢弃),待下次会话或手动触发重试`);const a=429===i&&t?.retryAfter||0;n.nextRetryAt=Date.now()+X(n.retryCount,r,a),console.error(`[TM]: send report fail, retryCount: ${n.retryCount}, next retry after ${Math.round((n.nextRetryAt-Date.now())/1e3)}s`)})(0,e,o,a,n)})).finally((()=>{i.timer=null,i.promise=null,V(e)}))}else if(null===i.timer){const t=o?m:d;i.timer=setTimeout((()=>{i.timer=null,V(e,!0)}),t)}},ie=e=>{if(!S?.enableTracking||S?.respectGpc&&function(){const e="undefined"!=typeof navigator?navigator:void 0;return!0===e?.globalPrivacyControl}())return void(S?.isLogger&&console.warn("[TM]: 用户已选择退出采集(enableTracking=false 或 GPC 信号开启),本事件忽略"));if(!e||"object"!=typeof e)return void console.error("[TM]: track data must be an object");const t=!0===e.track_real_time,r=Y(e);var n;if(r)if(n=r.data_type,T&&n&&!T.dataTypes.includes(n))S?.isLogger&&console.warn(`[TM]: 数据类型 ${r.data_type} 未在远程配置中启用,本事件不上报`);else try{Q(t&&l?k:E,r)}catch(e){ne("enqueue_failed","事件入队失败",{error:e})}},ae=(e,t,r)=>{ie("string"==typeof e?{event_type:e,event_detail:t,...r}:e)},se=()=>{V(E,!0),V(k,!0);const e=[O.promise,U.promise].filter((e=>!!e));return Promise.all(e).then((()=>{}))},ce=()=>{S.isLogger=!0;try{localStorage.setItem(L,"true")}catch(e){console.error("[TM]: enable logger fail:",e)}},le=()=>{S.isLogger=!1;try{localStorage.setItem(L,"false")}catch(e){console.error("[TM]: disable logger fail:",e)}};o((()=>{V(E,!0),V(k,!0)}));const ue=e=>("boolean"==typeof e&&(S.enableTracking=e,(e=>{try{localStorage.setItem(C,e?"1":"0")}catch(e){}})(e),e?S?.isLogger&&console.warn("[TM]: 恢复采集"):(J(E,[]),J(k,[]),S?.isLogger&&console.warn("[TM]: 用户已选择退出采集,已清空未上报队列"))),!0===S?.enableTracking);return window.trackMonitor={track:ae,flush:se,bindUser:x,unBindUser:A,enableLogger:ce,disableLogger:le,setToken:K,registerGlobalProperties:j,enableTracking:ue},{client:{track:ae,flush:se,bindUser:x,unBindUser:A,enableLogger:ce,disableLogger:le,setToken:K,registerGlobalProperties:j,enableTracking:ue},beforeClose:()=>{const e=()=>{F(),V(E,!0,!0),V(k,!0,!0)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&e()})),window.addEventListener("online",e)}}},ae=(se=16,function(){const e=new Uint8Array(se);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<se;t++)e[t]=Math.floor(256*Math.random());let t="";for(let r=0;r<se;r++)t+=(e[r]<16?"0":"")+e[r].toString(16);return t})();var se;const ce=e=>{const t=history[e];return function(){const r=t.apply(this,arguments),n=new Event(e);return window.dispatchEvent(n),r}},le=e=>{window.addEventListener("replaceState",(t=>e(t)),!0),window.addEventListener("pushState",(t=>e(t)),!0)},ue=e=>{window.addEventListener("popstate",(t=>e(t)),!0)},de=[25,50,75,90],me=e=>{history.pushState=ce("pushState"),history.replaceState=ce("replaceState"),(()=>{let e="";const t=()=>{const t=window.location.href;if(t===e)return;const{host:r,hostname:n,href:o,protocol:i,origin:a,port:s,pathname:l,search:u,hash:d}=window.location,m={host:r,hostname:n,href:o,protocol:i,origin:a,port:s,pathname:l,search:u,hash:d,title:document.title,language:navigator.language.substring(0,2),user_agent:navigator.userAgent,win_screen:`${window.screen.width}x${window.screen.height}`,doc_screen:`${document.documentElement.clientWidth}x${document.documentElement.clientHeight}`,referrer:document.referrer,type:c()};window.trackMonitor.track({data_type:"auto",event_type:"page_view",event_detail:m}),e=t},r=i(t,200);t(),ue((()=>{r()})),le((()=>{r()})),window.addEventListener("popstate",(()=>{r()}))})(),(()=>{let e=document.referrer,t=window.location.href,r=Date.now(),n=!0;const o=(n=!1)=>{if(window.location.href!==t||n){const n=Date.now()-r;n>200&&window.trackMonitor.track({data_type:"auto",event_type:"page_leave",event_detail:{url:t,referrer:e,duration:n}}),r=Date.now(),e=t,t=window.location.href}},a=i(o);o(),ue((()=>{a()})),le((()=>{a()})),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?n&&(n=!1,o(!0)):(n=!0,r=Date.now())})),window.addEventListener("beforeunload",(()=>{n&&(n=!1,o(!0))}),!0)})(),(()=>{const e=a((e=>{const t=function(e){if(!e)return;if(["A","INPUT","TEXTAREA","BUTTON"].includes(e.tagName))return e;if(e.hasAttribute("track-click"))return e;return e.closest("a, button, [track-click]")||void 0}(e.target);if(!t)return;const r={element_id:t.id,element_content:t.textContent?.trim().slice(0,200)||null,element_class_name:t.className||null,element_name:t.getAttribute("name")||null,element_type:t.tagName.toLowerCase(),element_path:s(t),scroll_width:document.documentElement.scrollWidth,scroll_height:document.documentElement.scrollHeight,pageX:e.pageX,pageY:e.pageY,ratio:window.devicePixelRatio||1};window.trackMonitor.track({data_type:"auto",event_type:"click",event_detail:r})}));window.addEventListener("click",e,!0)})(),!1!==e?.enableScroll&&(()=>{const e=new Set,t=a((()=>{const r=document.documentElement,n=r.scrollHeight-r.clientHeight;if(n<=0)return;const o=Math.round((window.scrollY||r.scrollTop)/n*100),i=de.filter((t=>o>=t&&!e.has(t)));i.length&&(i.forEach((t=>{e.add(t),window.trackMonitor.track({data_type:"auto",event_type:"scroll",event_detail:{scroll_depth:t}})})),e.has(90)&&window.removeEventListener("scroll",t))}),300);window.addEventListener("scroll",t,{passive:!0})})()};let pe=null,fe=null;const he="track-expose",ge="track-view",ye=e=>{try{fe=new WeakMap}catch(e){console.error("[TM]: create WeakMap fail: ",e)}const t=(e,t=!1)=>{const n=fe?.get(e);if(n&&!t)return;n&&(n.viewTimer&&clearTimeout(n.viewTimer),n.exposeTimer&&clearTimeout(n.exposeTimer));const o=e.dataset.durationView||500,i=e.dataset.durationExpose||500;fe?.set(e,{duration_view:o,duration_expose:i,viewTimer:null,exposeTimer:null}),pe?.observe(e),t&&function(e){if(!(e instanceof Element))return!1;if(!function e(t){if(!t)return!0;const r=window.getComputedStyle(t);return"none"!==r.display&&"hidden"!==r.visibility&&0!==parseFloat(r.opacity)&&e(t.parentElement)}(e))return!1;const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}(e)&&r(e)},r=t=>{const r=fe?.get(t);if(!r)return;const o=t.dataset.eventDetail,i=t.dataset.traceid??void 0,a=t.dataset.spm,s=t.hasAttribute("track-real-time"),c=t.hasAttribute(ge),l=t.hasAttribute(he);c&&l?r.exposeTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"view_expose",event_detail:o,track_real_time:s}),t.removeAttribute(ge),r.exposeTimer=null}),parseInt(r.duration_expose,10)):(c&&(r.viewTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"view",event_detail:o,track_real_time:s}),t.removeAttribute(ge),l&&r.exposeTimer||n(t),r.viewTimer=null}),parseInt(r.duration_view,10))),l&&(r.exposeTimer=window.setTimeout((()=>{e({spm:a,request_id:i,data_type:"auto",event_type:"expose",event_detail:o,track_real_time:s}),r.exposeTimer=null}),parseInt(r.duration_expose,10))))},n=e=>{const t=fe?.get(e);t&&(pe?.unobserve(e),t.viewTimer&&clearTimeout(t.viewTimer),t.exposeTimer&&clearTimeout(t.exposeTimer),fe?.delete(e))},o=e=>{e.forEach((e=>{const t=e.target,o=fe?.get(t);o&&(o.viewTimer&&(clearTimeout(o.viewTimer),o.viewTimer=null),o.exposeTimer&&(clearTimeout(o.exposeTimer),o.exposeTimer=null),e.isIntersecting&&(r(t),t.hasAttribute(ge)||t.hasAttribute(he)||n(t)))}))};pe=(()=>{let e=null;try{e=new IntersectionObserver(o,{root:null,threshold:.5})}catch(e){console.error("[TM]: create IntersectionObserver fail: ",e)}return e})();new Set([...document.querySelectorAll(`[${he}]`),...document.querySelectorAll(`[${ge}]`)]).forEach((e=>t(e))),new MutationObserver((e=>{e.forEach((e=>{if("attributes"===e.type&&e.target instanceof HTMLElement){const r=e.target,o=e.attributeName,i=["data-event-detail","data-traceid","data-spm","data-duration-view","data-duration-expose"];r.hasAttribute(he)||r.hasAttribute(ge)?i.includes(o)?t(r,!0):o!==he&&o!==ge||t(r,!1):n(r)}else"childList"===e.type&&(e.addedNodes.forEach((e=>{if(e instanceof HTMLElement)if(e.hasAttribute(he)||e.hasAttribute(ge))t(e);else{new Set([...e.querySelectorAll(`[${he}]`),...e.querySelectorAll(`[${ge}]`)]).forEach((e=>t(e)))}})),e.removedNodes.forEach((e=>{if(e instanceof HTMLElement){const t=fe?.get(e);if(t)n(e);else{new Set([...e.querySelectorAll(`[${he}]`),...e.querySelectorAll(`[${ge}]`)]).forEach((e=>n(e)))}}})))}))})).observe(document.body||document.documentElement,{attributes:!0,childList:!0,subtree:!0})},we=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;function ve(e){const t=e.match(we);if(!t)return{};return{filename:t[2],functionName:t[1]||"",lineno:parseInt(t[3],10)||void 0,colno:parseInt(t[4],10)||void 0}}function Te(e){try{const{stack:t}=e;if(!t)return[];const r=[];for(const e of t.split("\n").slice(1)){const t=ve(e);!t||t.filename?.includes("chrome-extension://")||t.filename?.includes("node_modules")||t.filename?.includes("<anonymous>")||r.push(t)}return r.slice(0,10)}catch(e){return[]}}const _e=new Set,be=(e,t)=>{if((r=S?.errorTraceRate??.5)<0||r>1?(console.warn("[TM]: probability should be between 0 and 1"),0):Math.random()<r){if(window.trackMonitor.track(t),_e.size>=1e3){const e=_e.values().next().value;void 0!==e&&_e.delete(e)}_e.add(e)}var r},Se=()=>{window.addEventListener("error",(e=>{(e=>{if(e instanceof ErrorEvent&&"Script error."===e.message){const t=p("js-Script error.");if(_e.has(t))return;return void be(t,{data_type:"error",event_type:"js",event_detail:{traceId:ae,msg:'Script error.(跨域脚本未加载 crossorigin 属性,无法获取堆栈;建议脚本加 crossorigin="anonymous")',target:"",stack:[],errorUuid:t,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno,crossorigin_missing:!0}}})}if("js"!==m(e))return;if((e=>{const t=e.error?.stack||"";return/chrome-extension:\/\//.test(t)})(e))return;const t=p(`js-${e.message}-${e.filename}`);if(_e.has(t))return;const r=Te(e.error),n={traceId:ae,msg:e.message,target:r[0]?`${r[0].filename?.split("?")[0]}:${r[0].lineno}:${r[0].colno}`:"",stack:r,errorUuid:t,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno}};be(t,{data_type:"error",event_type:"js",event_detail:n})})(e)}),!0)},Ee=()=>{window.addEventListener("error",(e=>{(e=>{if("resource"!==m(e))return;const t=e.target,r=p(`resource-${t.src}-${t.tagName}`);if(_e.has(r))return;const n={traceId:ae,msg:`加载${t.tagName}失败`,target:t.src?.split("?")[0],errorUuid:r,meta:{url:t.src,html:t.outerHTML,tagName:t.tagName}};be(r,{data_type:"error",event_type:"resource",event_detail:n})})(e)}),!0)},ke=()=>{window.addEventListener("unhandledrejection",(e=>(e=>{const t=e.reason?.message||e.reason,r=p(`unhandledrejection-${t}`);if(_e.has(r))return;const n={traceId:ae,msg:t,stack:Te(e.reason),errorUuid:r};be(r,{data_type:"error",event_type:"unhandledrejection",event_detail:n})})(e)),!0)},Me=()=>{const e=(e,t,r)=>{var n;if("string"!=typeof(n=e.url)||![S?.pushUrl,S?.authUrl,S?.realTimeUrl].filter((e=>!!e)).some((e=>0===n.indexOf(e))))if(t){const n=p(`http-${t}-${e.url}-${r}`);if(_e.has(n))return;const o={traceId:ae,errorType:t,msg:r,target:e.url.split("?")[0],errorUuid:n,request:e};be(n,{data_type:"error",event_type:"http",event_detail:o})}else if(e.status>=400){let r=e.statusText;const n=p(`http-${t="http_error"}-${e.url}-${r}`);if(_e.has(n))return;const o={traceId:ae,errorUuid:n,errorType:t,target:e.url.split("?")[0],msg:r,request:e};be(n,{data_type:"error",event_type:"http",event_detail:o})}};((e,t)=>{if("XMLHttpRequest"in window&&"function"==typeof window.XMLHttpRequest){const e=window.XMLHttpRequest;window.oXMLHttpRequest||(window.oXMLHttpRequest=e),window.XMLHttpRequest=function(){const r=new e,{open:n,send:o}=r;let i={};r.open=(e,t,o,a,s)=>{void 0===o&&(o=!0),i.method=e,i.url=t,n.call(r,e,t,o,a,s)},r.send=e=>{i.requestTime=(new Date).getTime(),o.call(r,e)};const a=(e,n)=>{const{status:o,statusText:a}=r,s=(new Date).getTime();i={...i,status:o,statusText:a,responseTime:s,duration:s-i.requestTime},"function"==typeof t&&t(i,e,n)};return r.addEventListener("loadend",(()=>a())),r.addEventListener("error",(()=>a("net_error","ERR_NETWORK"))),r.addEventListener("abort",(()=>a("cannel_request","ERR_CANCELED"))),r.addEventListener("timeout",(()=>a("timeout","ERR_NETWORK"))),r}}})(0,e),((e,t)=>{if("fetch"in window&&"function"==typeof window.fetch){const e=window.fetch;window.oFetch||(window.oFetch=e),window.fetch=async(r,n)=>{let o={};return o.method=n?.method||"",o.url=(r&&"string"!=typeof r?r?.url:r)||"",o.requestTime=(new Date).getTime(),e.call(window,r,n).then((async e=>{if("function"==typeof t){const r=e.clone(),n=(new Date).getTime();o={...o,status:r.status,statusText:r.statusText,responseTime:n,duration:n-o.requestTime},t(o)}return e})).catch((e=>{if("function"==typeof t){const r=(new Date).getTime();o={...o,responseTime:r,duration:r-o.requestTime},"AbortError"===e.name?t(o,"cannel_request","ERR_CANCELED"):t(o,"net_error","ERR_NETWORK")}return Promise.reject(e)}))}}})(0,e)};const xe=new WeakSet,Ae=e=>({form_id:e.id||null,form_class:"string"==typeof e.className?e.className:null,form_name:e.getAttribute("name")||null,form_action:e.getAttribute("action")||null,form_text:(e.textContent||"").trim().slice(0,200)||null});let Le=-1;const Ce=e=>{addEventListener("pageshow",(t=>{t.persisted&&(Le=t.timeStamp,e(t))}),!0)},Re=(e,t,r,n)=>{let o,i;return a=>{t.value>=0&&(a||n)&&(i=t.value-(o??0),(i||void 0===o)&&(o=t.value,t.delta=i,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,r),e(t)))}},Ie=e=>{requestAnimationFrame((()=>requestAnimationFrame((()=>e()))))},$e=()=>{const e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},Ne=()=>{const e=$e();return e?.activationStart??0},qe=(e,t=-1)=>{const r=$e();let n="navigate";return Le>=0?n="back-forward-cache":r&&(document.prerendering||Ne()>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}},Pe=new WeakMap;function Oe(e,t){return Pe.get(e)||Pe.set(e,new t),Pe.get(e)}class Ue{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const Be=(e,t,r={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){const n=new PerformanceObserver((e=>{Promise.resolve().then((()=>{t(e.getEntries())}))}));return n.observe({type:e,buffered:!0,...r}),n}}catch{}},ze=e=>{let t=!1;return()=>{t||(e(),t=!0)}};let De=-1;const Fe=new Set,je=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,He=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(const e of Fe)e();isFinite(De)||(De="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",He,!0))}},Je=()=>{if(De<0){const e=Ne(),t=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>"hidden"===t.name&&t.startTime>e))[0]?.startTime;De=t??je(),addEventListener("visibilitychange",He,!0),addEventListener("prerenderingchange",He,!0),Ce((()=>{setTimeout((()=>{De=je()}))}))}return{get firstHiddenTime(){return De},onHidden(e){Fe.add(e)}}},Ke=e=>{document.prerendering?addEventListener("prerenderingchange",(()=>e()),!0):e()},Ge=[1800,3e3],We=(e,t={})=>{Ke((()=>{const r=Je();let n,o=qe("FCP");const i=Be("paint",(e=>{for(const t of e)"first-contentful-paint"===t.name&&(i.disconnect(),t.startTime<r.firstHiddenTime&&(o.value=Math.max(t.startTime-Ne(),0),o.entries.push(t),n(!0)))}));i&&(n=Re(e,o,Ge,t.reportAllChanges),Ce((r=>{o=qe("FCP"),n=Re(e,o,Ge,t.reportAllChanges),Ie((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))})))}))},Xe=[.1,.25];let Qe=0,Ve=1/0,Ye=0;const Ze=e=>{for(const t of e)t.interactionId&&(Ve=Math.min(Ve,t.interactionId),Ye=Math.max(Ye,t.interactionId),Qe=Ye?(Ye-Ve)/7+1:0)};let et;const tt=()=>et?Qe:performance.interactionCount??0;let rt=0;class nt{u=[];l=new Map;m;p;v(){rt=tt(),this.u.length=0,this.l.clear()}L(){const e=Math.min(this.u.length-1,Math.floor((tt()-rt)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&"first-input"!==e.entryType)return;const t=this.u.at(-1);let r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((e,t)=>t.P-e.P)),this.u.length>10){const e=this.u.splice(10);for(const t of e)this.l.delete(t.id)}this.p?.(r)}}}const ot=e=>{const t=globalThis.requestIdleCallback||setTimeout;"hidden"===document.visibilityState?e():(e=ze(e),addEventListener("visibilitychange",e,{once:!0,capture:!0}),t((()=>{e(),removeEventListener("visibilitychange",e,{capture:!0})})))},it=[200,500],at=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const r=Je();Ke((()=>{"interactionCount"in performance||et||(et=Be("event",Ze,{type:"event",buffered:!0,durationThreshold:0}));let n,o=qe("INP");const i=Oe(t,nt),a=e=>{ot((()=>{for(const t of e)i.h(t);const t=i.L();t&&t.P!==o.value&&(o.value=t.P,o.entries=t.entries,n())}))},s=Be("event",a,{durationThreshold:t.durationThreshold??40});n=Re(e,o,it,t.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),r.onHidden((()=>{a(s.takeRecords()),n(!0)})),Ce((()=>{i.v(),o=qe("INP"),n=Re(e,o,it,t.reportAllChanges)})))}))};class st{m;h(e){this.m?.(e)}}const ct=[2500,4e3],lt=[800,1800],ut=e=>{document.prerendering?Ke((()=>ut(e))):"complete"!==document.readyState?addEventListener("load",(()=>ut(e)),!0):setTimeout(e)};function dt(){const e={ttfb:null,lcp:null,fp:null,fcp:null,connectionRtt:null,ttfbRequestTime:null,inp:null,cls:null,dcl:null,loadTime:null};((e,t={})=>{Ke((()=>{const r=Je();let n,o=qe("LCP");const i=Oe(t,st),a=e=>{t.reportAllChanges||(e=e.slice(-1));for(const t of e)i.h(t),t.startTime<r.firstHiddenTime&&(o.value=Math.max(t.startTime-Ne(),0),o.entries=[t],n())},s=Be("largest-contentful-paint",a);if(s){n=Re(e,o,ct,t.reportAllChanges);const r=ze((()=>{a(s.takeRecords()),s.disconnect(),n(!0)})),i=e=>{e.isTrusted&&(ot(r),removeEventListener(e.type,i,{capture:!0}))};for(const e of["keydown","click","visibilitychange"])addEventListener(e,i,{capture:!0});Ce((r=>{o=qe("LCP"),n=Re(e,o,ct,t.reportAllChanges),Ie((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))}))}}))})((t=>{e.lcp=u(t.value)}),{reportAllChanges:!0}),((e,t={})=>{const r=Je();We(ze((()=>{let n,o=qe("CLS",0);const i=Oe(t,Ue),a=e=>{for(const t of e)i.h(t);i.i>o.value&&(o.value=i.i,o.entries=i.o,n())},s=Be("layout-shift",a);s&&(n=Re(e,o,Xe,t.reportAllChanges),r.onHidden((()=>{a(s.takeRecords()),n(!0)})),Ce((()=>{i.i=0,o=qe("CLS",0),n=Re(e,o,Xe,t.reportAllChanges),Ie((()=>n()))})),setTimeout(n))})))})((t=>{e.cls=Math.round(1e4*t.value)/1e4}),{reportAllChanges:!0}),at((t=>{e.inp=u(t.value)}),{reportAllChanges:!0}),((e,t={})=>{let r=qe("TTFB"),n=Re(e,r,lt,t.reportAllChanges);ut((()=>{const o=$e();o&&(r.value=Math.max(o.responseStart-Ne(),0),r.entries=[o],n(!0),Ce((()=>{r=qe("TTFB",0),n=Re(e,r,lt,t.reportAllChanges),n(!0)})))}))})((t=>{e.ttfb=u(t.value)})),We((t=>{e.fcp=u(t.value)}));const t=()=>{(()=>{try{performance.getEntriesByType("paint").forEach((t=>{"first-paint"===t.name&&(e.fp=u(t.startTime))}))}catch(e){console.warn("[TM]: Failed to collect FP:",e)}try{const t=navigator.connection||navigator.mozConnection||navigator.webkitConnection;t&&void 0!==t.rtt&&(e.connectionRtt=t.rtt)}catch(e){console.warn("[TM]: Failed to collect Connection RTT:",e)}try{const t=performance.getEntriesByType("navigation")[0];if(t){const{responseStart:r,requestStart:n}=t;r>0&&n>0&&n<=r&&(e.ttfbRequestTime=u(r-n))}}catch(e){console.warn("[TM]: Failed to collect TTFB Request Time:",e)}try{const t=performance.getEntriesByType("navigation")[0];if(t){const{domContentLoadedEventEnd:r,loadEventEnd:n,fetchStart:o}=t;r>0&&o>0&&(e.dcl=u(r-o)),n>0&&o>0&&(e.loadTime=u(n-o))}}catch(e){console.warn("[TM]: Failed to collect DCL and Load Time:",e)}})(),window.trackMonitor.track({data_type:"performance",event_type:"metrics",event_detail:{traceId:ae,data:e}})};let r=0;const n=()=>{const e=Date.now();e-r<3e4||(r=e,t())};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",n),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&n()}))}const mt="__tengence_sdk",pt=e=>{if("undefined"!=typeof window&&window.trackMonitor&&window.trackMonitor[mt])return console.warn("[TM]: init 已调用过,复用现有实例(如需重建请刷新页面)"),window.trackMonitor;const{client:t,beforeClose:r}=ie(e),n=T,o=(e,t)=>n?n.dataTypes.includes(e):t,i=o("auto",!1!==e.traceBehavior);var a;return i&&(ye(t.track),!1!==e.enableScroll&&me({enableScroll:e.enableScroll})),i&&!1!==e.enableFormTrack&&(a=t.track,document.addEventListener("focusin",(e=>{const t=e.target;if(!(r=t)||"INPUT"!==r.tagName&&"SELECT"!==r.tagName&&"TEXTAREA"!==r.tagName)return;var r;const n=t.closest("form");n&&!xe.has(n)&&(xe.add(n),a({data_type:"auto",event_type:"form_start",event_detail:Ae(n)}))}),!0),document.addEventListener("submit",(e=>{const t=e.target;if(!t||"FORM"!==t.tagName)return;const r=e.submitter;a({data_type:"auto",event_type:"form_submit",event_detail:{...Ae(t),submitter_id:r?.id||null,submitter_text:(r?.textContent||"").trim().slice(0,200)||null}})}),!0)),o("error",!1!==e.traceError)&&(Se(),Ee(),ke(),Me()),o("performance",!1!==e.tracePerformance)&&l((()=>{!function(){const e=window.performance||window.msPerformance;if(!e)return{dnsLookupTime:null,tcpConnectTime:null,ttfb:null,transferTime:null,domParseTime:null,domCompleteTime:null,loadEventTime:null,totalPageLoad:null};const t=e.getEntriesByType&&"function"==typeof e.getEntriesByType?e.getEntriesByType("navigation"):void 0,r=Array.isArray(t)?t[0]:void 0;let n=null;if(r)n=r;else{const t=e.timing;t&&(n={startTime:0,domainLookupStart:t.domainLookupStart,domainLookupEnd:t.domainLookupEnd,connectStart:t.connectStart,connectEnd:t.connectEnd,requestStart:t.requestStart,responseStart:t.responseStart,responseEnd:t.responseEnd,domInteractive:t.domInteractive,domComplete:t.domComplete,loadEventEnd:t.loadEventEnd,fetchStart:t.fetchStart},!n.requestStart&&t.fetchStart&&(n.requestStart=t.fetchStart))}const o={dnsLookupTime:n?u(n.domainLookupEnd-n.domainLookupStart):null,tcpConnectTime:n?u(n.connectEnd-n.connectStart):null,ttfb:n?u(n.responseStart-(n.requestStart??n.fetchStart??0)):null,transferTime:n?u(n.responseEnd-n.responseStart):null,domParseTime:n?u(n.domInteractive-n.responseEnd):null,domCompleteTime:n?u(n.domComplete-n.domInteractive):null,loadEventTime:n?u(n.loadEventEnd-(n.domComplete??0)):null,totalPageLoad:n?u((n.loadEventEnd??performance.now())-(n.startTime??0)):null};window.trackMonitor.track({data_type:"performance",event_type:"navigation_timing",event_detail:{traceId:ae,data:o}})}(),function(){const e=window.performance||window.msPerformance;if(!e)return[];const t=[];if(e.getEntriesByType){const r=(e.getEntriesByType("resource")||[]).map((e=>{const t="number"==typeof e.redirectEnd&&"number"==typeof e.redirectStart?u(e.redirectEnd-e.redirectStart):null,r="number"==typeof e.domainLookupEnd&&"number"==typeof e.domainLookupStart?u(e.domainLookupEnd-e.domainLookupStart):null,n="number"==typeof e.connectEnd&&"number"==typeof e.connectStart?u(e.connectEnd-e.connectStart):null,o="number"==typeof e.requestStart&&"number"==typeof e.fetchStart?u(e.requestStart-e.fetchStart):null,i="number"==typeof e.responseStart&&"number"==typeof e.requestStart?u(e.responseStart-e.requestStart):null,a="number"==typeof e.responseEnd&&"number"==typeof e.responseStart?u(e.responseEnd-e.responseStart):null,s="number"==typeof e.duration?u(e.duration):null,c="number"==typeof e.startTime?u(e.startTime):null,l="number"==typeof e.transferSize&&isFinite(e.transferSize)&&e.transferSize>=0?Math.round(e.transferSize):null,d="number"==typeof e.encodedBodySize&&isFinite(e.encodedBodySize)&&e.encodedBodySize>=0?Math.round(e.encodedBodySize):null,m="number"==typeof e.decodedBodySize&&isFinite(e.decodedBodySize)&&e.decodedBodySize>=0?Math.round(e.decodedBodySize):null;return{name:e.name,initiatorType:e.initiatorType||"",startTime:c,duration:s,redirectTime:t,cacheTime:o,dnsTime:r,connectTime:n,requestTime:i,responseTime:a,transferSize:l,encodedBodySize:d,decodedBodySize:m}}));r.sort(((e,t)=>(t.duration??0)-(e.duration??0)));const n=S?.resourceFlowLimit??15;if(0===n)return;for(let e=0;e<Math.min(n,r.length);e++)t.push(r[e]);if(!t.length)return}window.trackMonitor.track({data_type:"performance",event_type:"resource_flow",event_detail:{traceId:ae,data:t}})}(),dt()})),l((()=>{r()})),window.trackMonitor[mt]=!0,window.trackMonitor};export{pt as default};
|
|
@@ -34,6 +34,8 @@ export interface BaseOptions {
|
|
|
34
34
|
enableTracking?: boolean;
|
|
35
35
|
respectGpc?: boolean;
|
|
36
36
|
requestTimeout?: number;
|
|
37
|
+
configUrl?: string;
|
|
38
|
+
configTtl?: number;
|
|
37
39
|
sanitize?: SanitizeOptions | false;
|
|
38
40
|
beforeSend?: (events: ReportData[]) => ReportData[];
|
|
39
41
|
onDrop?: (events: ReportData[], reason: DropReason) => void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TrackSDK={})}(this,(function(e){"use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},n.apply(this,arguments)};function r(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function c(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}u((r=r.apply(e,t||[])).next())}))}function o(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function c(c){return function(u){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&c[0]?r.return:c[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,c[1])).done)return o;switch(r=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,r=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){i.label=c[1];break}if(6===c[0]&&i.label<o[1]){i.label=o[1],o=c;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(c);break}o[2]&&i.ops.pop(),i.trys.pop();continue}c=t.call(e,i)}catch(e){c=[6,e],r=0}finally{n=o=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,u])}}}function i(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function c(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var u=function(e){function n(t,n){var r=e.call(this,n||"[TM]: Auth error ".concat(t))||this;return Object.defineProperty(r,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.name="AuthError",r.status=t,r}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(n,e),n}(Error),l=function(e){var t=e.method,n=e.url,r=e.data,o=e.headers,i=void 0===o?{}:o,a=e.withCredentials,c=void 0!==a&&a,u=e.timeoutMs;return new Promise((function(e,o){var a=new XMLHttpRequest;a.open(t,n,!0),u&&(a.timeout=u),Object.keys(i).forEach((function(e){a.setRequestHeader(e,i[e])})),a.withCredentials=!!c,a.onreadystatechange=function(){if(4===a.readyState)if(a.status>=200&&a.status<300)try{var t=JSON.parse(a.responseText);e(t)}catch(e){o(e)}else{var n=new Error("[TM]: Request failed with status ".concat(a.status));n.status=a.status,o(n)}},a.onerror=function(){o(new Error("[TM]: Network error"))},a.ontimeout=function(){var e=new Error("[TM]: Request timeout");e.timeout=!0,o(e)},"POST"===t&&r?a.send(r):a.send()}))},s=function(e,t,r){if(!r)return fetch(e,t);var o=new AbortController,i=setTimeout((function(){return o.abort()}),r);return fetch(e,n(n({},t),{signal:o.signal})).catch((function(e){if(e&&"AbortError"===e.name){var t=new Error("[TM]: Request timeout");throw t.timeout=!0,t}throw e})).finally((function(){return clearTimeout(i)}))},d=function(e,t,n,r){var o={"Content-Type":"application/json"};n&&(o.Authorization="Bearer ".concat(n));var i=function(){return l({method:"POST",url:e,data:JSON.stringify(t),headers:o,withCredentials:!0,timeoutMs:r})};return"function"!=typeof fetch?i():s(e,{method:"POST",keepalive:!0,credentials:"include",headers:o,body:JSON.stringify(t)},r).then((function(e){if(401===e.status||403===e.status)throw new u(e.status,"[TM]: Auth error ".concat(e.status));if(429===e.status){(r=new Error("[TM]: Request throttled with status 429")).status=429;var t=e.headers.get("Retry-After");if(t){var n=parseInt(t,10);isNaN(n)||(r.retryAfter=1e3*n)}throw r}var r;if(!e.ok)throw(r=new Error("[TM]: Request failed with status ".concat(e.status))).status=e.status,r;return e.json()})).catch((function(e){if(e instanceof u)throw e;if(e&&e.status)throw e;return i()}))},f=function(e,t,n){var r={};t&&(r.Authorization="Bearer ".concat(t));var o=function(){return l({method:"GET",url:e,headers:r,withCredentials:!0,timeoutMs:n})};return"function"!=typeof fetch?o():s(e,{method:"GET",credentials:"include",headers:r},n).then((function(e){if(401===e.status||403===e.status)throw new u(e.status,"[TM]: Auth error ".concat(e.status));if(!e.ok){var t=new Error("[TM]: Request failed with status ".concat(e.status));throw t.status=e.status,t}return e.json()})).catch((function(e){if(e instanceof u)throw e;if(e&&e.status)throw e;return o()}))},v=window.requestIdleCallback||window.requestAnimationFrame||function(e){return setTimeout(e,17)};function p(e,t,n){void 0===t&&(t=150),void 0===n&&(n=!1);var r=null;return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=this,c=n&&!r;r&&clearTimeout(r),r=setTimeout((function(){r=null,n||e.apply(a,o)}),t),c&&e.apply(a,o)}}var m=function(e,t){void 0===t&&(t=300);var n=0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var i=Date.now();i-n>=t&&(n=i,e.apply(this,r))}};function h(e,t){if(void 0===t&&(t=""),!e)return t;var n=e.parentElement,r=e.id,o=e.tagName.toLowerCase(),i=t?">".concat(t):"";return n&&n!==document.documentElement&&n!==document.body?r?"#".concat(r).concat(i):h(n,"".concat(o).concat(i)):"".concat(o).concat(i)}var y=function(){var e,t;if(null===(e=window.performance)||void 0===e?void 0:e.navigation)return performance.navigation.type;if(null===(t=window.performance)||void 0===t?void 0:t.getEntriesByType){var n=performance.getEntriesByType("navigation");if(n.length>0)return n[0].type}return 255},g=function(e){"prerendering"in document&&document.prerendering?function(e){"prerendering"in document&&document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()}((function(){return g(e)})):"complete"!==(null===document||void 0===document?void 0:document.readyState)?addEventListener("load",(function(){return g(e)}),!0):setTimeout(e)};function w(e){return"number"!=typeof e||!isFinite(e)||e<0?null:Math.round(100*e)/100}function T(){var e=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(var t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;var n="";for(t=0;t<16;t++)n+=(e[t]<16?"0":"")+e[t].toString(16);return n}var b=function(e){return e instanceof ErrorEvent?"Script error."===e.message?"cors":"js":"resource"},_=function(e){return function(e){for(var t=5381,n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(16).padStart(8,"0")}(e)+function(e){for(var t=5381,n=e.length-1;n>=0;n--)t=((t<<5)+t^e.charCodeAt(n))>>>0;return t.toString(16).padStart(8,"0")}(e)};var S,E,k,x={view:"#3b82f6",click:"#06b6d4",expose:"#8b5cf6",enter:"#10b981",leave:"#f59e0b",stay:"#84cc16",cart:"#ec4899",buy:"#ef4444",pay:"#dc2626",default:"#6b7280"},A={view:"👁️",click:"👆",expose:"✨",enter:"🚪",leave:"👋",stay:"⏱️",cart:"🛒",buy:"💰",pay:"💳",default:"📊"},M={common:"#3b82f6",behavior:"#10b981",performance:"#f59e0b",error:"#ef4444",custom:"#8b5cf6",default:"#6b7280"},L=function(e,t){t.forEach((function(t,r){var o=t.event_type||"unknown",i=t.data_type||"auto",a=function(e){return x[e]||x.default}(o),c=function(e){return M[e]||M.default}(i),u=function(e){return A[e]||A.default}(o),l=t.event_detail;if("string"==typeof l)try{l=JSON.parse(l)}catch(e){}console.groupCollapsed("%c".concat(u," [TM-").concat(e,"] %c").concat(i.toUpperCase(),"%c → %c").concat(o.toUpperCase(),"%c #").concat(r+1),"color: #6b7280; font-weight: bold;","color: ".concat(c,"; font-weight: bold; background: ").concat(c,"20; padding: 2px 6px; border-radius: 3px;"),"color: #6b7280;","color: ".concat(a,"; font-weight: bold; background: ").concat(a,"20; padding: 2px 6px; border-radius: 3px;"),"color: #6b7280; font-weight: normal;");var s=n(n({},t),{event_detail:l});console.log("%c"+JSON.stringify(s,null,2),"color: #6b7280; font-family: monospace; font-size: 11px; line-height: 1.5;"),console.groupEnd()})),console.log("%c✅ [TM] 本次通过 ".concat(e," 上报 ").concat(t.length," 条埋点数据"),"color: #10b981; font-weight: bold; font-size: 12px; padding: 4px 8px; background: #10b98120; border-radius: 4px; border-left: 3px solid #10b981;")},C=["auto","behavior","performance","error"],I="tengence_sdk_config",R=null,O=function(e,t){if(t)return t;if(e){var n=/^(https?:\/\/[^/]+)/.exec(e);if(n)return"".concat(n[1],"/v1/track/config")}return"".concat("https://api.tengence.com","/v1/track/config")},P=function(e,t,n){return r(void 0,void 0,void 0,(function(){var r,i,a,c,u;return o(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,f(e,t,n)];case 1:return r=o.sent(),(i=null!==(u=null==r?void 0:r.data)&&void 0!==u?u:r)&&Array.isArray(i.dataTypes)&&0!==i.dataTypes.length?(a={appId:i.appId,dataTypes:i.dataTypes.filter((function(e){return C.includes(e)})),idFieldName:"string"==typeof i.idFieldName&&i.idFieldName?i.idFieldName:"event_id",configVersion:i.configVersion,updatedAt:i.updatedAt,fetchedAt:Date.now()},function(e){try{localStorage.setItem(I,JSON.stringify(e))}catch(e){}}(a),R=a,[2,a]):("undefined"!=typeof console&&console.warn("[TM]: 远程配置返回空,沿用缓存/默认配置"),[2,null]);case 2:return c=o.sent(),"undefined"!=typeof console&&console.warn("[TM]: 拉取远程配置失败,沿用缓存/默认配置",c),[2,null];case 3:return[2]}}))}))},N=void 0,q="TRACK_MONITOR_DATA",j="MONITOR_REAL_TIME_DATA",U="TRACK_MONITOR_USER",B="tengence_device_id",D="tengence_register_properties",z="TRACK_MONITOR_LOGGER",F="tengence_tracking_enabled",H=2e3,J="tengence_access_token",K=null,G=null,W=function(e){return(t=e,n={},r=null==N?void 0:N.requestTimeout,o={"Content-Type":"application/json"},i=function(){return l({method:"POST",url:t,data:JSON.stringify(n),headers:o,withCredentials:!0,timeoutMs:r})},"function"!=typeof fetch?i():s(t,{method:"POST",credentials:"include",headers:o,body:JSON.stringify(n)},r).then((function(e){if(!e.ok){var t=new Error("[TM]: Request failed with status ".concat(e.status));throw t.status=e.status,t}return e.json()})).catch((function(e){if(e&&e.status)throw e;return i()}))).then((function(e){var t=e&&e.data,n=t&&t.accessToken,r=t&&t.accessExpAt;if(!n||"number"!=typeof r)throw new Error("[TM]: authUrl 响应缺少 accessToken/accessExpAt");return function(e,t){K={token:e,expAt:t};try{localStorage.setItem(J,JSON.stringify({token:e,expAt:t}))}catch(e){}}(n,r),n}));var t,n,r,o,i},X=function(e){var t,n=function(){if(K)return K;try{var e=localStorage.getItem(J);if(!e)return null;var t=JSON.parse(e);if(t&&"string"==typeof t.token&&t.token&&"number"==typeof t.expAt)return K={token:t.token,expAt:t.expAt}}catch(e){}return null}();return(t=n)&&t.token.length>0&&t.expAt-6e4>Date.now()?Promise.resolve(n.token):(G||(G=W(e).catch((function(e){throw e})).finally((function(){G=null}))),G)},Q={timer:null,promise:null},V={timer:null,promise:null},$=function(e){var t=JSON.stringify(e);return(new TextEncoder).encode(t).length/1024},Y=null,Z=function(){if(Y)return Y;try{var e=localStorage.getItem(D),t=e?JSON.parse(e):{};return Y=t,t}catch(e){return console.error("[TM]: get register properties fail: ",e),{}}},ee=function(e){Y=e;try{localStorage.setItem(D,JSON.stringify(e))}catch(e){console.error("[TM]: save register properties fail: ",e)}},te=function(e){if(e&&"object"==typeof e&&!Array.isArray(e)){var t=n(n({},Z()),e),r=Object.keys(t);if(r.length>50){var o={};return r.slice(0,50).forEach((function(e){o[e]=t[e]})),console.warn("[TM]: register properties exceed max ".concat(50," keys, extra keys dropped")),void ee(o)}ee(t)}else console.error("[TM]: registerGlobalProperties props must be a plain object")},ne=function(e){var t=document.cookie.match(new RegExp("(?:^|;\\s*)"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):void 0},re=function(e){document.cookie="".concat(B,"=").concat(encodeURIComponent(e),"; Max-Age=63072000; Path=/; Secure; SameSite=Lax")},oe=function(){if(S)return S;try{var e=localStorage.getItem(B);if(e)return ne(B)||re(e),S=e;var t=ne(B);if(t){try{localStorage.setItem(B,t)}catch(e){}return S=t}e=T();try{localStorage.setItem(B,e)}catch(e){}return re(e),S=e}catch(e){return void console.error("[TM]: get or create device id fail: ",e)}},ie="tengence_session_id",ae=function(){try{var e=sessionStorage.getItem(ie),t=e?JSON.parse(e):null,n=Date.now();return!t||!t.id||n-t.lastActiveAt>18e5?(t={id:T(),lastActiveAt:n},sessionStorage.setItem(ie,JSON.stringify(t))):(t.lastActiveAt=n,sessionStorage.setItem(ie,JSON.stringify(t))),t.id}catch(e){return}},ce=function(e,t){var n,r;try{var o=new URL(e,location.href);if(!o.searchParams.toString())return e;if(t&&t.length){var a=[];try{for(var c=i(t),u=c.next();!u.done;u=c.next()){var l=u.value,s=o.searchParams.get(l);null!==s&&a.push("".concat(l,"=").concat(encodeURIComponent(s)))}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}o.search=a.length?"?".concat(a.join("&")):""}else o.search="";return o.toString()}catch(t){return e}},ue=function(e,t,n){var r,o;if("string"==typeof e)return t>0&&e.length>t?e.slice(0,t)+"...[truncated]":e;if(Array.isArray(e))return e.map((function(e){return ue(e,t,n)}));if(e&&"object"==typeof e){var a={};try{for(var c=i(Object.keys(e)),u=c.next();!u.done;u=c.next()){var l=u.value,s=e[l];"string"==typeof s&&/(^|_)url$|(^|_)href$|^referrer$/i.test(l)&&/^https?:\/\//i.test(s)?a[l]=ce(s,n):a[l]=ue(s,t,n)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(o=c.return)&&o.call(c)}finally{if(r)throw r.error}}return a}return e},le=function(e){var t,r={page_url:location.href,hostname:window.location.hostname||window.location.host,os:window.navigator.platform,user_id:localStorage.getItem(U)||void 0,user_agent:window.navigator.userAgent,screen_width:window.screen.width,screen_height:window.screen.height,lib_version:"1.2.2",lib_type:"js",event_time:Date.now(),timezone_offset:(new Date).getTimezoneOffset().toString()},o=null==N?void 0:N.sanitize;try{t="string"==typeof e.event_detail?e.event_detail:JSON.stringify(o&&(o.maxTextLength>0||o.stripQuery)?ue(e.event_detail,o.maxTextLength,o.preserveQueryKeys):e.event_detail)}catch(e){return ve("serialize_failed","事件 event_detail 序列化失败(循环引用/BigInt?),该事件丢弃",{error:e}),void console.warn("[TM]: event_detail 序列化失败,该事件丢弃",e)}return n(n({session_id:e.session_id||((null==N?void 0:N.enableAutoSessionId)?ae():void 0),request_id:e.request_id,event_id:e.event_id||T(),spm:e.spm,data_type:e.data_type||"behavior",event_type:e.event_type,event_detail:t},r),{page_url:o&&o.stripQuery?ce(r.page_url,o.preserveQueryKeys):r.page_url,device_id:oe(),register_properties:JSON.stringify(Z()),platform:e.platform||E})},se=function(){try{return"true"===localStorage.getItem(z)}catch(e){return!1}},de=function(e,t,n,r,o){return void 0===e?t:"number"!=typeof e||Number.isNaN(e)||e<n||e>r?(console.warn("[TM]: 配置 ".concat(o,"=").concat(e," 非法,回退默认值 ").concat(t)),t):e},fe=function(e,t){var n;try{null===(n=null==N?void 0:N.onDrop)||void 0===n||n.call(N,e,t)}catch(e){}},ve=function(e,t,n){var r;(null==N?void 0:N.isLogger)&&console.error("[TM]: ".concat(t));try{null===(r=null==N?void 0:N.onError)||void 0===r||r.call(N,{code:e,message:t,context:n})}catch(e){}},pe=function(){try{var e=localStorage.getItem(F);return null===e||"1"===e}catch(e){return!0}},me=function(e){var t,a,c,l,s,f,p,m,h,y,g,w=e.apiKey,T=void 0,b=/Android|iPhone|iPad|iPod|Mobile/i.test(window.navigator.userAgent);E=e.platform||(b?"h5":"web");var _=(N={pushUrl:e.pushUrl||"https://api.tengence.com/v1/push/event",authUrl:e.authUrl,realTimeUrl:e.realTimeUrl,cacheNumber:de(e.cacheNumber,100,1,1/0,"cacheNumber"),reportInterval:de(e.reportInterval,5e3,100,1/0,"reportInterval"),realTimeReportInterval:de(e.realTimeReportInterval,200,100,1/0,"realTimeReportInterval"),maxCacheSize:de(e.maxCacheSize,56,1,1/0,"maxCacheSize"),maxRetries:de(e.maxRetries,10,0,1/0,"maxRetries"),isLogger:null!==(t=e.isLogger)&&void 0!==t?t:se(),errorTraceRate:de(e.errorTraceRate,.5,0,1,"errorTraceRate"),resourceFlowLimit:de(e.resourceFlowLimit,15,0,200,"resourceFlowLimit"),traceBehavior:null===(a=e.traceBehavior)||void 0===a||a,tracePerformance:null===(c=e.tracePerformance)||void 0===c||c,traceError:null===(l=e.traceError)||void 0===l||l,sanitize:!1===e.sanitize?{stripQuery:!1,maxTextLength:0,preserveQueryKeys:[]}:{stripQuery:null!==(f=null===(s=e.sanitize)||void 0===s?void 0:s.stripQuery)&&void 0!==f&&f,maxTextLength:de(null===(p=e.sanitize)||void 0===p?void 0:p.maxTextLength,0,0,1/0,"sanitize.maxTextLength"),preserveQueryKeys:(null===(m=e.sanitize)||void 0===m?void 0:m.preserveQueryKeys)||[]},enableAutoSessionId:null!==(h=e.enableAutoSessionId)&&void 0!==h&&h,enableTracking:null!==(y=e.enableTracking)&&void 0!==y?y:pe(),respectGpc:null===(g=e.respectGpc)||void 0===g||g,requestTimeout:de(e.requestTimeout,1e4,1e3,6e4,"requestTimeout"),configUrl:O(e.pushUrl,e.configUrl),configTtl:de(e.configTtl,3e5,6e4,864e5,"configTtl"),beforeSend:e.beforeSend,onDrop:e.onDrop,onError:e.onError}).pushUrl,S=N.authUrl,k=N.realTimeUrl,x=N.cacheNumber,A=N.reportInterval,M=N.realTimeReportInterval,C=N.maxCacheSize,B=N.maxRetries;w||S||(console.error("[TM]: 未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"),ve("init_missing_credential","未配置 apiKey 或 authUrl,SDK 无法获取上报凭证,数据将不会上报。请配置 apiKey(直连)或 authUrl(自动换取 accessToken),或调用 setToken 注入 accessToken。"));var D=function(){try{var e=localStorage.getItem(I);if(!e)return null;var t=JSON.parse(e);return Array.isArray(t.dataTypes)&&0!==t.dataTypes.length?t:null}catch(e){return null}}();D&&(R=D),v((function(){return r(void 0,void 0,void 0,(function(){var e,t,n;return o(this,(function(r){switch(r.label){case 0:return r.trys.push([0,7,,8]),(t=w||T)?[3,4]:S?[4,X(S)]:[3,2];case 1:return n=r.sent(),[3,3];case 2:n=void 0,r.label=3;case 3:t=n,r.label=4;case 4:return(e=t)?[4,P(N.configUrl,e,N.requestTimeout)]:[3,6];case 5:r.sent(),r.label=6;case 6:return[3,8];case 7:return r.sent(),[3,8];case 8:return[2]}}))}))}));var G={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},W={retryCount:0,nextRetryAt:0,retryExhausted:!1,halveBatch:!1},Y=function(e){try{localStorage.setItem(U,e)}catch(e){console.error("[TM]: monitor bind user fail: ",e)}},Z=function(){localStorage.removeItem(U)},ee={},ne={},re=new Set,oe=null,ie=function(){null!==oe&&(clearTimeout(oe),oe=null),re.size&&(re.forEach((function(e){try{localStorage.setItem(e,JSON.stringify(ee[e]||[]))}catch(t){ve("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),本次数据仅保留内存",{key:e,error:t})}})),re.clear())},ae=function(e){if(ee[e])return ee[e];var t=[];try{t=JSON.parse(localStorage.getItem(e)||"[]")}catch(t){ve("queue_read_failed","读取本地缓存队列失败,按空队列处理",{key:e,error:t})}return ee[e]=t,ne[e]=t.reduce((function(e,t){return e+$(t)}),0),ee[e]},ce=function(e,t){re.delete(e),ee[e]=t,ne[e]=t.reduce((function(e,t){return e+$(t)}),0);try{localStorage.setItem(e,JSON.stringify(t))}catch(t){ve("queue_write_failed","写入本地缓存队列失败(隐私模式/容量满?),队列清空处理",{key:e,error:t});try{localStorage.setItem(e,"[]")}catch(t){ve("localstorage_unavailable","localStorage 不可用,本次数据仅保留内存",{key:e,error:t})}}},ue=function(e){T=e},me=function(e,t,n){return void 0===n&&(n=!1),r(void 0,void 0,void 0,(function(){var i,a,c,l,s,f,v;return o(this,(function(p){switch(p.label){case 0:i=e&&k?k:_,p.label=1;case 1:return p.trys.push([1,6,,7]),(c=w||T)?[3,5]:S?[4,X(S)]:[3,3];case 2:return l=p.sent(),[3,4];case 3:l=void 0,p.label=4;case 4:c=l,p.label=5;case 5:return a=c,[3,7];case 6:throw s=p.sent(),ve("token_fetch_failed","从 authUrl 获取 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:S,error:s}),s;case 7:if(!a)throw ve("init_missing_credential","未配置 apiKey/authUrl 且未注入 accessToken,本次数据未上报(保留缓存队列待重试)"),new Error("[TM]: credential missing, skip report");return(null==N?void 0:N.isLogger)&&L(e?"RealTimeFetch":"Fetch",t),f=(null==N?void 0:N.beforeSend)?function(){var e;try{e=N.beforeSend(t)}catch(e){ve("before_send_failed","beforeSend 钩子抛错,本次按原始数据发送",{error:e})}return Array.isArray(e)?e:t}():t,v=n||null==N?void 0:N.requestTimeout,[2,d(i,{data:f},a,v).catch((function(e){return r(void 0,void 0,void 0,(function(){var t,n;return o(this,(function(r){switch(r.label){case 0:return t=null==e?void 0:e.status,e instanceof u||401===t||403===t?w||T||!S?[3,2]:(function(){K=null;try{localStorage.removeItem(J)}catch(e){}}(),[4,X(S).catch((function(){}))]):[3,2];case 1:if(n=r.sent())return[2,d(i,{data:f},n,v)];ve("token_invalid","上报 401/403 且刷新 accessToken 失败,本批暂不上报(保留队列待重试)",{authUrl:S}),r.label=2;case 2:throw e}}))}))}))]}}))}))},he=function(e,t){var n=new Set(t.filter((function(e){return!!e})));if(n.size){var r=ae(e);if(r.length){var o=r.filter((function(e){return e.event_id&&!n.has(e.event_id)}));o.length!==r.length&&ce(e,o)}}},ye=function(e,t,n){void 0===n&&(n=0);var r=(t?M:A)*Math.pow(2,e)*(.8+.4*Math.random()),o=Math.min(r,6e4);return Math.max(o,n)},ge=function(e,t){var n=$(t);if(n>=64)return fe([t],"item_too_large"),void console.warn("[TM]: 单条事件超过体积上限(".concat(64,"KB),丢弃该条"));var r=ae(e);if(r.unshift(t),ne[e]+=n,r.length>H){var o=r.length-H,i=r.splice(r.length-o,r.length);ne[e]=r.reduce((function(e,t){return e+$(t)}),0),fe(i,"queue_overflow"),console.warn("[TM]: 队列超过上限(".concat(H,"条),丢弃最旧 ").concat(o," 条"))}!function(e){re.add(e),null===oe&&(oe=setTimeout((function(){oe=null,ie()}),200))}(e),we(e,ne[e]>=C)},we=function(e,t,n){if(void 0===t&&(t=!1),void 0===n&&(n=!1),null==N?void 0:N.enableTracking){var a=ae(e);if(a.length){var c=function(e){return e===j}(e),u=c?V:Q,l=function(e){return e?W:G}(c);if(l.halveBatch&&a.length>1&&(a=a.slice(0,Math.ceil(a.length/2))),!l.retryExhausted)if(Date.now()<l.nextRetryAt)null===u.timer&&(u.timer=setTimeout((function(){u.timer=null,we(e)}),l.nextRetryAt-Date.now()));else if(0!==l.retryCount||(a.length>=x||t)){if(null!==u.timer&&(clearTimeout(u.timer),u.timer=null),u.promise)return;u.promise=function(e,t,n,a,c){return void 0===c&&(c=!1),r(void 0,void 0,void 0,(function(){var r,u,l,s,d,f,v,p,m,h,y,g,w,T,b,_,S,E;return o(this,(function(k){switch(k.label){case 0:r=[],u=[],l=0;try{for(s=i(t),d=s.next();!d.done;d=s.next())f=d.value,v=1024*$(f),u.length&&l+v>65536&&(r.push(u),u=[],l=0),u.push(f),l+=v}catch(e){w={error:e}}finally{try{d&&!d.done&&(T=s.return)&&T.call(s)}finally{if(w)throw w.error}}u.length&&r.push(u),p=function(t){var r,i,a,u,l;return o(this,(function(o){switch(o.label){case 0:return[4,me(n,t,c)];case 1:return r=o.sent(),i=null===(S=null==r?void 0:r.data)||void 0===S?void 0:S.accepted_ids,a=null===(E=null==r?void 0:r.data)||void 0===E?void 0:E.rejected_ids,Array.isArray(i)?(he(e,i),Array.isArray(a)&&a.length&&(u=new Set(a),he(e,a),l=t.filter((function(e){return e.event_id&&u.has(e.event_id)})),l.length&&fe(l,"server_rejected"),console.warn("[TM]: 服务端校验拒绝 ".concat(a.length," 条(永久性拒绝),已从队列移除并通知 onDrop")))):(he(e,t.map((function(e){return e.event_id}))),(null==N?void 0:N.isLogger)&&console.warn("[TM]: 响应缺少 accepted_ids,按整批成功清理")),[2]}}))},k.label=1;case 1:k.trys.push([1,6,7,8]),m=i(r),h=m.next(),k.label=2;case 2:return h.done?[3,5]:(y=h.value,[5,p(y)]);case 3:k.sent(),k.label=4;case 4:return h=m.next(),[3,2];case 5:return[3,8];case 6:return g=k.sent(),b={error:g},[3,8];case 7:try{h&&!h.done&&(_=m.return)&&_.call(m)}finally{if(b)throw b.error}return[7];case 8:return a.retryCount=0,a.nextRetryAt=0,a.halveBatch=!1,[2]}}))}))}(e,a,c,l,n).catch((function(e){!function(e,t,n,r,o){(null==t?void 0:t.timeout)&&ve("request_timeout","上报请求超时,数据保留队列按退避重试",{url:n&&k?k:_,timeoutMs:null==N?void 0:N.requestTimeout});var i=null==t?void 0:t.status;if(413!==i){if(i&&i>=400&&i<500&&401!==i&&403!==i&&408!==i&&410!==i&&429!==i)return r.retryExhausted=!0,fe(o,"rejected_4xx"),void console.warn("[TM]: 批次提交被服务端拒绝(HTTP ".concat(i,"),数据保留在队列并暂停自动重试"));if(r.retryCount++,r.retryCount>B)return r.retryExhausted=!0,fe(o,"retries_exhausted"),void console.warn("[TM]: 重试次数已达上限(".concat(B,"),数据保留在队列(不丢弃),待下次会话或手动触发重试"));var a=429===i&&(null==t?void 0:t.retryAfter)||0;r.nextRetryAt=Date.now()+ye(r.retryCount,n,a),console.error("[TM]: send report fail, retryCount: ".concat(r.retryCount,", next retry after ").concat(Math.round((r.nextRetryAt-Date.now())/1e3),"s"))}else o.length>1?(r.halveBatch=!0,r.retryCount++,r.nextRetryAt=Date.now()+ye(r.retryCount,n,0),console.warn("[TM]: 批次过大(HTTP 413),降容半批重发(本批 ".concat(o.length," 条)"))):(r.retryExhausted=!0,fe(o,"rejected_4xx"),console.warn("[TM]: 单条事件仍超限(HTTP 413),数据保留在队列"))}(0,e,c,l,a)})).finally((function(){u.timer=null,u.promise=null,we(e)}))}else if(null===u.timer){var s=c?M:A;u.timer=setTimeout((function(){u.timer=null,we(e,!0)}),s)}}}},Te=function(e){var t;if(!(null==N?void 0:N.enableTracking)||(null==N?void 0:N.respectGpc)&&!0===(null==(t="undefined"!=typeof navigator?navigator:void 0)?void 0:t.globalPrivacyControl))(null==N?void 0:N.isLogger)&&console.warn("[TM]: 用户已选择退出采集(enableTracking=false 或 GPC 信号开启),本事件忽略");else if(e&&"object"==typeof e){var n,r=!0===e.track_real_time,o=le(e);if(o)if(n=o.data_type,R&&n&&!R.dataTypes.includes(n))(null==N?void 0:N.isLogger)&&console.warn("[TM]: 数据类型 ".concat(o.data_type," 未在远程配置中启用,本事件不上报"));else try{ge(r&&k?j:q,o)}catch(e){ve("enqueue_failed","事件入队失败",{error:e})}}else console.error("[TM]: track data must be an object")},be=function(e,t,r){Te("string"==typeof e?n({event_type:e,event_detail:t},r):e)},_e=function(){we(q,!0),we(j,!0);var e=[Q.promise,V.promise].filter((function(e){return!!e}));return Promise.all(e).then((function(){}))},Se=function(){N.isLogger=!0;try{localStorage.setItem(z,"true")}catch(e){console.error("[TM]: enable logger fail:",e)}},Ee=function(){N.isLogger=!1;try{localStorage.setItem(z,"false")}catch(e){console.error("[TM]: disable logger fail:",e)}};v((function(){we(q,!0),we(j,!0)}));var ke=function(e){return"boolean"==typeof e&&(N.enableTracking=e,function(e){try{localStorage.setItem(F,e?"1":"0")}catch(e){}}(e),e?(null==N?void 0:N.isLogger)&&console.warn("[TM]: 恢复采集"):(ce(q,[]),ce(j,[]),(null==N?void 0:N.isLogger)&&console.warn("[TM]: 用户已选择退出采集,已清空未上报队列"))),!0===(null==N?void 0:N.enableTracking)};return window.trackMonitor={track:be,flush:_e,bindUser:Y,unBindUser:Z,enableLogger:Se,disableLogger:Ee,setToken:ue,registerGlobalProperties:te,enableTracking:ke},{client:{track:be,flush:_e,bindUser:Y,unBindUser:Z,enableLogger:Se,disableLogger:Ee,setToken:ue,registerGlobalProperties:te,enableTracking:ke},beforeClose:function(){var e=function(){ie(),we(q,!0,!0),we(j,!0,!0)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()})),window.addEventListener("online",e)}}},he=(k=16,function(){var e=new Uint8Array(k);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(var t=0;t<k;t++)e[t]=Math.floor(256*Math.random());var n="";for(t=0;t<k;t++)n+=(e[t]<16?"0":"")+e[t].toString(16);return n})(),ye=function(e){var t=history[e];return function(){var n=t.apply(this,arguments),r=new Event(e);return window.dispatchEvent(r),n}},ge=function(e){window.addEventListener("replaceState",(function(t){return e(t)}),!0),window.addEventListener("pushState",(function(t){return e(t)}),!0)},we=function(e){window.addEventListener("popstate",(function(t){return e(t)}),!0)},Te=[25,50,75,90],be=function(e){var t,n,r;history.pushState=ye("pushState"),history.replaceState=ye("replaceState"),t="",r=p(n=function(){var e=window.location.href;if(e!==t){var n=window.location,r={host:n.host,hostname:n.hostname,href:n.href,protocol:n.protocol,origin:n.origin,port:n.port,pathname:n.pathname,search:n.search,hash:n.hash,title:document.title,language:navigator.language.substring(0,2),user_agent:navigator.userAgent,win_screen:"".concat(window.screen.width,"x").concat(window.screen.height),doc_screen:"".concat(document.documentElement.clientWidth,"x").concat(document.documentElement.clientHeight),referrer:document.referrer,type:y()};window.trackMonitor.track({data_type:"auto",event_type:"page_view",event_detail:r}),t=e}},200),n(),we((function(){r()})),ge((function(){r()})),window.addEventListener("popstate",(function(){r()})),function(){var e=document.referrer,t=window.location.href,n=Date.now(),r=!0,o=function(r){if(void 0===r&&(r=!1),window.location.href!==t||r){var o=Date.now()-n;o>200&&window.trackMonitor.track({data_type:"auto",event_type:"page_leave",event_detail:{url:t,referrer:e,duration:o}}),n=Date.now(),e=t,t=window.location.href}},i=p(o);o(),we((function(){i()})),ge((function(){i()})),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState?r&&(r=!1,o(!0)):(r=!0,n=Date.now())})),window.addEventListener("beforeunload",(function(){r&&(r=!1,o(!0))}),!0)}(),function(){var e=m((function(e){var t,n=function(e){if(e)return["A","INPUT","TEXTAREA","BUTTON"].includes(e.tagName)||e.hasAttribute("track-click")?e:e.closest("a, button, [track-click]")||void 0}(e.target);if(n){var r={element_id:n.id,element_content:(null===(t=n.textContent)||void 0===t?void 0:t.trim().slice(0,200))||null,element_class_name:n.className||null,element_name:n.getAttribute("name")||null,element_type:n.tagName.toLowerCase(),element_path:h(n),scroll_width:document.documentElement.scrollWidth,scroll_height:document.documentElement.scrollHeight,pageX:e.pageX,pageY:e.pageY,ratio:window.devicePixelRatio||1};window.trackMonitor.track({data_type:"auto",event_type:"click",event_detail:r})}}));window.addEventListener("click",e,!0)}(),!1!==(null==e?void 0:e.enableScroll)&&function(){var e=new Set,t=m((function(){var n=document.documentElement,r=n.scrollHeight-n.clientHeight;if(!(r<=0)){var o=Math.round((window.scrollY||n.scrollTop)/r*100),i=Te.filter((function(t){return o>=t&&!e.has(t)}));i.length&&(i.forEach((function(t){e.add(t),window.trackMonitor.track({data_type:"auto",event_type:"scroll",event_detail:{scroll_depth:t}})})),e.has(90)&&window.removeEventListener("scroll",t))}}),300);window.addEventListener("scroll",t,{passive:!0})}()},_e=null,Se=null,Ee="track-expose",ke="track-view",xe=function(e){try{Se=new WeakMap}catch(e){console.error("[TM]: create WeakMap fail: ",e)}var t=function(e,t){void 0===t&&(t=!1);var r=null==Se?void 0:Se.get(e);if(!r||t){r&&(r.viewTimer&&clearTimeout(r.viewTimer),r.exposeTimer&&clearTimeout(r.exposeTimer));var o=e.dataset.durationView||500,i=e.dataset.durationExpose||500;null==Se||Se.set(e,{duration_view:o,duration_expose:i,viewTimer:null,exposeTimer:null}),null==_e||_e.observe(e),t&&function(e){if(!(e instanceof Element))return!1;if(!function e(t){if(!t)return!0;var n=window.getComputedStyle(t);return"none"!==n.display&&"hidden"!==n.visibility&&0!==parseFloat(n.opacity)&&e(t.parentElement)}(e))return!1;var t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}(e)&&n(e)}},n=function(t){var n,o=null==Se?void 0:Se.get(t);if(o){var i=t.dataset.eventDetail,a=null!==(n=t.dataset.traceid)&&void 0!==n?n:void 0,c=t.dataset.spm,u=t.hasAttribute("track-real-time"),l=t.hasAttribute(ke),s=t.hasAttribute(Ee);l&&s?o.exposeTimer=window.setTimeout((function(){e({spm:c,request_id:a,data_type:"auto",event_type:"view_expose",event_detail:i,track_real_time:u}),t.removeAttribute(ke),o.exposeTimer=null}),parseInt(o.duration_expose,10)):(l&&(o.viewTimer=window.setTimeout((function(){e({spm:c,request_id:a,data_type:"auto",event_type:"view",event_detail:i,track_real_time:u}),t.removeAttribute(ke),s&&o.exposeTimer||r(t),o.viewTimer=null}),parseInt(o.duration_view,10))),s&&(o.exposeTimer=window.setTimeout((function(){e({spm:c,request_id:a,data_type:"auto",event_type:"expose",event_detail:i,track_real_time:u}),o.exposeTimer=null}),parseInt(o.duration_expose,10))))}},r=function(e){var t=null==Se?void 0:Se.get(e);t&&(null==_e||_e.unobserve(e),t.viewTimer&&clearTimeout(t.viewTimer),t.exposeTimer&&clearTimeout(t.exposeTimer),null==Se||Se.delete(e))},o=function(e){e.forEach((function(e){var t=e.target,o=null==Se?void 0:Se.get(t);o&&(o.viewTimer&&(clearTimeout(o.viewTimer),o.viewTimer=null),o.exposeTimer&&(clearTimeout(o.exposeTimer),o.exposeTimer=null),e.isIntersecting&&(n(t),t.hasAttribute(ke)||t.hasAttribute(Ee)||r(t)))}))};_e=function(){var e=null;try{e=new IntersectionObserver(o,{root:null,threshold:.5})}catch(e){console.error("[TM]: create IntersectionObserver fail: ",e)}return e}(),new Set(c(c([],a(document.querySelectorAll("[".concat(Ee,"]"))),!1),a(document.querySelectorAll("[".concat(ke,"]"))),!1)).forEach((function(e){return t(e)})),new MutationObserver((function(e){e.forEach((function(e){if("attributes"===e.type&&e.target instanceof HTMLElement){var n=e.target,o=e.attributeName;n.hasAttribute(Ee)||n.hasAttribute(ke)?["data-event-detail","data-traceid","data-spm","data-duration-view","data-duration-expose"].includes(o)?t(n,!0):o!==Ee&&o!==ke||t(n,!1):r(n)}else"childList"===e.type&&(e.addedNodes.forEach((function(e){e instanceof HTMLElement&&(e.hasAttribute(Ee)||e.hasAttribute(ke)?t(e):new Set(c(c([],a(e.querySelectorAll("[".concat(Ee,"]"))),!1),a(e.querySelectorAll("[".concat(ke,"]"))),!1)).forEach((function(e){return t(e)})))})),e.removedNodes.forEach((function(e){e instanceof HTMLElement&&((null==Se?void 0:Se.get(e))?r(e):new Set(c(c([],a(e.querySelectorAll("[".concat(Ee,"]"))),!1),a(e.querySelectorAll("[".concat(ke,"]"))),!1)).forEach((function(e){return r(e)})))})))}))})).observe(document.body||document.documentElement,{attributes:!0,childList:!0,subtree:!0})},Ae=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;function Me(e){var t=e.match(Ae);return t?{filename:t[2],functionName:t[1]||"",lineno:parseInt(t[3],10)||void 0,colno:parseInt(t[4],10)||void 0}:{}}function Le(e){var t,n,r,o,a;try{var c=e.stack;if(!c)return[];var u=[];try{for(var l=i(c.split("\n").slice(1)),s=l.next();!s.done;s=l.next()){var d=Me(s.value);!d||(null===(r=d.filename)||void 0===r?void 0:r.includes("chrome-extension://"))||(null===(o=d.filename)||void 0===o?void 0:o.includes("node_modules"))||(null===(a=d.filename)||void 0===a?void 0:a.includes("<anonymous>"))||u.push(d)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}return u.slice(0,10)}catch(e){return[]}}var Ce=new Set,Ie=function(e,t){var n,r;if((r=null!==(n=null==N?void 0:N.errorTraceRate)&&void 0!==n?n:.5)<0||r>1?(console.warn("[TM]: probability should be between 0 and 1"),0):Math.random()<r){if(window.trackMonitor.track(t),Ce.size>=1e3){var o=Ce.values().next().value;void 0!==o&&Ce.delete(o)}Ce.add(e)}},Re=function(){window.addEventListener("error",(function(e){!function(e){var t;if(e instanceof ErrorEvent&&"Script error."===e.message){var n=_("js-Script error.");if(Ce.has(n))return;Ie(n,{data_type:"error",event_type:"js",event_detail:{traceId:he,msg:'Script error.(跨域脚本未加载 crossorigin 属性,无法获取堆栈;建议脚本加 crossorigin="anonymous")',target:"",stack:[],errorUuid:n,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno,crossorigin_missing:!0}}})}else if("js"===b(e)&&!function(e){var t,n=(null===(t=e.error)||void 0===t?void 0:t.stack)||"";return/chrome-extension:\/\//.test(n)}(e)){var r=_("js-".concat(e.message,"-").concat(e.filename));if(!Ce.has(r)){var o=Le(e.error),i={traceId:he,msg:e.message,target:o[0]?"".concat(null===(t=o[0].filename)||void 0===t?void 0:t.split("?")[0],":").concat(o[0].lineno,":").concat(o[0].colno):"",stack:o,errorUuid:r,meta:{filename:e.filename,colno:e.colno,lineno:e.lineno}};Ie(r,{data_type:"error",event_type:"js",event_detail:i})}}}(e)}),!0)},Oe=function(){window.addEventListener("error",(function(e){!function(e){var t;if("resource"===b(e)){var n=e.target,r=_("resource-".concat(n.src,"-").concat(n.tagName));if(!Ce.has(r)){var o={traceId:he,msg:"加载".concat(n.tagName,"失败"),target:null===(t=n.src)||void 0===t?void 0:t.split("?")[0],errorUuid:r,meta:{url:n.src,html:n.outerHTML,tagName:n.tagName}};Ie(r,{data_type:"error",event_type:"resource",event_detail:o})}}}(e)}),!0)},Pe=function(){window.addEventListener("unhandledrejection",(function(e){return function(e){var t,n=(null===(t=e.reason)||void 0===t?void 0:t.message)||e.reason,r=_("".concat("unhandledrejection","-").concat(n));if(!Ce.has(r)){var o={traceId:he,msg:n,stack:Le(e.reason),errorUuid:r};Ie(r,{data_type:"error",event_type:"unhandledrejection",event_detail:o})}}(e)}),!0)},Ne=function(){var e=function(e,t,n){var r;if("string"!=typeof(r=e.url)||![null==N?void 0:N.pushUrl,null==N?void 0:N.authUrl,null==N?void 0:N.realTimeUrl].filter((function(e){return!!e})).some((function(e){return 0===r.indexOf(e)})))if(t){var o=_("http-".concat(t,"-").concat(e.url,"-").concat(n));if(Ce.has(o))return;var i={traceId:he,errorType:t,msg:n,target:e.url.split("?")[0],errorUuid:o,request:e};Ie(o,{data_type:"error",event_type:"http",event_detail:i})}else if(e.status>=400){var a=e.statusText;o=_("http-".concat(t="http_error","-").concat(e.url,"-").concat(a));if(Ce.has(o))return;i={traceId:he,errorUuid:o,errorType:t,target:e.url.split("?")[0],msg:a,request:e};Ie(o,{data_type:"error",event_type:"http",event_detail:i})}};!function(e,t){if("XMLHttpRequest"in window&&"function"==typeof window.XMLHttpRequest){var r=window.XMLHttpRequest;window.oXMLHttpRequest||(window.oXMLHttpRequest=r),window.XMLHttpRequest=function(){var e=new r,o=e.open,i=e.send,a={};e.open=function(t,n,r,i,c){void 0===r&&(r=!0),a.method=t,a.url=n,o.call(e,t,n,r,i,c)},e.send=function(t){a.requestTime=(new Date).getTime(),i.call(e,t)};var c=function(r,o){var i=e.status,c=e.statusText,u=(new Date).getTime();a=n(n({},a),{status:i,statusText:c,responseTime:u,duration:u-a.requestTime}),"function"==typeof t&&t(a,r,o)};return e.addEventListener("loadend",(function(){return c()})),e.addEventListener("error",(function(){return c("net_error","ERR_NETWORK")})),e.addEventListener("abort",(function(){return c("cannel_request","ERR_CANCELED")})),e.addEventListener("timeout",(function(){return c("timeout","ERR_NETWORK")})),e}}}(0,e),function(e,t){if("fetch"in window&&"function"==typeof window.fetch){var i=window.fetch;window.oFetch||(window.oFetch=i),window.fetch=function(e,a){return r(void 0,void 0,void 0,(function(){var c;return o(this,(function(u){return(c={}).method=(null==a?void 0:a.method)||"",c.url=(e&&"string"!=typeof e?null==e?void 0:e.url:e)||"",c.requestTime=(new Date).getTime(),[2,i.call(window,e,a).then((function(e){return r(void 0,void 0,void 0,(function(){var r,i;return o(this,(function(o){return"function"==typeof t&&(r=e.clone(),i=(new Date).getTime(),c=n(n({},c),{status:r.status,statusText:r.statusText,responseTime:i,duration:i-c.requestTime}),t(c)),[2,e]}))}))})).catch((function(e){if("function"==typeof t){var r=(new Date).getTime();c=n(n({},c),{responseTime:r,duration:r-c.requestTime}),"AbortError"===e.name?t(c,"cannel_request","ERR_CANCELED"):t(c,"net_error","ERR_NETWORK")}return Promise.reject(e)}))]}))}))}}}(0,e)};var qe=new WeakSet,je=function(e){return{form_id:e.id||null,form_class:"string"==typeof e.className?e.className:null,form_name:e.getAttribute("name")||null,form_action:e.getAttribute("action")||null,form_text:(e.textContent||"").trim().slice(0,200)||null}};function Ue(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Be(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}var De=-1,ze=e=>{addEventListener("pageshow",(t=>{t.persisted&&(De=t.timeStamp,e(t))}),!0)},Fe=(e,t,n,r)=>{var o,i;return a=>{t.value>=0&&(a||r)&&(((i=t.value-(null!=o?o:0))||void 0===o)&&(o=t.value,t.delta=i,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,n),e(t)))}},He=e=>{requestAnimationFrame((()=>requestAnimationFrame((()=>e()))))},Je=()=>{var e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},Ke=()=>{var e,t=Je();return null!==(e=null==t?void 0:t.activationStart)&&void 0!==e?e:0},Ge=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,n=Je(),r="navigate";return De>=0?r="back-forward-cache":n&&(document.prerendering||Ke()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:"v5-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},We=new WeakMap;function Xe(e,t){return We.get(e)||We.set(e,new t),We.get(e)}class Qe{constructor(){Ue(this,"t",void 0),Ue(this,"i",0),Ue(this,"o",[])}h(e){var t;if(!e.hadRecentInput){var n=this.o[0],r=this.o.at(-1);this.i&&n&&r&&e.startTime-r.startTime<1e3&&e.startTime-n.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),null===(t=this.t)||void 0===t||t.call(this,e)}}}var Ve,$e=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((e=>{Promise.resolve().then((()=>{t(e.getEntries())}))}));return r.observe(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Be(Object(n),!0).forEach((function(t){Ue(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Be(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({type:e,buffered:!0},n)),r}}catch(e){}},Ye=e=>{var t=!1;return()=>{t||(e(),t=!0)}},Ze=-1,et=new Set,tt=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,nt=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(var t of et)t();isFinite(Ze)||(Ze="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",nt,!0))}},rt=()=>{if(Ze<0){var e,t=Ke(),n=document.prerendering||null===(e=globalThis.performance.getEntriesByType("visibility-state").filter((e=>"hidden"===e.name&&e.startTime>t))[0])||void 0===e?void 0:e.startTime;Ze=null!=n?n:tt(),addEventListener("visibilitychange",nt,!0),addEventListener("prerenderingchange",nt,!0),ze((()=>{setTimeout((()=>{Ze=tt()}))}))}return{get firstHiddenTime(){return Ze},onHidden(e){et.add(e)}}},ot=e=>{document.prerendering?addEventListener("prerenderingchange",(()=>e()),!0):e()},it=[1800,3e3],at=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};ot((()=>{var n,r=rt(),o=Ge("FCP"),i=$e("paint",(e=>{for(var t of e)"first-contentful-paint"===t.name&&(i.disconnect(),t.startTime<r.firstHiddenTime&&(o.value=Math.max(t.startTime-Ke(),0),o.entries.push(t),n(!0)))}));i&&(n=Fe(e,o,it,t.reportAllChanges),ze((r=>{o=Ge("FCP"),n=Fe(e,o,it,t.reportAllChanges),He((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))})))}))},ct=[.1,.25],ut=0,lt=1/0,st=0,dt=e=>{for(var t of e)t.interactionId&&(lt=Math.min(lt,t.interactionId),st=Math.max(st,t.interactionId),ut=st?(st-lt)/7+1:0)},ft=()=>{var e;return Ve?ut:null!==(e=performance.interactionCount)&&void 0!==e?e:0},vt=0;class pt{constructor(){Ue(this,"u",[]),Ue(this,"l",new Map),Ue(this,"m",void 0),Ue(this,"p",void 0)}v(){vt=ft(),this.u.length=0,this.l.clear()}L(){var e=Math.min(this.u.length-1,Math.floor((ft()-vt)/50));return this.u[e]}h(e){var t;if(null!==(t=this.m)&&void 0!==t&&t.call(this,e),e.interactionId||"first-input"===e.entryType){var n=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>n.P){var o;if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((e,t)=>t.P-e.P)),this.u.length>10){var i=this.u.splice(10);for(var a of i)this.l.delete(a.id)}null===(o=this.p)||void 0===o||o.call(this,r)}}}}var mt=e=>{var t=globalThis.requestIdleCallback||setTimeout;"hidden"===document.visibilityState?e():(e=Ye(e),addEventListener("visibilitychange",e,{once:!0,capture:!0}),t((()=>{e(),removeEventListener("visibilitychange",e,{capture:!0})})))},ht=[200,500],yt=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype){var n=rt();ot((()=>{var r;"interactionCount"in performance||Ve||(Ve=$e("event",dt,{type:"event",buffered:!0,durationThreshold:0}));var o,i=Ge("INP"),a=Xe(t,pt),c=e=>{mt((()=>{for(var t of e)a.h(t);var n=a.L();n&&n.P!==i.value&&(i.value=n.P,i.entries=n.entries,o())}))},u=$e("event",c,{durationThreshold:null!==(r=t.durationThreshold)&&void 0!==r?r:40});o=Fe(e,i,ht,t.reportAllChanges),u&&(u.observe({type:"first-input",buffered:!0}),n.onHidden((()=>{c(u.takeRecords()),o(!0)})),ze((()=>{a.v(),i=Ge("INP"),o=Fe(e,i,ht,t.reportAllChanges)})))}))}};class gt{constructor(){Ue(this,"m",void 0)}h(e){var t;null===(t=this.m)||void 0===t||t.call(this,e)}}var wt=[2500,4e3],Tt=[800,1800],bt=e=>{document.prerendering?ot((()=>bt(e))):"complete"!==document.readyState?addEventListener("load",(()=>bt(e)),!0):setTimeout(e)};function _t(){var e={ttfb:null,lcp:null,fp:null,fcp:null,connectionRtt:null,ttfbRequestTime:null,inp:null,cls:null,dcl:null,loadTime:null};!function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};ot((()=>{var n,r=rt(),o=Ge("LCP"),i=Xe(t,gt),a=e=>{for(var a of(t.reportAllChanges||(e=e.slice(-1)),e))i.h(a),a.startTime<r.firstHiddenTime&&(o.value=Math.max(a.startTime-Ke(),0),o.entries=[a],n())},c=$e("largest-contentful-paint",a);if(c){n=Fe(e,o,wt,t.reportAllChanges);var u=Ye((()=>{a(c.takeRecords()),c.disconnect(),n(!0)})),l=e=>{e.isTrusted&&(mt(u),removeEventListener(e.type,l,{capture:!0}))};for(var s of["keydown","click","visibilitychange"])addEventListener(s,l,{capture:!0});ze((r=>{o=Ge("LCP"),n=Fe(e,o,wt,t.reportAllChanges),He((()=>{o.value=performance.now()-r.timeStamp,n(!0)}))}))}}))}((function(t){e.lcp=w(t.value)}),{reportAllChanges:!0}),function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt();at(Ye((()=>{var r,o=Ge("CLS",0),i=Xe(t,Qe),a=e=>{for(var t of e)i.h(t);i.i>o.value&&(o.value=i.i,o.entries=i.o,r())},c=$e("layout-shift",a);c&&(r=Fe(e,o,ct,t.reportAllChanges),n.onHidden((()=>{a(c.takeRecords()),r(!0)})),ze((()=>{i.i=0,o=Ge("CLS",0),r=Fe(e,o,ct,t.reportAllChanges),He((()=>r()))})),setTimeout(r))})))}((function(t){e.cls=Math.round(1e4*t.value)/1e4}),{reportAllChanges:!0}),yt((function(t){e.inp=w(t.value)}),{reportAllChanges:!0}),function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Ge("TTFB"),r=Fe(e,n,Tt,t.reportAllChanges);bt((()=>{var o=Je();o&&(n.value=Math.max(o.responseStart-Ke(),0),n.entries=[o],r(!0),ze((()=>{n=Ge("TTFB",0),(r=Fe(e,n,Tt,t.reportAllChanges))(!0)})))}))}((function(t){e.ttfb=w(t.value)})),at((function(t){e.fcp=w(t.value)}));var t=function(){!function(){try{performance.getEntriesByType("paint").forEach((function(t){"first-paint"===t.name&&(e.fp=w(t.startTime))}))}catch(e){console.warn("[TM]: Failed to collect FP:",e)}try{var t=navigator.connection||navigator.mozConnection||navigator.webkitConnection;t&&void 0!==t.rtt&&(e.connectionRtt=t.rtt)}catch(e){console.warn("[TM]: Failed to collect Connection RTT:",e)}try{if(o=performance.getEntriesByType("navigation")[0]){var n=o.responseStart,r=o.requestStart;n>0&&r>0&&r<=n&&(e.ttfbRequestTime=w(n-r))}}catch(e){console.warn("[TM]: Failed to collect TTFB Request Time:",e)}try{var o;if(o=performance.getEntriesByType("navigation")[0]){var i=o.domContentLoadedEventEnd,a=o.loadEventEnd,c=o.fetchStart;i>0&&c>0&&(e.dcl=w(i-c)),a>0&&c>0&&(e.loadTime=w(a-c))}}catch(e){console.warn("[TM]: Failed to collect DCL and Load Time:",e)}}(),window.trackMonitor.track({data_type:"performance",event_type:"metrics",event_detail:{traceId:he,data:e}})},n=0,r=function(){var e=Date.now();e-n<3e4||(n=e,t())};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",r),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&r()}))}var St="__tengence_sdk";e.init=function(e){if("undefined"!=typeof window&&window.trackMonitor&&window.trackMonitor[St])return console.warn("[TM]: init 已调用过,复用现有实例(如需重建请刷新页面)"),window.trackMonitor;var t,r=me(e),o=r.client,i=r.beforeClose,a=R,c=function(e,t){return a?a.dataTypes.includes(e):t},u=c("auto",!1!==e.traceBehavior);return u&&(xe(o.track),!1!==e.enableScroll&&be({enableScroll:e.enableScroll})),u&&!1!==e.enableFormTrack&&(t=o.track,document.addEventListener("focusin",(function(e){var n=e.target;if((r=n)&&("INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName)){var r,o=n.closest("form");o&&!qe.has(o)&&(qe.add(o),t({data_type:"auto",event_type:"form_start",event_detail:je(o)}))}}),!0),document.addEventListener("submit",(function(e){var r=e.target;if(r&&"FORM"===r.tagName){var o=e.submitter;t({data_type:"auto",event_type:"form_submit",event_detail:n(n({},je(r)),{submitter_id:(null==o?void 0:o.id)||null,submitter_text:((null==o?void 0:o.textContent)||"").trim().slice(0,200)||null})})}}),!0)),c("error",!1!==e.traceError)&&(Re(),Oe(),Pe(),Ne()),c("performance",!1!==e.tracePerformance)&&g((function(){!function(){var e,t,n,r,o,i=window.performance||window.msPerformance;if(!i)return{dnsLookupTime:null,tcpConnectTime:null,ttfb:null,transferTime:null,domParseTime:null,domCompleteTime:null,loadEventTime:null,totalPageLoad:null};var a=i.getEntriesByType&&"function"==typeof i.getEntriesByType?i.getEntriesByType("navigation"):void 0,c=Array.isArray(a)?a[0]:void 0,u=null;if(c)u=c;else{var l=i.timing;l&&!(u={startTime:0,domainLookupStart:l.domainLookupStart,domainLookupEnd:l.domainLookupEnd,connectStart:l.connectStart,connectEnd:l.connectEnd,requestStart:l.requestStart,responseStart:l.responseStart,responseEnd:l.responseEnd,domInteractive:l.domInteractive,domComplete:l.domComplete,loadEventEnd:l.loadEventEnd,fetchStart:l.fetchStart}).requestStart&&l.fetchStart&&(u.requestStart=l.fetchStart)}var s={dnsLookupTime:u?w(u.domainLookupEnd-u.domainLookupStart):null,tcpConnectTime:u?w(u.connectEnd-u.connectStart):null,ttfb:u?w(u.responseStart-(null!==(t=null!==(e=u.requestStart)&&void 0!==e?e:u.fetchStart)&&void 0!==t?t:0)):null,transferTime:u?w(u.responseEnd-u.responseStart):null,domParseTime:u?w(u.domInteractive-u.responseEnd):null,domCompleteTime:u?w(u.domComplete-u.domInteractive):null,loadEventTime:u?w(u.loadEventEnd-(null!==(n=u.domComplete)&&void 0!==n?n:0)):null,totalPageLoad:u?w((null!==(r=u.loadEventEnd)&&void 0!==r?r:performance.now())-(null!==(o=u.startTime)&&void 0!==o?o:0)):null};window.trackMonitor.track({data_type:"performance",event_type:"navigation_timing",event_detail:{traceId:he,data:s}})}(),function(){var e,t=window.performance||window.msPerformance;if(!t)return[];var n=[];if(t.getEntriesByType){var r=(t.getEntriesByType("resource")||[]).map((function(e){var t="number"==typeof e.redirectEnd&&"number"==typeof e.redirectStart?w(e.redirectEnd-e.redirectStart):null,n="number"==typeof e.domainLookupEnd&&"number"==typeof e.domainLookupStart?w(e.domainLookupEnd-e.domainLookupStart):null,r="number"==typeof e.connectEnd&&"number"==typeof e.connectStart?w(e.connectEnd-e.connectStart):null,o="number"==typeof e.requestStart&&"number"==typeof e.fetchStart?w(e.requestStart-e.fetchStart):null,i="number"==typeof e.responseStart&&"number"==typeof e.requestStart?w(e.responseStart-e.requestStart):null,a="number"==typeof e.responseEnd&&"number"==typeof e.responseStart?w(e.responseEnd-e.responseStart):null,c="number"==typeof e.duration?w(e.duration):null,u="number"==typeof e.startTime?w(e.startTime):null,l="number"==typeof e.transferSize&&isFinite(e.transferSize)&&e.transferSize>=0?Math.round(e.transferSize):null,s="number"==typeof e.encodedBodySize&&isFinite(e.encodedBodySize)&&e.encodedBodySize>=0?Math.round(e.encodedBodySize):null,d="number"==typeof e.decodedBodySize&&isFinite(e.decodedBodySize)&&e.decodedBodySize>=0?Math.round(e.decodedBodySize):null;return{name:e.name,initiatorType:e.initiatorType||"",startTime:u,duration:c,redirectTime:t,cacheTime:o,dnsTime:n,connectTime:r,requestTime:i,responseTime:a,transferSize:l,encodedBodySize:s,decodedBodySize:d}}));r.sort((function(e,t){var n,r;return(null!==(n=t.duration)&&void 0!==n?n:0)-(null!==(r=e.duration)&&void 0!==r?r:0)}));var o=null!==(e=null==N?void 0:N.resourceFlowLimit)&&void 0!==e?e:15;if(0===o)return;for(var i=0;i<Math.min(o,r.length);i++)n.push(r[i]);if(!n.length)return}window.trackMonitor.track({data_type:"performance",event_type:"resource_flow",event_detail:{traceId:he,data:n}})}(),_t()})),g((function(){i()})),window.trackMonitor[St]=!0,window.trackMonitor}}));
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { DataType } from "../interface";
|
|
2
|
+
/**
|
|
3
|
+
* SDK 远程配置(埋点采集行为由后端 DI 集成应用/任务配置下发)
|
|
4
|
+
*
|
|
5
|
+
* 行业实践对齐(PostHog decide / Firebase Remote Config / 阿里云 Quick Tracking):
|
|
6
|
+
* - SDK 启动异步拉取配置,不阻塞初始化(init 立即返回)
|
|
7
|
+
* - localStorage 缓存 + TTL(默认 5 分钟);失败回退链:新配置 → 缓存 → 默认全类型
|
|
8
|
+
* - 线上配置优先:dataTypes 决定 SDK 采集/上报哪些数据类型(未被勾选的类型不上报)
|
|
9
|
+
*/
|
|
10
|
+
export interface RemoteTrackConfig {
|
|
11
|
+
appId?: string;
|
|
12
|
+
dataTypes: DataType[];
|
|
13
|
+
idFieldName: string;
|
|
14
|
+
configVersion?: number;
|
|
15
|
+
updatedAt?: string;
|
|
16
|
+
fetchedAt: number;
|
|
17
|
+
}
|
|
18
|
+
export declare const DEFAULT_DATA_TYPES: DataType[];
|
|
19
|
+
export declare const DEFAULT_CONFIG_TTL: number;
|
|
20
|
+
/**
|
|
21
|
+
* 推导配置地址:显式 configUrl 优先;否则从 pushUrl 取 base → {base}/v1/track/config
|
|
22
|
+
* (push 与 config 同属 API 数据面域名;authUrl 在 www 域名下不作推导源)
|
|
23
|
+
*/
|
|
24
|
+
export declare const deriveConfigUrl: (pushUrl?: string, configUrl?: string) => string;
|
|
25
|
+
/** 读取缓存(无论是否过期都返回,作为失败兜底;fresh 判断由调用方做) */
|
|
26
|
+
export declare const loadCachedConfig: () => RemoteTrackConfig | null;
|
|
27
|
+
export declare const isConfigFresh: (cfg: RemoteTrackConfig, ttl?: number) => boolean;
|
|
28
|
+
/**
|
|
29
|
+
* 拉取远程配置(GET {configUrl},Bearer 凭证与 push 一致:apiKey 或 accessToken)。
|
|
30
|
+
* 成功:覆盖缓存并生效;失败:保留缓存/默认配置,静默回退(console.warn)。
|
|
31
|
+
*/
|
|
32
|
+
export declare const fetchRemoteConfig: (configUrl: string, credential?: string, timeoutMs?: number) => Promise<RemoteTrackConfig | null>;
|
|
33
|
+
/** 当前生效的远程配置(无则为 null → 全类型放行) */
|
|
34
|
+
export declare const getRemoteConfig: () => RemoteTrackConfig | null;
|
|
35
|
+
/** 设置生效配置(init 时同步应用缓存) */
|
|
36
|
+
export declare const setRemoteConfig: (cfg: RemoteTrackConfig | null) => void;
|
|
37
|
+
/**
|
|
38
|
+
* 数据类型是否允许采集/上报(线上配置优先):
|
|
39
|
+
* - 无远程配置 → 放行(不阻塞采集)
|
|
40
|
+
* - 事件未标注 data_type → 放行(不误伤)
|
|
41
|
+
* - 已标注且未被勾选 → 丢弃
|
|
42
|
+
*/
|
|
43
|
+
export declare const isDataTypeEnabled: (dataType?: string) => boolean;
|
package/dist/utils/request.d.ts
CHANGED
|
@@ -37,4 +37,12 @@ export declare const postJson: <T>(url: string, payload: any, timeoutMs?: number
|
|
|
37
37
|
* @param timeoutMs 请求超时(毫秒,G2);0/undefined 不设超时(页面卸载补发路径)
|
|
38
38
|
*/
|
|
39
39
|
export declare const postJsonWithAuth: <T>(url: string, payload: any, credential?: string, timeoutMs?: number) => Promise<T>;
|
|
40
|
+
/**
|
|
41
|
+
* 带 Bearer 鉴权的 JSON GET(远程配置等只读数据面接口)。
|
|
42
|
+
* fetch 优先,网络失败/超时/不可用时回退 XHR(与 postJsonWithAuth 同策略)。
|
|
43
|
+
* @param url 请求地址
|
|
44
|
+
* @param credential accessToken 或 apiKey(作为 Bearer)
|
|
45
|
+
* @param timeoutMs 请求超时(毫秒);0/undefined 不设超时
|
|
46
|
+
*/
|
|
47
|
+
export declare const getJsonWithAuth: <T>(url: string, credential?: string, timeoutMs?: number) => Promise<T>;
|
|
40
48
|
export {};
|