@yuanze_dev/tracker-miniprogram 0.11.2 → 0.11.4
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/README.md +38 -1
- package/dist/index.js +1 -1
- package/index.d.ts +29 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Mini Program Click Text
|
|
2
2
|
|
|
3
|
-
Version 0.11.
|
|
3
|
+
Version 0.11.4 includes the runtime SDK and the Node.js 22 WXML preparation tool.
|
|
4
4
|
It adds optional `$text` to `$autocapture`; existing page fields are reused.
|
|
5
5
|
|
|
6
6
|
Install and lock this package, then keep the existing SDK initialization and
|
|
@@ -104,3 +104,40 @@ sensitive marks to descendants. Pure 4-8 digit labels are omitted; phone numbers
|
|
|
104
104
|
email addresses and long numeric identifiers use existing redaction.
|
|
105
105
|
|
|
106
106
|
This tool targets native WXML. It does not establish Taro or web-view support.
|
|
107
|
+
|
|
108
|
+
## Development Exercise Observation
|
|
109
|
+
|
|
110
|
+
The optional SDK sender observer supports a prepared development Self-check
|
|
111
|
+
exercise. A central application bootstrap enables it; business buttons, callbacks
|
|
112
|
+
and labels do not need test-specific changes. It observes the SDK sender directly
|
|
113
|
+
without replacing `wx.request`, including on devices where that property is readonly.
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
const onSenderEvent = (event) => exerciseObserver.record(event);
|
|
117
|
+
tracker.init({
|
|
118
|
+
endpoint: trackingEndpoint,
|
|
119
|
+
writeKey: developmentWriteKey,
|
|
120
|
+
initialProperties: { $validation_run_id: validationRunId },
|
|
121
|
+
testing: { enabled: true, validationRunId, onSenderEvent },
|
|
122
|
+
});
|
|
123
|
+
const state = tracker.getTestingSenderState(onSenderEvent);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Use the same callback reference for state inspection. Testing requires an explicit
|
|
127
|
+
enable flag, a development Write Key and a valid run UUID matching the initial
|
|
128
|
+
properties. Invalid testing configuration is rejected before an existing tracker
|
|
129
|
+
is disposed. Keep this configuration and the test controls out of production builds.
|
|
130
|
+
|
|
131
|
+
Notifications contain only `phase` (`started`, `succeeded`, `failed`), `requestId`
|
|
132
|
+
and up to 50 matching-run event references: `eventId`, `validationRunId`,
|
|
133
|
+
`validationCaseId` and `isAutocapture`. They do not expose credentials, request
|
|
134
|
+
bodies, labels or error objects. This is bounded sender evidence for one prepared
|
|
135
|
+
exercise, with no arbitrary event-query API.
|
|
136
|
+
|
|
137
|
+
State includes `available`, `healthy`, `validationRunId` and `pendingRequests`.
|
|
138
|
+
Disposal or replacement with another observer makes the old callback unavailable.
|
|
139
|
+
Throwing or asynchronous observers make observation unhealthy without changing
|
|
140
|
+
the actual sender result; the callback must be synchronous. Failed observation,
|
|
141
|
+
pending sends or a missing observer must not be reported as successful delivery.
|
|
142
|
+
Sender success alone does not prove event storage: complete the prepared exercise
|
|
143
|
+
with `task selfcheck verify`. Normal initialization leaves observation disabled.
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __defProps=Object.defineProperties;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropDescs=Object.getOwnPropertyDescriptors||function(object){var descriptors={};var names=__getOwnPropNames(object);for(var index=0;index<names.length;index++){var key=names[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}if(__getOwnPropSymbols){var symbols=__getOwnPropSymbols(object);for(var index=0;index<symbols.length;index++){var key=symbols[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}}return descriptors};var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __pow=Math.pow;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b));var __objRest=(source,exclude)=>{var target={};for(var prop in source)if(__hasOwnProp.call(source,prop)&&exclude.indexOf(prop)<0)target[prop]=source[prop];if(source!=null&&__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(source)){if(exclude.indexOf(prop)<0&&__propIsEnum.call(source,prop))target[prop]=source[prop]}return target};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var __async=(__this,__arguments,generator)=>{return new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}};var rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}};var step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())})};var index_exports={};__export(index_exports,{SDK_NAME:()=>SDK_NAME2,SDK_VERSION:()=>SDK_VERSION2,SYSTEM_EVENTS:()=>SYSTEM_EVENTS,default:()=>index_default,dispose:()=>dispose,enableAutoTrack:()=>enableAutoTrack,flush:()=>flush,getTracker:()=>getTracker,identify:()=>identify,init:()=>init,installAutoTrack:()=>installAutoTrack,isSystemEvent:()=>isSystemEvent,refreshRemoteConfig:()=>refreshRemoteConfig,register:()=>register,reset:()=>reset,track:()=>track,trackTap:()=>trackTap,tracker:()=>tracker,wxEnvContext:()=>wxEnvContext,wxPersistence:()=>wxPersistence,wxSender:()=>wxSender,wxStorage:()=>wxStorage});module.exports=__toCommonJS(index_exports);function uuid(){const c=typeof globalThis==="undefined"?void 0:globalThis.crypto;if(typeof(c==null?void 0:c.randomUUID)==="function"){try{return c.randomUUID()}catch(e){}}if(typeof(c==null?void 0:c.getRandomValues)==="function"){try{const b2=c.getRandomValues(new Uint8Array(16));return formatUuid(b2)}catch(e){}}const b=new Uint8Array(16);for(let i=0;i<16;i+=1)b[i]=Math.floor(Math.random()*256);return formatUuid(b)}function formatUuid(b){b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=[];for(let i=0;i<16;i+=1){const value=b[i].toString(16);hex.push(value.length===1?`0${value}`:value)}const s=hex.join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function memoryStorage(){const m=new Map;return{get:k=>{var _a;return(_a=m.get(k))!=null?_a:null},set:(k,v)=>void m.set(k,v),remove:k=>void m.delete(k)}}function webStorage(){const mem=memoryStorage();let ls=null;try{ls=typeof localStorage!=="undefined"?localStorage:null}catch(e){ls=null}if(!ls)return mem;return{get(k){try{return ls.getItem(k)}catch(e){return mem.get(k)}},set(k,v){try{ls.setItem(k,v)}catch(e){mem.set(k,v)}},remove(k){try{ls.removeItem(k)}catch(e){mem.remove(k)}}}}var STORAGE_KEYS={anonymousId:"yz_anon",userId:"yz_uid",userUuid:"yz_user_uuid",session:"yz_session"};var SESSION_TIMEOUT_MS=30*60*1e3;var TOUCH_PERSIST_MS=60*1e3;function normalizeSnapshot(snapshot){var _a,_b,_c,_d,_e;const anonymousId=String((_a=snapshot==null?void 0:snapshot.anonymousId)!=null?_a:"").trim();const sessionId=String((_b=snapshot==null?void 0:snapshot.sessionId)!=null?_b:"").trim();const userId=String((_c=snapshot==null?void 0:snapshot.userId)!=null?_c:"").trim()||null;const userUuid=userId?String((_d=snapshot==null?void 0:snapshot.userUuid)!=null?_d:"").trim()||null:null;const distinctId=userId!=null?userId:anonymousId;const distinctIdType=userId?"user_id":"anonymous_id";if(!anonymousId||!sessionId)return null;if(String((_e=snapshot==null?void 0:snapshot.distinctId)!=null?_e:"").trim()!==distinctId)return null;if((snapshot==null?void 0:snapshot.distinctIdType)!==distinctIdType)return null;return{anonymousId,userId,userUuid,sessionId}}function dayKey(ts){const d=new Date(ts);const p=n=>n<10?`0${n}`:String(n);return`${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`}var Identity=class{constructor(store,now=Date.now,initialSnapshot){__publicField(this,"store",store);__publicField(this,"now",now);__publicField(this,"anonymousId");__publicField(this,"userId");__publicField(this,"userUuid");__publicField(this,"session");__publicField(this,"persistedAt");var _a;const initial=initialSnapshot?normalizeSnapshot(initialSnapshot):null;if(initial){this.anonymousId=initial.anonymousId;this.userId=initial.userId;this.userUuid=initial.userUuid;const at=this.now();this.session={id:initial.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot()}else{this.anonymousId=(_a=this.store.get(STORAGE_KEYS.anonymousId))!=null?_a:this.newAnonymousId();this.userId=this.store.get(STORAGE_KEYS.userId)||null;this.userUuid=this.store.get(STORAGE_KEYS.userUuid)||null;this.session=this.loadSession()}this.persistedAt=this.session.lastActive}persistSnapshot(){this.store.set(STORAGE_KEYS.anonymousId,this.anonymousId);if(this.userId)this.store.set(STORAGE_KEYS.userId,this.userId);else this.store.remove(STORAGE_KEYS.userId);if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session))}newAnonymousId(){const id=`anon_${uuid()}`;this.store.set(STORAGE_KEYS.anonymousId,id);return id}loadSession(){const raw=this.store.get(STORAGE_KEYS.session);if(raw){try{const s=JSON.parse(raw);if((s==null?void 0:s.id)&&typeof s.lastActive==="number"&&!this.expired(s,this.now()))return s}catch(e){}}return this.startSession(this.now())}expired(s,at){return at-s.lastActive>SESSION_TIMEOUT_MS||s.day!==dayKey(at)}startSession(at){const s={id:uuid(),lastActive:at,day:dayKey(at)};this.store.set(STORAGE_KEYS.session,JSON.stringify(s));this.persistedAt=at;return s}touch(){const at=this.now();if(this.expired(this.session,at)){this.session=this.startSession(at);return}this.session.lastActive=at;if(at-this.persistedAt>=TOUCH_PERSIST_MS){this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session));this.persistedAt=at}}identify(userId,options){var _a;const id=String(userId!=null?userId:"").trim();if(!id)return false;const userChanged=id!==this.userId;const uuidWasProvided=(options==null?void 0:options.userUuid)!==void 0;const nextUuid=uuidWasProvided?String((_a=options.userUuid)!=null?_a:"").trim()||null:this.userUuid;const uuidChanged=nextUuid!==this.userUuid;if(!userChanged&&!uuidChanged)return false;this.userId=id;this.store.set(STORAGE_KEYS.userId,id);this.userUuid=userChanged&&!uuidWasProvided?null:nextUuid;if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);return true}reset(anonymousId){this.userId=null;this.store.remove(STORAGE_KEYS.userId);this.userUuid=null;this.store.remove(STORAGE_KEYS.userUuid);const sharedAnonymousId=anonymousId==null?void 0:anonymousId.trim();if(sharedAnonymousId){this.anonymousId=sharedAnonymousId;this.store.set(STORAGE_KEYS.anonymousId,sharedAnonymousId)}else{this.anonymousId=this.newAnonymousId()}this.session=this.startSession(this.now())}snapshot(){var _a;return{distinctId:(_a=this.userId)!=null?_a:this.anonymousId,distinctIdType:this.userId?"user_id":"anonymous_id",anonymousId:this.anonymousId,userId:this.userId,userUuid:this.userUuid,sessionId:this.session.id}}applySnapshot(snapshot){const next=normalizeSnapshot(snapshot);if(!next)return false;const before=this.snapshot();if(before.userId!==null&&before.userId!==next.userId&&before.anonymousId===next.anonymousId)return false;const at=this.now();this.anonymousId=next.anonymousId;this.userId=next.userId;this.userUuid=next.userUuid;this.session={id:next.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot();this.persistedAt=at;const after=this.snapshot();return before.anonymousId!==after.anonymousId||before.userId!==after.userId||before.userUuid!==after.userUuid||before.sessionId!==after.sessionId}setAnonymousId(id){this.anonymousId=id;this.store.set(STORAGE_KEYS.anonymousId,id)}};var DB_NAME="yz_tracker";var STORE="queue";var DEFAULT_LIMIT=500;function openDb(dbName){return new Promise((resolve,reject)=>{const req=indexedDB.open(dbName,1);req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(STORE)){db.createObjectStore(STORE,{keyPath:"eventId"}).createIndex("savedAt","savedAt")}};req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);req.onblocked=()=>reject(new Error("indexedDB blocked"))})}function indexedDbPersistence(opts={}){var _a,_b;if(typeof indexedDB==="undefined")return null;const dbName=(_a=opts.dbName)!=null?_a:DB_NAME;const limit=(_b=opts.limit)!=null?_b:DEFAULT_LIMIT;let dbPromise=null;const db=()=>{dbPromise!=null?dbPromise:dbPromise=openDb(dbName);return dbPromise};const write=fn=>__async(null,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readwrite");fn(tx.objectStore(STORE))}catch(e){}});return{load(){return __async(this,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readonly");const req=tx.objectStore(STORE).index("savedAt").getAll();const rows=yield new Promise((resolve,reject)=>{req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error)});return rows.map(r=>r.payload)}catch(e){return[]}})},add(records){void write(store=>{for(const r of records)store.put(r);const countReq=store.count();countReq.onsuccess=()=>{const over=countReq.result-limit;if(over<=0)return;let dropped=0;const cur=store.index("savedAt").openCursor();cur.onsuccess=()=>{const c=cur.result;if(!c||dropped>=over)return;c.delete();dropped+=1;c.continue()}}})},remove(eventIds){if(!eventIds.length)return;void write(store=>{for(const id of eventIds)store.delete(id)})}}}var SDK_NAME="@yuanze_dev/tracker";var SDK_VERSION="0.16.2";var PROTOCOL_VERSION=1;var MAX_BATCH_SIZE=50;var PLATFORMS=["web","pc","flutter","ios","android","miniprogram","backend","electron-renderer","electron-main","tauri-web","tauri-rust","node"];var documentPageInstanceId;function currentPageInstanceId(){if(typeof window==="undefined"||typeof document==="undefined")return void 0;documentPageInstanceId!=null?documentPageInstanceId:documentPageInstanceId=uuid();return documentPageInstanceId}var MAX_BACKOFF_MS=3e4;var Tracker=class{constructor(opts){__publicField(this,"queue",[]);__publicField(this,"timer",null);__publicField(this,"superProps",{});__publicField(this,"identity");__publicField(this,"persistence");__publicField(this,"send");__publicField(this,"endpoint");__publicField(this,"writeKey");__publicField(this,"platform");__publicField(this,"appVersion");__publicField(this,"sdkName");__publicField(this,"sdkVersion");__publicField(this,"maxBatch");__publicField(this,"flushMs");__publicField(this,"maxQueueSize");__publicField(this,"pageInstanceId");__publicField(this,"sessionAuthority");__publicField(this,"flushing",false);__publicField(this,"flushWaiters",[]);__publicField(this,"retryCount",0);__publicField(this,"droppedEventCount",0);__publicField(this,"configVersion",0);__publicField(this,"pageviewHandler",null);__publicField(this,"pageleaveHandler",null);__publicField(this,"diagnosticsBridge",null);__publicField(this,"disposeHandlers",[]);__publicField(this,"identityChangeHandlers",[]);var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k;this.endpoint=opts.endpoint;this.writeKey=opts.writeKey;this.platform=(_a=opts.platform)==null?void 0:_a.trim().toLowerCase();this.appVersion=opts.appVersion;this.sdkName=(_b=opts.sdkName)!=null?_b:SDK_NAME;this.sdkVersion=(_c=opts.sdkVersion)!=null?_c:SDK_VERSION;this.maxBatch=(_d=opts.maxBatch)!=null?_d:5;this.flushMs=(_e=opts.flushMs)!=null?_e:5e3;this.maxQueueSize=(_f=opts.maxQueueSize)!=null?_f:500;this.pageInstanceId=currentPageInstanceId();this.sessionAuthority=(_g=opts.sessionAuthority)!=null?_g:"local";this.send=(_h=opts.sender)!=null?_h:defaultFetchSender;this.identity=new Identity((_i=opts.storage)!=null?_i:webStorage(),Date.now,opts.initialIdentity);if(opts.distinctId&&!opts.initialIdentity)this.identity.setAnonymousId(opts.distinctId);this.superProps=__spreadValues({},(_j=opts.initialProperties)!=null?_j:{});this.persistence=opts.persistence===false?null:(_k=opts.persistence)!=null?_k:indexedDbPersistence({limit:this.maxQueueSize});void this.restore();if(this.platform&&PLATFORMS.indexOf(this.platform)<0){console.error(`[tracker] platform "${this.platform}" 不在受控端列表里,按端分析时这批数据会自成一端。可选值:${PLATFORMS.join(" / ")}(微信小程序是 miniprogram,不是 wechat)`)}if(typeof document!=="undefined"){const onVisibilityChange=()=>{if(document.visibilityState==="hidden")this.flush(true)};document.addEventListener("visibilitychange",onVisibilityChange);this.addDisposeHandler(()=>document.removeEventListener("visibilitychange",onVisibilityChange));if(typeof window!=="undefined"){const onPageHide=()=>this.flush(true);window.addEventListener("pagehide",onPageHide);this.addDisposeHandler(()=>window.removeEventListener("pagehide",onPageHide))}}}restore(){return __async(this,null,function*(){if(!this.persistence)return;const saved=yield this.persistence.load();const known=new Set(this.queue.map(e=>e.eventId));const revived=saved.filter(e=>(e==null?void 0:e.eventId)&&!known.has(e.eventId));if(!revived.length)return;this.queue.unshift(...revived);this.trim();void this.flush()})}register(props){for(const key of Object.keys(props))this.superProps[key]=props[key]}identify(id,options){const before=this.identity.snapshot();if(!this.identity.identify(id,options))return;this.enqueue("$identify",{});const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}reset(anonymousId){const before=this.identity.snapshot();this.identity.reset(anonymousId);const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}getDistinctId(){return this.identity.snapshot().distinctId}getAnonymousId(){return this.identity.snapshot().anonymousId}getSessionId(){return this.identity.snapshot().sessionId}getPageInstanceId(){return this.pageInstanceId}getIdentitySnapshot(){return this.identity.snapshot()}touchIdentity(){const before=this.identity.snapshot();if(this.sessionAuthority==="external")return before;this.identity.touch();const after=this.identity.snapshot();if(before.sessionId!==after.sessionId){for(const handler of this.identityChangeHandlers)handler(before,after)}return after}applyIdentitySnapshot(snapshot,options={}){const before=this.identity.snapshot();const changed=this.identity.applySnapshot(snapshot);if(!changed)return false;const after=this.identity.snapshot();const identityChanged=before.userId!==after.userId||before.userUuid!==after.userUuid;if(options.emitIdentify===true&&before.anonymousId===after.anonymousId&&after.userId!==null&&identityChanged){this.enqueue("$identify",{})}for(const handler of this.identityChangeHandlers)handler(before,after);return true}setConfigVersion(version){if(Number.isInteger(version)&&version>=0)this.configVersion=version}getConfigVersion(){return this.configVersion}get pending(){return this.queue.length}get droppedEvents(){return this.droppedEventCount}dispose(){if(this.timer){clearTimeout(this.timer);this.timer=null}this.diagnosticsBridge=null;for(const handler of this.disposeHandlers.splice(0))handler()}addDisposeHandler(handler){this.disposeHandlers.push(handler)}addIdentityChangeHandler(handler){this.identityChangeHandlers.push(handler);const remove=()=>{this.identityChangeHandlers=this.identityChangeHandlers.filter(candidate=>candidate!==handler)};this.addDisposeHandler(remove);return remove}setPageviewHandler(handler){this.pageviewHandler=handler}setPageleaveHandler(handler){this.pageleaveHandler=handler}setDiagnosticsBridge(bridge){this.diagnosticsBridge=bridge}captureException(error,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.captureException(error,options))!=null?_b:null}log(level,message,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.log(level,message,options))!=null?_b:null}flushDiagnostics(){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.flush())!=null?_b:Promise.resolve()}pageview(input){const url=typeof input==="string"?input:input==null?void 0:input.$url;if(this.pageviewHandler)this.pageviewHandler(url);else if(input&&typeof input==="object")this.track("$pageview",input);else if(url)this.track("$pageview",{$url:url})}pageleave(){var _a;(_a=this.pageleaveHandler)==null?void 0:_a.call(this)}track(name,properties){this.enqueue(name,properties!=null?properties:{})}trackUnsafe(name,properties={}){this.enqueue(name,properties)}captureAs(who,name,properties={},options={}){this.enqueue(name,properties,who,options)}enqueue(name,properties,override,options={}){var _a,_b,_c,_d;const who=override!=null?override:this.touchIdentity();const raw={eventId:(_a=options.eventId)!=null?_a:uuid(),eventName:name,distinctId:who.distinctId,distinctIdType:who.distinctIdType,anonymousId:who.anonymousId,userId:(_b=who.userId)!=null?_b:void 0,userUuid:(_c=who.userUuid)!=null?_c:void 0,sessionId:who.sessionId,pageInstanceId:this.pageInstanceId,platform:this.platform,appVersion:this.appVersion,clientTime:new Date().toISOString(),properties:__spreadProps(__spreadValues(__spreadValues({},this.superProps),properties),{$sdk_name:this.sdkName,$sdk_version:this.sdkVersion,$protocol_version:PROTOCOL_VERSION,$config_version:this.configVersion})};this.queue.push(raw);(_d=this.persistence)==null?void 0:_d.add([{eventId:raw.eventId,savedAt:Date.now(),payload:raw}]);this.trim();if(this.queue.length>=this.maxBatch)this.flush();else this.schedule()}trim(){var _a;const overflow=this.queue.length-this.maxQueueSize;if(overflow>0){const dropped=this.queue.splice(0,overflow);this.droppedEventCount+=dropped.length;(_a=this.persistence)==null?void 0:_a.remove(dropped.map(e=>e.eventId));console.warn(`[tracker] 队列超过 ${this.maxQueueSize} 条,丢弃最旧的 ${overflow} 条`)}}schedule(delayMs=this.flushMs){if(this.timer)return;this.timer=setTimeout(()=>this.flush(),delayMs)}flush(unloading=false){return __async(this,null,function*(){var _a,_b;if(this.timer){clearTimeout(this.timer);this.timer=null}if(this.flushing&&!unloading){yield new Promise(resolve=>this.flushWaiters.push(resolve));if(this.queue.length>0)yield this.flush();return}if(this.queue.length===0)return;this.flushing=true;const batch=this.queue.splice(0,Math.min(MAX_BATCH_SIZE,this.queue.length));const body=JSON.stringify({events:batch,protocolVersion:PROTOCOL_VERSION});const headers={"Content-Type":"application/json","x-write-key":this.writeKey};try{yield this.send(this.endpoint,body,headers,unloading);(_a=this.persistence)==null?void 0:_a.remove(batch.map(e=>e.eventId));this.retryCount=0}catch(err){if((err==null?void 0:err.retryable)!==false){this.queue.unshift(...batch);this.trim();this.retryCount+=1}else{this.droppedEventCount+=batch.length;console.warn("[tracker] 丢弃一批(不可重试):",err==null?void 0:err.status);(_b=this.persistence)==null?void 0:_b.remove(batch.map(e=>e.eventId));this.retryCount=0}}finally{this.flushing=false;for(const resolve of this.flushWaiters.splice(0))resolve()}if(this.queue.length>0&&!unloading){this.schedule(Math.min(this.flushMs*__pow(2,this.retryCount),MAX_BACKOFF_MS))}})}};var defaultFetchSender=(endpoint,body,headers,keepalive)=>__async(null,null,function*(){const res=yield fetch(endpoint,{method:"POST",headers,body,keepalive});if(!res.ok){const e=new Error(`HTTP ${res.status}`);e.status=res.status;e.retryable=res.status>=500||res.status===429;throw e}});var DEFAULT_CAPTURE_SETTINGS={captureClicks:true,captureText:true,maxTextLength:64,sampleRate:1,allowSelectors:["a","button",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','input[type="submit"]','input[type="button"]',"summary"],denySelectors:["[data-no-track]",".yz-no-track"],captureHref:true,captureTitle:true,captureAriaLabel:true,captureRole:true,captureName:true,captureId:true,captureDataTestId:true,capturePageviews:true,capturePageleave:true,capturePageDuration:true,captureVisibleDuration:false};var bool=v=>typeof v==="boolean";var number=(v,min,max)=>typeof v==="number"&&Number.isFinite(v)&&v>=min&&v<=max;var strings=v=>Array.isArray(v)&&v.length<=50&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=256);var integer=(v,min,max)=>number(v,min,max)&&Number.isInteger(v);var stringList=(v,maxItems,maxLength)=>Array.isArray(v)&&v.length<=maxItems&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=maxLength);var object=v=>v&&typeof v==="object"&&!Array.isArray(v)?v:{};function isValidHttpsOrigin(value){if(typeof value!=="string")return false;try{const url=new URL(value);return url.protocol==="https:"&&url.origin===value}catch(e){return false}}function parseReplayConfig(input){var _a,_b,_c;if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const appVersions=object(settings.appVersions);const errorSampling=object(settings.errorSampling);const recording=object(settings.recording);const pages=object(settings.pages);const privacy=object(settings.privacy);const capture=object(settings.capture);const upload=object(settings.upload);const legacyQuota=object(settings.quota);const maxSessionBytes=(_a=settings.maxSessionBytes)!=null?_a:legacyQuota.maxSessionBytes;const uploadOrigins=(_b=raw.uploadOrigins)!=null?_b:[];const checkpointMaxBytes=(_c=recording.checkpointMaxBytes)!=null?_c:4*1024*1024;if(!bool(raw.enabled)||!bool(raw.supported)||raw.recorderKind!=="rrweb"||raw.replayFormat!=="rrweb-v1"||typeof raw.samplingSalt!=="string"||!stringList(uploadOrigins,10,512)||!uploadOrigins.every(isValidHttpsOrigin)||!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!bool(settings.enabled)||!bool(settings.emergencyDisabled)||!number(settings.sampleRate,0,1)||!stringList(appVersions.include,100,100)||!stringList(appVersions.exclude,100,100)||!bool(errorSampling.enabled)||errorSampling.mode!=="after-error"&&errorSampling.mode!=="rolling-buffer"||!integer(errorSampling.rollingBufferSeconds,5,120)||!integer(recording.maxSessionMinutes,1,720)||!integer(recording.maxEvents,100,2e6)||!integer(recording.chunkSeconds,2,60)||!integer(recording.chunkMaxBytes,64*1024,2*1024*1024)||!integer(checkpointMaxBytes,256*1024,16*1024*1024)||!integer(recording.checkpointSeconds,10,120)||!integer(recording.localQueueMaxBytes,1024*1024,200*1024*1024)||!integer(recording.stopAfterBackgroundMinutes,1,120)||!stringList(pages.include,50,512)||!stringList(pages.exclude,100,512)||!bool(privacy.maskAllInputs)||!stringList(privacy.maskSelectors,100,256)||!stringList(privacy.blockSelectors,100,256)||!stringList(privacy.redactUrlParams,100,100)||!bool(capture.canvas)||!bool(capture.inlineImages)||!bool(capture.collectFonts)||!bool(capture.crossOriginIframes)||!integer(upload.concurrency,1,6)||!integer(upload.timeoutSeconds,5,120)||!integer(upload.maxRetries,0,12)||!integer(upload.retryBaseMs,100,1e4)||!integer(upload.localRetryDays,1,30)||!integer(maxSessionBytes,1024*1024,2*1024*1024*1024))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,recorderKind:"rrweb",replayFormat:"rrweb-v1",uploadOrigins,samplingSalt:raw.samplingSalt,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{enabled:settings.enabled,emergencyDisabled:settings.emergencyDisabled,sampleRate:settings.sampleRate,appVersions:{include:appVersions.include,exclude:appVersions.exclude},errorSampling:{enabled:errorSampling.enabled,mode:errorSampling.mode,rollingBufferSeconds:errorSampling.rollingBufferSeconds},recording:{maxSessionMinutes:recording.maxSessionMinutes,maxEvents:recording.maxEvents,chunkSeconds:recording.chunkSeconds,chunkMaxBytes:recording.chunkMaxBytes,checkpointMaxBytes,checkpointSeconds:recording.checkpointSeconds,localQueueMaxBytes:recording.localQueueMaxBytes,stopAfterBackgroundMinutes:recording.stopAfterBackgroundMinutes},pages:{include:pages.include,exclude:pages.exclude},privacy:{maskAllInputs:privacy.maskAllInputs,maskSelectors:privacy.maskSelectors,blockSelectors:privacy.blockSelectors,redactUrlParams:privacy.redactUrlParams},capture:{canvas:capture.canvas,inlineImages:capture.inlineImages,collectFonts:capture.collectFonts,crossOriginIframes:capture.crossOriginIframes},upload:{concurrency:upload.concurrency,timeoutSeconds:upload.timeoutSeconds,maxRetries:upload.maxRetries,retryBaseMs:upload.retryBaseMs,localRetryDays:upload.localRetryDays},maxSessionBytes}}}var DIAGNOSTIC_LEVELS=new Set(["debug","info","warn","error","fatal"]);function parseDiagnosticsConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const errors=object(settings.errors);const logs=object(settings.logs);const context=object(settings.context);const upload=object(settings.upload);const privacy=object(settings.privacy);const levels=logs.levels;if(!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!bool(raw.enabled)||!bool(raw.supported)||typeof raw.endpointPath!=="string"||!raw.endpointPath.startsWith("/")||raw.endpointPath.length>512||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!number(errors.sampleRate,0,1)||!bool(errors.captureUnhandled)||!bool(errors.captureHandled)||!Array.isArray(levels)||levels.length>5||!levels.every(level=>typeof level==="string"&&DIAGNOSTIC_LEVELS.has(level))||new Set(levels).size!==levels.length||!number(logs.sampleRate,0,1)||!integer(context.windowSeconds,5,300)||!integer(context.maxEntries,10,200)||!integer(context.maxBytes,16*1024,1024*1024)||!integer(upload.batchSize,1,100)||!integer(upload.batchMaxBytes,16*1024,1024*1024)||!integer(upload.flushMs,500,6e4)||!integer(upload.timeoutMs,1e3,3e4)||!integer(upload.maxRetries,0,12)||!integer(upload.offlineMaxBytes,256*1024,50*1024*1024)||!integer(upload.offlineTtlHours,1,168)||!integer(privacy.maxMessageBytes,128,4096)||!integer(privacy.maxStackBytes,4096,256*1024)||!stringList(privacy.denyKeys,100,128)||!stringList(privacy.redactUrlParams,100,128))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,endpointPath:raw.endpointPath,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{errors:{sampleRate:errors.sampleRate,captureUnhandled:errors.captureUnhandled,captureHandled:errors.captureHandled},logs:{levels:[...levels],sampleRate:logs.sampleRate},context:{windowSeconds:context.windowSeconds,maxEntries:context.maxEntries,maxBytes:context.maxBytes},upload:{batchSize:upload.batchSize,batchMaxBytes:upload.batchMaxBytes,flushMs:upload.flushMs,timeoutMs:upload.timeoutMs,maxRetries:upload.maxRetries,offlineMaxBytes:upload.offlineMaxBytes,offlineTtlHours:upload.offlineTtlHours},privacy:{maxMessageBytes:privacy.maxMessageBytes,maxStackBytes:privacy.maxStackBytes,denyKeys:[...privacy.denyKeys],redactUrlParams:[...privacy.redactUrlParams]}}}}function parseRemoteConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const c=raw.config;if(!c||typeof c!=="object")return null;const config=c;const candidate={captureClicks:config.captureClicks,captureText:config.captureText,maxTextLength:config.maxTextLength,sampleRate:config.sampleRate,allowSelectors:config.allowSelectors,denySelectors:config.denySelectors,captureHref:config.captureHref,captureTitle:config.captureTitle===void 0?true:config.captureTitle,captureAriaLabel:config.captureAriaLabel,captureRole:config.captureRole,captureName:config.captureName,captureId:config.captureId,captureDataTestId:config.captureDataTestId,capturePageviews:config.capturePageviews,capturePageleave:config.capturePageleave,capturePageDuration:config.capturePageDuration,captureVisibleDuration:config.captureVisibleDuration};const valid=bool(raw.enabled)&&number(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.schemaVersion)&&number(raw.configVersion,0,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.configVersion)&&typeof raw.platform==="string"&&number(raw.refreshIntervalSeconds,5,3600)&&bool(candidate.captureClicks)&&bool(candidate.captureText)&&number(candidate.maxTextLength,0,512)&&Number.isInteger(candidate.maxTextLength)&&number(candidate.sampleRate,0,1)&&strings(candidate.allowSelectors)&&strings(candidate.denySelectors)&&bool(candidate.captureHref)&&bool(candidate.captureTitle)&&bool(candidate.captureAriaLabel)&&bool(candidate.captureRole)&&bool(candidate.captureName)&&bool(candidate.captureId)&&bool(candidate.captureDataTestId)&&bool(candidate.capturePageviews)&&bool(candidate.capturePageleave)&&bool(candidate.capturePageDuration)&&bool(candidate.captureVisibleDuration);if(!valid)return null;const replay=parseReplayConfig(raw.replay);const diagnostics=parseDiagnosticsConfig(raw.diagnostics);return __spreadValues(__spreadValues({schemaVersion:raw.schemaVersion,configVersion:raw.configVersion,enabled:raw.enabled,platform:raw.platform,refreshIntervalSeconds:raw.refreshIntervalSeconds,config:candidate},raw.replay===void 0?{}:{replay}),raw.diagnostics===void 0?{}:{diagnostics})}function deriveConfigEndpoint(trackEndpoint){try{const base=typeof location!=="undefined"?location.href:void 0;const url=new URL(trackEndpoint,base);url.pathname=url.pathname.replace(/\/api\/v1\/track\/?$/,"/api/v1/config");url.search="";url.hash="";return url.toString()}catch(e){return trackEndpoint.replace(/\/api\/v1\/track\/?$/,"/api/v1/config")}}var SENSITIVE_TEXT=/(\d[\d\s-]{9,}\d)|([\w.+-]+@[\w-]+\.[\w.]+)|(\d{15,19})/g;function sanitizeText(input,maxLength=64){return input.replace(/\s+/g," ").trim().replace(SENSITIVE_TEXT,"[redacted]").slice(0,maxLength)}function coerceDatasetValue(raw){if(raw===void 0)return void 0;if(raw==="true")return true;if(raw==="false")return false;if(raw==="")return raw;const n=Number(raw);return Number.isFinite(n)&&String(n)===raw?n:raw}var wxSender=(endpoint,body,headers)=>new Promise((resolve,reject)=>{wx.request({url:endpoint,method:"POST",header:headers,data:body,timeout:1e4,success:res=>{if(res.statusCode>=200&&res.statusCode<300)return resolve();const e=new Error(`HTTP ${res.statusCode}`);e.status=res.statusCode;e.retryable=res.statusCode>=500||res.statusCode===429;reject(e)},fail:err=>{const e=new Error(err.errMsg);e.retryable=true;reject(e)}})});function wxStorage(){return{get(key){try{const v=wx.getStorageSync(key);return typeof v==="string"&&v?v:null}catch(e){return null}},set(key,value){try{wx.setStorageSync(key,value)}catch(e){}},remove(key){try{wx.removeStorageSync(key)}catch(e){}}}}var QUEUE_PREFIX="yz_q_";function imul32(a,b){if(typeof Math.imul==="function")return Math.imul(a,b);const ah=a>>>16&65535;const al=a&65535;const bh=b>>>16&65535;const bl=b&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0}function stableRuntimeHash(value){let hash=2166136261;for(let index=0;index<value.length;index+=1){hash^=value.charCodeAt(index);hash=imul32(hash,16777619)}return(hash>>>0).toString(16)}function storageNamespace(endpoint,writeKey){return`yz_mp_${stableRuntimeHash(`${endpoint}|${writeKey}`)}_`}function scopedWxStorage(endpoint,writeKey){const storage=wxStorage();const namespace=storageNamespace(endpoint,writeKey);return{get:key=>storage.get(namespace+key),set:(key,value)=>storage.set(namespace+key,value),remove:key=>storage.remove(namespace+key)}}function createWxPersistence(limit,queuePrefix){let known=-1;const keys=()=>{try{return wx.getStorageInfoSync().keys.filter(k=>k.slice(0,queuePrefix.length)===queuePrefix)}catch(e){return[]}};const readAll=()=>{const out=[];for(const k of keys()){try{const r=wx.getStorageSync(k);if(r==null?void 0:r.eventId)out.push(r)}catch(e){}}return out.sort((a,b)=>a.savedAt-b.savedAt)};return{load(){return __async(this,null,function*(){const all=readAll();known=all.length;return all.map(r=>r.payload)})},add(records){for(const r of records){try{wx.setStorageSync(queuePrefix+r.eventId,r)}catch(e){}}known=known<0?keys().length:known+records.length;if(known<=limit)return;const all=readAll();for(const r of all.slice(0,all.length-limit)){try{wx.removeStorageSync(queuePrefix+r.eventId)}catch(e){}}known=Math.min(all.length,limit)},remove(eventIds){for(const id of eventIds){try{wx.removeStorageSync(queuePrefix+id)}catch(e){}}if(known>0)known=Math.max(0,known-eventIds.length)}}}function wxPersistence(limit=500){return createWxPersistence(limit,QUEUE_PREFIX)}function scopedWxPersistence(endpoint,writeKey,limit=500){return createWxPersistence(limit,`${storageNamespace(endpoint,writeKey)}q_`)}function miniProgramDeviceType(deviceType,model){const normalized=deviceType==null?void 0:deviceType.trim().toLowerCase();if(normalized==="phone")return"mobile";if(normalized==="pad"||normalized==="tablet")return"tablet";if(normalized==="pc")return"desktop";const normalizedModel=model==null?void 0:model.trim();if(!normalizedModel)return null;if(/\b(?:ipad|tablet)\b/i.test(normalizedModel))return"tablet";if(/(?:^|[\s_-])pad(?:$|[\s_-])/i.test(normalizedModel))return"tablet";return null}function wxEnvContext(){try{const i=wx.getSystemInfoSync();const ctx={$runtime:"miniprogram"};const deviceType=miniProgramDeviceType(i.deviceType,i.model);if(deviceType)ctx.$device_type=deviceType;if(i.system)ctx.$os=i.system;if(i.model)ctx.$device_model=i.model;if(i.brand)ctx.$device_brand=i.brand;if(i.SDKVersion)ctx.$mp_sdk_version=i.SDKVersion;if(i.version)ctx.$wechat_version=i.version;return ctx}catch(e){return{$runtime:"miniprogram"}}}var SYSTEM_EVENTS=["$app_start","$app_foreground","$app_background","$pageview","$pageleave","$autocapture","$identify","$replay_diagnostic","$replay_focus","$experiment_exposure"];var isSystemEvent=name=>SYSTEM_EVENTS.includes(name);var SDK_NAME2="@yuanze_dev/tracker-miniprogram";var SDK_VERSION2="0.11.2";var instance=null;var captureSettings=DEFAULT_CAPTURE_SETTINGS;var captureEnabled=true;var configEtag;var configTimer=null;var configStorage=null;var configOptions=true;var configEndpoint="";var configWriteKey="";var configGeneration=0;var configRequest=null;function configCacheKey(writeKey){return`yz_capture_config_${stableRuntimeHash(writeKey)}_mini_program`}function applyRemoteConfig(payload){const runtime=autoTrackRuntimeSlot();const lifecycleChanged=payload.enabled!==captureEnabled||payload.config.capturePageviews!==captureSettings.capturePageviews||payload.config.capturePageleave!==captureSettings.capturePageleave||payload.config.capturePageDuration!==captureSettings.capturePageDuration||payload.config.captureVisibleDuration!==captureSettings.captureVisibleDuration;if(runtime&&lifecycleChanged){advanceCaptureEpoch(runtime)}captureSettings=payload.config;captureEnabled=payload.enabled;instance==null?void 0:instance.setConfigVersion(payload.configVersion);if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&lifecycleChanged)resumeLifecycle(runtime)}function loadCachedRemoteConfig(){try{const raw=configStorage==null?void 0:configStorage.get(configCacheKey(configWriteKey));if(!raw)return;const cached=JSON.parse(raw);const payload=parseRemoteConfig(cached.payload);if(!payload||payload.platform!=="mini-program")return;configEtag=cached.etag;applyRemoteConfig(payload)}catch(e){}}function refreshRemoteConfig(){if(configOptions===false||!configEndpoint||!configWriteKey)return Promise.resolve();if(configRequest)return configRequest;if(configTimer){clearTimeout(configTimer);configTimer=null}const options=typeof configOptions==="object"?configOptions:{};const generation=configGeneration;const endpoint=configEndpoint;const writeKey=configWriteKey;const storage=configStorage;const etag=configEtag;const request=new Promise(resolve=>{var _a,_b;let settled=false;const complete=()=>{var _a2;if(settled)return;settled=true;if(generation===configGeneration&&configOptions!==false){configTimer=setTimeout(()=>{void refreshRemoteConfig()},(_a2=options.refreshMs)!=null?_a2:45e3)}resolve()};try{const url=`${(_a=options.endpoint)!=null?_a:endpoint}?platform=mini-program`;wx.request({url,method:"GET",header:__spreadValues({"x-write-key":writeKey},etag?{"If-None-Match":etag}:{}),timeout:(_b=options.timeoutMs)!=null?_b:3e3,success:res=>{var _a2,_b2,_c;if(generation!==configGeneration)return;try{if(res.statusCode===304)return;if(res.statusCode<200||res.statusCode>=300)return;let data=res.data;if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){return}}const payload=parseRemoteConfig(data);if(!payload||payload.platform!=="mini-program")return;configEtag=(_c=(_a2=res.header)==null?void 0:_a2.ETag)!=null?_c:(_b2=res.header)==null?void 0:_b2.etag;storage==null?void 0:storage.set(configCacheKey(writeKey),JSON.stringify({etag:configEtag,savedAt:Date.now(),payload}));applyRemoteConfig(payload)}catch(e){}},fail:complete,complete})}catch(e){complete()}});const cleanup=()=>{if(configRequest===tracked)configRequest=null};const tracked=request.then(cleanup,cleanup);configRequest=tracked;return tracked}function dispose(){configGeneration+=1;if(configTimer){clearTimeout(configTimer);configTimer=null}configRequest=null;configOptions=false;configEndpoint="";configWriteKey="";configEtag=void 0;configStorage=null;captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;const current=instance;instance=null;current==null?void 0:current.dispose();disableOwnedAutoTrackRuntime()}function init(options){var _b;dispose();const _a=options,{envContext=true,persist=true,autoTrack=true,remoteConfig=true}=_a,rest=__objRest(_a,["envContext","persist","autoTrack","remoteConfig"]);configStorage=wxStorage();const identityStorage=scopedWxStorage(rest.endpoint,rest.writeKey);instance=new Tracker(__spreadProps(__spreadValues({},rest),{platform:"miniprogram",sdkName:SDK_NAME2,sdkVersion:SDK_VERSION2,sender:wxSender,storage:identityStorage,persistence:persist?scopedWxPersistence(rest.endpoint,rest.writeKey,(_b=rest.maxQueueSize)!=null?_b:500):false}));if(envContext)instance.register(wxEnvContext());captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;configEtag=void 0;configOptions=remoteConfig;configEndpoint=deriveConfigEndpoint(rest.endpoint);configWriteKey=rest.writeKey;if(remoteConfig!==false)loadCachedRemoteConfig();if(autoTrack)enableAutoTrack();else bindAutoTrackRuntime(false);if(remoteConfig!==false)void refreshRemoteConfig();return instance}function getTracker(){return instance}function ensure(){if(!instance)throw new Error("tracker 未初始化,请先在 app.js 里调用 init()");return instance}function track(name,properties={}){ensure().trackUnsafe(name,properties)}function register(props){ensure().register(props)}function identify(id,options){ensure().identify(id,options)}function reset(){ensure().reset()}function flush(){return ensure().flush()}function trackTap(e){var _a,_b;const ds=(_b=(_a=e==null?void 0:e.currentTarget)==null?void 0:_a.dataset)!=null?_b:{};const name=ds.track;if(typeof name!=="string"||!name)return;const props={};for(const k of Object.keys(ds)){if(k==="track"||TEXT_METADATA_KEYS.has(k))continue;const v=ds[k];props[k]=typeof v==="string"?coerceDatasetValue(v):v}instance==null?void 0:instance.trackUnsafe(name,props)}var TEXT_METADATA_KEYS=new Set(["yzCapture","yzOwner","yzText","yzAdapter"]);var AUTO_TRACK_RUNTIME_KEY="__yz_tracker_miniprogram_auto_track_runtime__";var MODULE_RUNTIME_OWNER={};var FALLBACK_RUNTIME_ROOT={};function runtimeRoot(){if(typeof globalThis!=="undefined"){return globalThis}if(typeof wx==="object"&&wx){return wx}return FALLBACK_RUNTIME_ROOT}function autoTrackRuntimeSlot(){var _a;return(_a=runtimeRoot()[AUTO_TRACK_RUNTIME_KEY])!=null?_a:null}function advanceCaptureEpoch(runtime){runtime.epoch=Number.isFinite(runtime.epoch)?runtime.epoch+1:1}function resumeLifecycle(runtime){try{runtime.resumeApp()}catch(e){}if(runtime.appVisible===false)return;for(const resume of runtime.visiblePages.values()){try{resume()}catch(e){}}}function disableOwnedAutoTrackRuntime(){const runtime=autoTrackRuntimeSlot();if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&runtime.enabled){runtime.enabled=false;advanceCaptureEpoch(runtime)}}function bindAutoTrackRuntime(enabled){var _a,_b,_c,_d,_e;const root=runtimeRoot();const runtime=(_a=autoTrackRuntimeSlot())!=null?_a:{owner:null,enabled:false,epoch:0,interactionDepth:0,disposeOwner:null,captureState:()=>({enabled:false,epoch:0,settings:DEFAULT_CAPTURE_SETTINGS}),captureInteraction:()=>void 0,invokeInteraction:(self,args,method)=>method.apply(self,args),track:()=>void 0,flush:()=>void 0,refresh:()=>void 0,resumeApp:()=>void 0,appVisible:null,visiblePages:new Map};if(runtime.owner&&runtime.owner!==MODULE_RUNTIME_OWNER){try{(_b=runtime.disposeOwner)==null?void 0:_b.call(runtime)}catch(e){}}if(!Number.isFinite(runtime.epoch))runtime.epoch=0;if(!Number.isFinite(runtime.interactionDepth))runtime.interactionDepth=0;(_c=runtime.resumeApp)!=null?_c:runtime.resumeApp=()=>void 0;(_d=runtime.appVisible)!=null?_d:runtime.appVisible=null;(_e=runtime.visiblePages)!=null?_e:runtime.visiblePages=new Map;runtime.owner=MODULE_RUNTIME_OWNER;if(runtime.enabled!==enabled){runtime.enabled=enabled;advanceCaptureEpoch(runtime)}runtime.disposeOwner=dispose;runtime.captureState=()=>({enabled:runtime.enabled&&captureEnabled&&instance!==null,epoch:runtime.epoch,settings:captureSettings});runtime.captureInteraction=(self,event)=>{if(runtime.enabled&&runtime.interactionDepth===0)captureInteraction(self,event)};runtime.invokeInteraction=(self,args,method)=>{var _a2,_b2;if(runtime.interactionDepth>0)return method.apply(self,args);let unmarkedComponent=false;try{const context=self;const dataset=(_b2=(_a2=args[0])==null?void 0:_a2.currentTarget)==null?void 0:_b2.dataset;unmarkedComponent=!!(context==null?void 0:context.is)&&!context.route&&!context.__route__&&(dataset==null?void 0:dataset.yzCapture)!=="1"&&(dataset==null?void 0:dataset.yzCapture)!==1}catch(e){}if(unmarkedComponent)return method.apply(self,args);const epoch=runtime.epoch;const owner=runtime.owner;let properties;try{if(runtime.enabled){properties=snapshotInteraction(self,args[0])}}catch(e){}runtime.interactionDepth+=1;try{return method.apply(self,args)}finally{runtime.interactionDepth-=1;try{if(properties&&runtime.enabled&&runtime.epoch===epoch&&runtime.owner===owner&&captureEnabled&&captureSettings.captureClicks){if(!captureSettings.captureText)delete properties.$text;else if(typeof properties.$text==="string"){const text=sanitizeText(properties.$text,captureSettings.maxTextLength);if(text)properties.$text=text;else delete properties.$text}instance==null?void 0:instance.track("$autocapture",properties)}}catch(e){}}};runtime.track=(name,properties)=>{if(runtime.enabled)instance==null?void 0:instance.trackUnsafe(name,properties)};runtime.flush=(unloading=false)=>{if(runtime.enabled)void(instance==null?void 0:instance.flush(unloading).catch(()=>void 0))};runtime.refresh=()=>{if(runtime.enabled)void refreshRemoteConfig()};root[AUTO_TRACK_RUNTIME_KEY]=runtime;return runtime}var PAGE_LIFECYCLE_HOOKS=new Set(["onLoad","onShow","onReady","onHide","onUnload","onPullDownRefresh","onReachBottom","onShareAppMessage","onShareTimeline","onAddToFavorites","onPageScroll","onResize","onTabItemTap","onSaveExitState"]);var INTERACTION_WRAPPED="__yz_tracker_interaction_wrapped__";var LIFECYCLE_WRAPPED="__yz_tracker_lifecycle_wrapped__";function routeOf(self){var _a,_b;const direct=(_a=self==null?void 0:self.route)!=null?_a:self==null?void 0:self.__route__;if(direct)return direct;try{if(typeof getCurrentPages==="function"){const pages=getCurrentPages();const current=(_b=pages[pages.length-1])==null?void 0:_b.route;if(current)return current}}catch(e){}const componentPath=self==null?void 0:self.is;return componentPath?`miniprogram://component/${componentPath}`:"miniprogram://app"}var SENSITIVE_TARGET=/(?:^|[-_:])(captcha\d*|verify|verification|otp|password|passwd|credential)(?:$|[-_:])/i;var SENSITIVE_DATASET_KEYS=["sensitive","noTrack","yzSensitive","yzNoTrack","trackSensitive"];function isSensitiveInteraction(target){if(!target)return false;if(typeof target.id==="string"&&SENSITIVE_TARGET.test(target.id))return true;const dataset=target.dataset;return!!dataset&&SENSITIVE_DATASET_KEYS.some(key=>Object.prototype.hasOwnProperty.call(dataset,key))}function snapshotInteraction(self,event){var _a,_b,_c;if(!captureEnabled||!captureSettings.captureClicks||!event)return;const target=event.currentTarget;if(isSensitiveInteraction(target))return;const dataset=(_a=target==null?void 0:target.dataset)!=null?_a:{};const generated=dataset.yzCapture==="1"||dataset.yzCapture===1;const adaptedClick=generated&&dataset.yzAdapter==="tdesign-grid-item"&&event.type==="click";if(event.type!=="tap"&&event.type!=="longpress"&&event.type!=="longtap"&&!adaptedClick)return;const mark=event.mark;if(mark&&(Object.prototype.hasOwnProperty.call(mark,"yzSensitive")||typeof mark.yzNamed==="string"&&mark.yzNamed))return;if(generated&&typeof(mark==null?void 0:mark.yzOwner)==="string"&&mark.yzOwner!==dataset.yzOwner)return;if(typeof dataset.track==="string"&&dataset.track)return;const id=typeof(target==null?void 0:target.id)==="string"&&target.id?target.id:void 0;const route=routeOf(self);const componentPath=self==null?void 0:self.is;const pageRoute=(_b=self==null?void 0:self.route)!=null?_b:self==null?void 0:self.__route__;if(componentPath&&!pageRoute&&!generated)return;let text;if(captureSettings.captureText&&captureSettings.maxTextLength>0){const raw=(_c=dataset.yzText)!=null?_c:mark==null?void 0:mark.yzText;if(typeof raw==="string"&&raw.length<=4096&&!/^\d{4,8}$/.test(raw.trim())){text=sanitizeText(raw,captureSettings.maxTextLength)||void 0}}return __spreadValues(__spreadValues({$tag:"miniprogram",$selector:id?`#${id}`:`miniprogram:${route}`,$url:route,$role:event.type==="tap"||adaptedClick?"tap":"longpress"},id?{$element_id:id}:{}),text?{$text:text}:{})}function captureInteraction(self,event){const properties=snapshotInteraction(self,event);if(properties)instance==null?void 0:instance.track("$autocapture",properties)}function wrapInteractionMethods(methods,runtime,ignored=new Set){for(const name of Object.keys(methods)){const value=methods[name];if(ignored.has(name)||typeof value!=="function")continue;if(value[INTERACTION_WRAPPED])continue;const wrapped=function(...args){return runtime.invokeInteraction(this,args,value)};Object.defineProperty(wrapped,INTERACTION_WRAPPED,{value:true});methods[name]=wrapped}}function wrapPageInteractions(options,runtime){wrapInteractionMethods(options,runtime,PAGE_LIFECYCLE_HOOKS)}function wrap(hooks,name,extra){const original=hooks[name];if(typeof original==="function"&&original[LIFECYCLE_WRAPPED])return;const wrapped=function(...args){try{extra(this,args)}catch(e){}return typeof original==="function"?original.apply(this,args):void 0};Object.defineProperty(wrapped,LIFECYCLE_WRAPPED,{value:true});hooks[name]=wrapped}function installAutoTrackRuntime(enabled){const runtime=bindAutoTrackRuntime(enabled);if(typeof Page==="function"&&!Page.__yzAutoTrack){runtime.visiblePages.clear();const originalPage=Page;const patched=(options=>{const enteredAt=new WeakMap;const enter=self=>{var _a;const capture=runtime.captureState();if(runtime.appVisible===false||!capture.enabled||!capture.settings.capturePageviews)return;if(((_a=enteredAt.get(self))==null?void 0:_a.epoch)===capture.epoch)return;enteredAt.set(self,{at:Date.now(),epoch:capture.epoch});runtime.track("$pageview",{$url:routeOf(self)})};const leave=self=>{runtime.visiblePages.delete(self);const entry=enteredAt.get(self);enteredAt.delete(self);if(!entry)return;const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Math.max(0,Date.now()-entry.at)}:{}));runtime.flush(runtime.appVisible===false)};try{wrap(options,"onShow",self=>{runtime.visiblePages.set(self,()=>enter(self));enter(self)});wrap(options,"onHide",self=>leave(self));wrap(options,"onUnload",self=>leave(self));wrapPageInteractions(options,runtime)}catch(e){}return originalPage(options)});for(const key of Object.keys(originalPage))patched[key]=originalPage[key];patched.__yzAutoTrack=true;try{Page=patched}catch(e){}}if(typeof Component==="function"&&!Component.__yzTextTrack){const originalComponent=Component;const patched=(options=>{try{if(options.methods&&typeof options.methods==="object"){wrapInteractionMethods(options.methods,runtime)}}catch(e){}return originalComponent(options)});for(const key of Object.keys(originalComponent))patched[key]=originalComponent[key];patched.__yzTextTrack=true;try{Component=patched}catch(e){}}if(typeof App==="function"&&!App.__yzAutoTrack){runtime.resumeApp=()=>void 0;runtime.appVisible=null;const originalApp=App;const patched=(options=>{let launched=false;let visible=false;let startRecorded=false;let launchProperties={};let foregroundAt=Date.now();let foregroundEpoch=null;const resume=()=>{const capture=runtime.captureState();if(!launched||!visible||!capture.enabled)return;if(foregroundEpoch!==capture.epoch){foregroundAt=Date.now();foregroundEpoch=capture.epoch}if(!startRecorded){startRecorded=true;runtime.track("$app_start",launchProperties);runtime.flush()}};runtime.resumeApp=resume;try{wrap(options,"onLaunch",(_self,args)=>{var _a;const launch=(_a=args[0])!=null?_a:{};launched=true;visible=true;runtime.appVisible=true;startRecorded=false;foregroundEpoch=null;launchProperties=__spreadValues(__spreadValues({},typeof launch.scene==="number"?{$scene:launch.scene}:{}),typeof launch.path==="string"&&launch.path?{$path:launch.path}:{});resume()});wrap(options,"onHide",()=>{const capture=runtime.captureState();if(visible&&capture.enabled&&foregroundEpoch===capture.epoch){runtime.track("$app_background",{$duration_ms:Math.max(0,Date.now()-foregroundAt),$state:"hidden"})}visible=false;runtime.appVisible=false;foregroundEpoch=null;runtime.flush(true)});wrap(options,"onShow",(_self,args)=>{var _a;const show=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();const wasVisible=visible;visible=true;runtime.appVisible=true;if(!capture.enabled){foregroundEpoch=null;return}if(launched&&startRecorded&&!wasVisible){runtime.track("$app_foreground",__spreadProps(__spreadValues(__spreadValues({},typeof show.scene==="number"?{$scene:show.scene}:{}),typeof show.path==="string"&&show.path?{$path:show.path}:{}),{$previous_state:"hidden"}))}resume();runtime.refresh()})}catch(e){}return originalApp(options)});for(const key of Object.keys(originalApp))patched[key]=originalApp[key];patched.__yzAutoTrack=true;try{App=patched}catch(e){}}if(enabled)resumeLifecycle(runtime)}function installAutoTrack(){installAutoTrackRuntime(false)}function enableAutoTrack(){installAutoTrackRuntime(true)}var tracker={init,getTracker,track,register,identify,reset,flush,dispose,trackTap,installAutoTrack,enableAutoTrack,refreshRemoteConfig};var index_default=tracker;
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __defProps=Object.defineProperties;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropDescs=Object.getOwnPropertyDescriptors||function(object){var descriptors={};var names=__getOwnPropNames(object);for(var index=0;index<names.length;index++){var key=names[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}if(__getOwnPropSymbols){var symbols=__getOwnPropSymbols(object);for(var index=0;index<symbols.length;index++){var key=symbols[index];__defProp(descriptors,key,{value:__getOwnPropDesc(object,key),enumerable:true,configurable:true,writable:true})}}return descriptors};var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __pow=Math.pow;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b));var __objRest=(source,exclude)=>{var target={};for(var prop in source)if(__hasOwnProp.call(source,prop)&&exclude.indexOf(prop)<0)target[prop]=source[prop];if(source!=null&&__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(source)){if(exclude.indexOf(prop)<0&&__propIsEnum.call(source,prop))target[prop]=source[prop]}return target};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var __async=(__this,__arguments,generator)=>{return new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}};var rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}};var step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())})};var index_exports={};__export(index_exports,{SDK_NAME:()=>SDK_NAME2,SDK_VERSION:()=>SDK_VERSION2,SYSTEM_EVENTS:()=>SYSTEM_EVENTS,default:()=>index_default,dispose:()=>dispose,enableAutoTrack:()=>enableAutoTrack,flush:()=>flush,getTestingSenderState:()=>getTestingSenderState,getTracker:()=>getTracker,identify:()=>identify,init:()=>init,installAutoTrack:()=>installAutoTrack,isSystemEvent:()=>isSystemEvent,refreshRemoteConfig:()=>refreshRemoteConfig,register:()=>register,reset:()=>reset,track:()=>track,trackTap:()=>trackTap,tracker:()=>tracker,wxEnvContext:()=>wxEnvContext,wxPersistence:()=>wxPersistence,wxSender:()=>wxSender,wxStorage:()=>wxStorage});module.exports=__toCommonJS(index_exports);function uuid(){const c=typeof globalThis==="undefined"?void 0:globalThis.crypto;if(typeof(c==null?void 0:c.randomUUID)==="function"){try{return c.randomUUID()}catch(e){}}if(typeof(c==null?void 0:c.getRandomValues)==="function"){try{const b2=c.getRandomValues(new Uint8Array(16));return formatUuid(b2)}catch(e){}}const b=new Uint8Array(16);for(let i=0;i<16;i+=1)b[i]=Math.floor(Math.random()*256);return formatUuid(b)}function formatUuid(b){b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=[];for(let i=0;i<16;i+=1){const value=b[i].toString(16);hex.push(value.length===1?`0${value}`:value)}const s=hex.join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function memoryStorage(){const m=new Map;return{get:k=>{var _a;return(_a=m.get(k))!=null?_a:null},set:(k,v)=>void m.set(k,v),remove:k=>void m.delete(k)}}function webStorage(){const mem=memoryStorage();let ls=null;try{ls=typeof localStorage!=="undefined"?localStorage:null}catch(e){ls=null}if(!ls)return mem;return{get(k){try{return ls.getItem(k)}catch(e){return mem.get(k)}},set(k,v){try{ls.setItem(k,v)}catch(e){mem.set(k,v)}},remove(k){try{ls.removeItem(k)}catch(e){mem.remove(k)}}}}var STORAGE_KEYS={anonymousId:"yz_anon",userId:"yz_uid",userUuid:"yz_user_uuid",session:"yz_session"};var SESSION_TIMEOUT_MS=30*60*1e3;var TOUCH_PERSIST_MS=60*1e3;function normalizeSnapshot(snapshot){var _a,_b,_c,_d,_e;const anonymousId=String((_a=snapshot==null?void 0:snapshot.anonymousId)!=null?_a:"").trim();const sessionId=String((_b=snapshot==null?void 0:snapshot.sessionId)!=null?_b:"").trim();const userId=String((_c=snapshot==null?void 0:snapshot.userId)!=null?_c:"").trim()||null;const userUuid=userId?String((_d=snapshot==null?void 0:snapshot.userUuid)!=null?_d:"").trim()||null:null;const distinctId=userId!=null?userId:anonymousId;const distinctIdType=userId?"user_id":"anonymous_id";if(!anonymousId||!sessionId)return null;if(String((_e=snapshot==null?void 0:snapshot.distinctId)!=null?_e:"").trim()!==distinctId)return null;if((snapshot==null?void 0:snapshot.distinctIdType)!==distinctIdType)return null;return{anonymousId,userId,userUuid,sessionId}}function dayKey(ts){const d=new Date(ts);const p=n=>n<10?`0${n}`:String(n);return`${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`}var Identity=class{constructor(store,now=Date.now,initialSnapshot){__publicField(this,"store",store);__publicField(this,"now",now);__publicField(this,"anonymousId");__publicField(this,"userId");__publicField(this,"userUuid");__publicField(this,"session");__publicField(this,"persistedAt");var _a;const initial=initialSnapshot?normalizeSnapshot(initialSnapshot):null;if(initial){this.anonymousId=initial.anonymousId;this.userId=initial.userId;this.userUuid=initial.userUuid;const at=this.now();this.session={id:initial.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot()}else{this.anonymousId=(_a=this.store.get(STORAGE_KEYS.anonymousId))!=null?_a:this.newAnonymousId();this.userId=this.store.get(STORAGE_KEYS.userId)||null;this.userUuid=this.store.get(STORAGE_KEYS.userUuid)||null;this.session=this.loadSession()}this.persistedAt=this.session.lastActive}persistSnapshot(){this.store.set(STORAGE_KEYS.anonymousId,this.anonymousId);if(this.userId)this.store.set(STORAGE_KEYS.userId,this.userId);else this.store.remove(STORAGE_KEYS.userId);if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session))}newAnonymousId(){const id=`anon_${uuid()}`;this.store.set(STORAGE_KEYS.anonymousId,id);return id}loadSession(){const raw=this.store.get(STORAGE_KEYS.session);if(raw){try{const s=JSON.parse(raw);if((s==null?void 0:s.id)&&typeof s.lastActive==="number"&&!this.expired(s,this.now()))return s}catch(e){}}return this.startSession(this.now())}expired(s,at){return at-s.lastActive>SESSION_TIMEOUT_MS||s.day!==dayKey(at)}startSession(at){const s={id:uuid(),lastActive:at,day:dayKey(at)};this.store.set(STORAGE_KEYS.session,JSON.stringify(s));this.persistedAt=at;return s}touch(){const at=this.now();if(this.expired(this.session,at)){this.session=this.startSession(at);return}this.session.lastActive=at;if(at-this.persistedAt>=TOUCH_PERSIST_MS){this.store.set(STORAGE_KEYS.session,JSON.stringify(this.session));this.persistedAt=at}}identify(userId,options){var _a;const id=String(userId!=null?userId:"").trim();if(!id)return false;const userChanged=id!==this.userId;const uuidWasProvided=(options==null?void 0:options.userUuid)!==void 0;const nextUuid=uuidWasProvided?String((_a=options.userUuid)!=null?_a:"").trim()||null:this.userUuid;const uuidChanged=nextUuid!==this.userUuid;if(!userChanged&&!uuidChanged)return false;this.userId=id;this.store.set(STORAGE_KEYS.userId,id);this.userUuid=userChanged&&!uuidWasProvided?null:nextUuid;if(this.userUuid)this.store.set(STORAGE_KEYS.userUuid,this.userUuid);else this.store.remove(STORAGE_KEYS.userUuid);return true}reset(anonymousId){this.userId=null;this.store.remove(STORAGE_KEYS.userId);this.userUuid=null;this.store.remove(STORAGE_KEYS.userUuid);const sharedAnonymousId=anonymousId==null?void 0:anonymousId.trim();if(sharedAnonymousId){this.anonymousId=sharedAnonymousId;this.store.set(STORAGE_KEYS.anonymousId,sharedAnonymousId)}else{this.anonymousId=this.newAnonymousId()}this.session=this.startSession(this.now())}snapshot(){var _a;return{distinctId:(_a=this.userId)!=null?_a:this.anonymousId,distinctIdType:this.userId?"user_id":"anonymous_id",anonymousId:this.anonymousId,userId:this.userId,userUuid:this.userUuid,sessionId:this.session.id}}applySnapshot(snapshot){const next=normalizeSnapshot(snapshot);if(!next)return false;const before=this.snapshot();if(before.userId!==null&&before.userId!==next.userId&&before.anonymousId===next.anonymousId)return false;const at=this.now();this.anonymousId=next.anonymousId;this.userId=next.userId;this.userUuid=next.userUuid;this.session={id:next.sessionId,lastActive:at,day:dayKey(at)};this.persistSnapshot();this.persistedAt=at;const after=this.snapshot();return before.anonymousId!==after.anonymousId||before.userId!==after.userId||before.userUuid!==after.userUuid||before.sessionId!==after.sessionId}setAnonymousId(id){this.anonymousId=id;this.store.set(STORAGE_KEYS.anonymousId,id)}};var DB_NAME="yz_tracker";var STORE="queue";var DEFAULT_LIMIT=500;function openDb(dbName){return new Promise((resolve,reject)=>{const req=indexedDB.open(dbName,1);req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(STORE)){db.createObjectStore(STORE,{keyPath:"eventId"}).createIndex("savedAt","savedAt")}};req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);req.onblocked=()=>reject(new Error("indexedDB blocked"))})}function indexedDbPersistence(opts={}){var _a,_b;if(typeof indexedDB==="undefined")return null;const dbName=(_a=opts.dbName)!=null?_a:DB_NAME;const limit=(_b=opts.limit)!=null?_b:DEFAULT_LIMIT;let dbPromise=null;const db=()=>{dbPromise!=null?dbPromise:dbPromise=openDb(dbName);return dbPromise};const write=fn=>__async(null,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readwrite");fn(tx.objectStore(STORE))}catch(e){}});return{load(){return __async(this,null,function*(){try{const d=yield db();const tx=d.transaction(STORE,"readonly");const req=tx.objectStore(STORE).index("savedAt").getAll();const rows=yield new Promise((resolve,reject)=>{req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error)});return rows.map(r=>r.payload)}catch(e){return[]}})},add(records){void write(store=>{for(const r of records)store.put(r);const countReq=store.count();countReq.onsuccess=()=>{const over=countReq.result-limit;if(over<=0)return;let dropped=0;const cur=store.index("savedAt").openCursor();cur.onsuccess=()=>{const c=cur.result;if(!c||dropped>=over)return;c.delete();dropped+=1;c.continue()}}})},remove(eventIds){if(!eventIds.length)return;void write(store=>{for(const id of eventIds)store.delete(id)})}}}var SDK_NAME="@yuanze_dev/tracker";var SDK_VERSION="0.16.3";var PROTOCOL_VERSION=1;var MAX_BATCH_SIZE=50;var PLATFORMS=["web","pc","flutter","ios","android","miniprogram","backend","electron-renderer","electron-main","tauri-web","tauri-rust","node"];var documentPageInstanceId;function currentPageInstanceId(){if(typeof window==="undefined"||typeof document==="undefined")return void 0;documentPageInstanceId!=null?documentPageInstanceId:documentPageInstanceId=uuid();return documentPageInstanceId}var MAX_BACKOFF_MS=3e4;var Tracker=class{constructor(opts){__publicField(this,"queue",[]);__publicField(this,"timer",null);__publicField(this,"disposed",false);__publicField(this,"superProps",{});__publicField(this,"identity");__publicField(this,"persistence");__publicField(this,"send");__publicField(this,"endpoint");__publicField(this,"writeKey");__publicField(this,"platform");__publicField(this,"appVersion");__publicField(this,"sdkName");__publicField(this,"sdkVersion");__publicField(this,"maxBatch");__publicField(this,"flushMs");__publicField(this,"maxQueueSize");__publicField(this,"pageInstanceId");__publicField(this,"sessionAuthority");__publicField(this,"flushing",false);__publicField(this,"flushWaiters",[]);__publicField(this,"retryCount",0);__publicField(this,"droppedEventCount",0);__publicField(this,"configVersion",0);__publicField(this,"pageviewHandler",null);__publicField(this,"pageleaveHandler",null);__publicField(this,"diagnosticsBridge",null);__publicField(this,"disposeHandlers",[]);__publicField(this,"identityChangeHandlers",[]);var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k;this.endpoint=opts.endpoint;this.writeKey=opts.writeKey;this.platform=(_a=opts.platform)==null?void 0:_a.trim().toLowerCase();this.appVersion=opts.appVersion;this.sdkName=(_b=opts.sdkName)!=null?_b:SDK_NAME;this.sdkVersion=(_c=opts.sdkVersion)!=null?_c:SDK_VERSION;this.maxBatch=(_d=opts.maxBatch)!=null?_d:5;this.flushMs=(_e=opts.flushMs)!=null?_e:5e3;this.maxQueueSize=(_f=opts.maxQueueSize)!=null?_f:500;this.pageInstanceId=currentPageInstanceId();this.sessionAuthority=(_g=opts.sessionAuthority)!=null?_g:"local";this.send=(_h=opts.sender)!=null?_h:defaultFetchSender;this.identity=new Identity((_i=opts.storage)!=null?_i:webStorage(),Date.now,opts.initialIdentity);if(opts.distinctId&&!opts.initialIdentity)this.identity.setAnonymousId(opts.distinctId);this.superProps=__spreadValues({},(_j=opts.initialProperties)!=null?_j:{});this.persistence=opts.persistence===false?null:(_k=opts.persistence)!=null?_k:indexedDbPersistence({limit:this.maxQueueSize});void this.restore();if(this.platform&&PLATFORMS.indexOf(this.platform)<0){console.error(`[tracker] platform "${this.platform}" 不在受控端列表里,按端分析时这批数据会自成一端。可选值:${PLATFORMS.join(" / ")}(微信小程序是 miniprogram,不是 wechat)`)}if(typeof document!=="undefined"){const onVisibilityChange=()=>{if(document.visibilityState==="hidden")this.flush(true)};document.addEventListener("visibilitychange",onVisibilityChange);this.addDisposeHandler(()=>document.removeEventListener("visibilitychange",onVisibilityChange));if(typeof window!=="undefined"){const onPageHide=()=>this.flush(true);window.addEventListener("pagehide",onPageHide);this.addDisposeHandler(()=>window.removeEventListener("pagehide",onPageHide))}}}restore(){return __async(this,null,function*(){if(!this.persistence)return;const saved=yield this.persistence.load();if(this.disposed)return;const known=new Set(this.queue.map(e=>e.eventId));const revived=saved.filter(e=>(e==null?void 0:e.eventId)&&!known.has(e.eventId));if(!revived.length)return;this.queue.unshift(...revived);this.trim();void this.flush()})}register(props){for(const key of Object.keys(props))this.superProps[key]=props[key]}identify(id,options){const before=this.identity.snapshot();if(!this.identity.identify(id,options))return;this.enqueue("$identify",{});const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}reset(anonymousId){const before=this.identity.snapshot();this.identity.reset(anonymousId);const after=this.identity.snapshot();for(const handler of this.identityChangeHandlers)handler(before,after)}getDistinctId(){return this.identity.snapshot().distinctId}getAnonymousId(){return this.identity.snapshot().anonymousId}getSessionId(){return this.identity.snapshot().sessionId}getPageInstanceId(){return this.pageInstanceId}getIdentitySnapshot(){return this.identity.snapshot()}touchIdentity(){const before=this.identity.snapshot();if(this.sessionAuthority==="external")return before;this.identity.touch();const after=this.identity.snapshot();if(before.sessionId!==after.sessionId){for(const handler of this.identityChangeHandlers)handler(before,after)}return after}applyIdentitySnapshot(snapshot,options={}){const before=this.identity.snapshot();const changed=this.identity.applySnapshot(snapshot);if(!changed)return false;const after=this.identity.snapshot();const identityChanged=before.userId!==after.userId||before.userUuid!==after.userUuid;if(options.emitIdentify===true&&before.anonymousId===after.anonymousId&&after.userId!==null&&identityChanged){this.enqueue("$identify",{})}for(const handler of this.identityChangeHandlers)handler(before,after);return true}setConfigVersion(version){if(Number.isInteger(version)&&version>=0)this.configVersion=version}getConfigVersion(){return this.configVersion}get pending(){return this.queue.length}get droppedEvents(){return this.droppedEventCount}dispose(){this.disposed=true;if(this.timer){clearTimeout(this.timer);this.timer=null}this.diagnosticsBridge=null;for(const handler of this.disposeHandlers.splice(0))handler()}addDisposeHandler(handler){this.disposeHandlers.push(handler)}addIdentityChangeHandler(handler){this.identityChangeHandlers.push(handler);const remove=()=>{this.identityChangeHandlers=this.identityChangeHandlers.filter(candidate=>candidate!==handler)};this.addDisposeHandler(remove);return remove}setPageviewHandler(handler){this.pageviewHandler=handler}setPageleaveHandler(handler){this.pageleaveHandler=handler}setDiagnosticsBridge(bridge){this.diagnosticsBridge=bridge}captureException(error,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.captureException(error,options))!=null?_b:null}log(level,message,options){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.log(level,message,options))!=null?_b:null}flushDiagnostics(){var _a,_b;return(_b=(_a=this.diagnosticsBridge)==null?void 0:_a.flush())!=null?_b:Promise.resolve()}pageview(input){const url=typeof input==="string"?input:input==null?void 0:input.$url;if(this.pageviewHandler)this.pageviewHandler(url);else if(input&&typeof input==="object")this.track("$pageview",input);else if(url)this.track("$pageview",{$url:url})}pageleave(){var _a;(_a=this.pageleaveHandler)==null?void 0:_a.call(this)}track(name,properties){this.enqueue(name,properties!=null?properties:{})}trackUnsafe(name,properties={}){this.enqueue(name,properties)}captureAs(who,name,properties={},options={}){this.enqueue(name,properties,who,options)}enqueue(name,properties,override,options={}){var _a,_b,_c,_d;if(this.disposed)return;const who=override!=null?override:this.touchIdentity();const raw={eventId:(_a=options.eventId)!=null?_a:uuid(),eventName:name,distinctId:who.distinctId,distinctIdType:who.distinctIdType,anonymousId:who.anonymousId,userId:(_b=who.userId)!=null?_b:void 0,userUuid:(_c=who.userUuid)!=null?_c:void 0,sessionId:who.sessionId,pageInstanceId:this.pageInstanceId,platform:this.platform,appVersion:this.appVersion,clientTime:new Date().toISOString(),properties:__spreadProps(__spreadValues(__spreadValues({},this.superProps),properties),{$sdk_name:this.sdkName,$sdk_version:this.sdkVersion,$protocol_version:PROTOCOL_VERSION,$config_version:this.configVersion})};this.queue.push(raw);(_d=this.persistence)==null?void 0:_d.add([{eventId:raw.eventId,savedAt:Date.now(),payload:raw}]);this.trim();if(this.queue.length>=this.maxBatch)this.flush();else this.schedule()}trim(){var _a;const overflow=this.queue.length-this.maxQueueSize;if(overflow>0){const dropped=this.queue.splice(0,overflow);this.droppedEventCount+=dropped.length;(_a=this.persistence)==null?void 0:_a.remove(dropped.map(e=>e.eventId));console.warn(`[tracker] 队列超过 ${this.maxQueueSize} 条,丢弃最旧的 ${overflow} 条`)}}schedule(delayMs=this.flushMs){if(this.disposed||this.timer)return;this.timer=setTimeout(()=>this.flush(),delayMs)}flush(unloading=false){return __async(this,null,function*(){var _a,_b;if(this.disposed)return;if(this.timer){clearTimeout(this.timer);this.timer=null}if(this.flushing&&!unloading){yield new Promise(resolve=>this.flushWaiters.push(resolve));if(this.queue.length>0)yield this.flush();return}if(this.queue.length===0)return;this.flushing=true;const batch=this.queue.splice(0,Math.min(MAX_BATCH_SIZE,this.queue.length));const body=JSON.stringify({events:batch,protocolVersion:PROTOCOL_VERSION});const headers={"Content-Type":"application/json","x-write-key":this.writeKey};try{yield this.send(this.endpoint,body,headers,unloading);(_a=this.persistence)==null?void 0:_a.remove(batch.map(e=>e.eventId));this.retryCount=0}catch(err){if((err==null?void 0:err.retryable)!==false){this.queue.unshift(...batch);this.trim();this.retryCount+=1}else{this.droppedEventCount+=batch.length;console.warn("[tracker] 丢弃一批(不可重试):",err==null?void 0:err.status);(_b=this.persistence)==null?void 0:_b.remove(batch.map(e=>e.eventId));this.retryCount=0}}finally{this.flushing=false;for(const resolve of this.flushWaiters.splice(0))resolve()}if(this.queue.length>0&&!unloading){this.schedule(Math.min(this.flushMs*__pow(2,this.retryCount),MAX_BACKOFF_MS))}})}};var defaultFetchSender=(endpoint,body,headers,keepalive)=>__async(null,null,function*(){const res=yield fetch(endpoint,{method:"POST",headers,body,keepalive});if(!res.ok){const e=new Error(`HTTP ${res.status}`);e.status=res.status;e.retryable=res.status>=500||res.status===429;throw e}});var DEFAULT_CAPTURE_SETTINGS={captureClicks:true,captureText:true,maxTextLength:64,sampleRate:1,allowSelectors:["a","button",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','input[type="submit"]','input[type="button"]',"summary"],denySelectors:["[data-no-track]",".yz-no-track"],captureHref:true,captureTitle:true,captureAriaLabel:true,captureRole:true,captureName:true,captureId:true,captureDataTestId:true,capturePageviews:true,capturePageleave:true,capturePageDuration:true,captureVisibleDuration:false};var bool=v=>typeof v==="boolean";var number=(v,min,max)=>typeof v==="number"&&Number.isFinite(v)&&v>=min&&v<=max;var strings=v=>Array.isArray(v)&&v.length<=50&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=256);var integer=(v,min,max)=>number(v,min,max)&&Number.isInteger(v);var stringList=(v,maxItems,maxLength)=>Array.isArray(v)&&v.length<=maxItems&&v.every(x=>typeof x==="string"&&x.length>0&&x.length<=maxLength);var object=v=>v&&typeof v==="object"&&!Array.isArray(v)?v:{};function isValidHttpsOrigin(value){if(typeof value!=="string")return false;try{const url=new URL(value);return url.protocol==="https:"&&url.origin===value}catch(e){return false}}function parseReplayConfig(input){var _a,_b,_c;if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const appVersions=object(settings.appVersions);const errorSampling=object(settings.errorSampling);const recording=object(settings.recording);const pages=object(settings.pages);const privacy=object(settings.privacy);const capture=object(settings.capture);const upload=object(settings.upload);const legacyQuota=object(settings.quota);const maxSessionBytes=(_a=settings.maxSessionBytes)!=null?_a:legacyQuota.maxSessionBytes;const uploadOrigins=(_b=raw.uploadOrigins)!=null?_b:[];const checkpointMaxBytes=(_c=recording.checkpointMaxBytes)!=null?_c:4*1024*1024;if(!bool(raw.enabled)||!bool(raw.supported)||raw.recorderKind!=="rrweb"||raw.replayFormat!=="rrweb-v1"||typeof raw.samplingSalt!=="string"||!stringList(uploadOrigins,10,512)||!uploadOrigins.every(isValidHttpsOrigin)||!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!bool(settings.enabled)||!bool(settings.emergencyDisabled)||!number(settings.sampleRate,0,1)||!stringList(appVersions.include,100,100)||!stringList(appVersions.exclude,100,100)||!bool(errorSampling.enabled)||errorSampling.mode!=="after-error"&&errorSampling.mode!=="rolling-buffer"||!integer(errorSampling.rollingBufferSeconds,5,120)||!integer(recording.maxSessionMinutes,1,720)||!integer(recording.maxEvents,100,2e6)||!integer(recording.chunkSeconds,2,60)||!integer(recording.chunkMaxBytes,64*1024,2*1024*1024)||!integer(checkpointMaxBytes,256*1024,16*1024*1024)||!integer(recording.checkpointSeconds,10,120)||!integer(recording.localQueueMaxBytes,1024*1024,200*1024*1024)||!integer(recording.stopAfterBackgroundMinutes,1,120)||!stringList(pages.include,50,512)||!stringList(pages.exclude,100,512)||!bool(privacy.maskAllInputs)||!stringList(privacy.maskSelectors,100,256)||!stringList(privacy.blockSelectors,100,256)||!stringList(privacy.redactUrlParams,100,100)||!bool(capture.canvas)||!bool(capture.inlineImages)||!bool(capture.collectFonts)||!bool(capture.crossOriginIframes)||!integer(upload.concurrency,1,6)||!integer(upload.timeoutSeconds,5,120)||!integer(upload.maxRetries,0,12)||!integer(upload.retryBaseMs,100,1e4)||!integer(upload.localRetryDays,1,30)||!integer(maxSessionBytes,1024*1024,2*1024*1024*1024))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,recorderKind:"rrweb",replayFormat:"rrweb-v1",uploadOrigins,samplingSalt:raw.samplingSalt,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{enabled:settings.enabled,emergencyDisabled:settings.emergencyDisabled,sampleRate:settings.sampleRate,appVersions:{include:appVersions.include,exclude:appVersions.exclude},errorSampling:{enabled:errorSampling.enabled,mode:errorSampling.mode,rollingBufferSeconds:errorSampling.rollingBufferSeconds},recording:{maxSessionMinutes:recording.maxSessionMinutes,maxEvents:recording.maxEvents,chunkSeconds:recording.chunkSeconds,chunkMaxBytes:recording.chunkMaxBytes,checkpointMaxBytes,checkpointSeconds:recording.checkpointSeconds,localQueueMaxBytes:recording.localQueueMaxBytes,stopAfterBackgroundMinutes:recording.stopAfterBackgroundMinutes},pages:{include:pages.include,exclude:pages.exclude},privacy:{maskAllInputs:privacy.maskAllInputs,maskSelectors:privacy.maskSelectors,blockSelectors:privacy.blockSelectors,redactUrlParams:privacy.redactUrlParams},capture:{canvas:capture.canvas,inlineImages:capture.inlineImages,collectFonts:capture.collectFonts,crossOriginIframes:capture.crossOriginIframes},upload:{concurrency:upload.concurrency,timeoutSeconds:upload.timeoutSeconds,maxRetries:upload.maxRetries,retryBaseMs:upload.retryBaseMs,localRetryDays:upload.localRetryDays},maxSessionBytes}}}var DIAGNOSTIC_LEVELS=new Set(["debug","info","warn","error","fatal"]);function parseDiagnosticsConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const settings=object(raw.settings);const versions=object(raw.configVersionSet);const errors=object(settings.errors);const logs=object(settings.logs);const context=object(settings.context);const upload=object(settings.upload);const privacy=object(settings.privacy);const levels=logs.levels;if(!integer(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)||!bool(raw.enabled)||!bool(raw.supported)||typeof raw.endpointPath!=="string"||!raw.endpointPath.startsWith("/")||raw.endpointPath.length>512||!integer(versions.system,0,Number.MAX_SAFE_INTEGER)||!integer(versions.project,0,Number.MAX_SAFE_INTEGER)||!integer(versions.environment,0,Number.MAX_SAFE_INTEGER)||!number(errors.sampleRate,0,1)||!bool(errors.captureUnhandled)||!bool(errors.captureHandled)||!Array.isArray(levels)||levels.length>5||!levels.every(level=>typeof level==="string"&&DIAGNOSTIC_LEVELS.has(level))||new Set(levels).size!==levels.length||!number(logs.sampleRate,0,1)||!integer(context.windowSeconds,5,300)||!integer(context.maxEntries,10,200)||!integer(context.maxBytes,16*1024,1024*1024)||!integer(upload.batchSize,1,100)||!integer(upload.batchMaxBytes,16*1024,1024*1024)||!integer(upload.flushMs,500,6e4)||!integer(upload.timeoutMs,1e3,3e4)||!integer(upload.maxRetries,0,12)||!integer(upload.offlineMaxBytes,256*1024,50*1024*1024)||!integer(upload.offlineTtlHours,1,168)||!integer(privacy.maxMessageBytes,128,4096)||!integer(privacy.maxStackBytes,4096,256*1024)||!stringList(privacy.denyKeys,100,128)||!stringList(privacy.redactUrlParams,100,128))return null;return{schemaVersion:raw.schemaVersion,enabled:raw.enabled,supported:raw.supported,endpointPath:raw.endpointPath,configVersionSet:{system:versions.system,project:versions.project,environment:versions.environment},settings:{errors:{sampleRate:errors.sampleRate,captureUnhandled:errors.captureUnhandled,captureHandled:errors.captureHandled},logs:{levels:[...levels],sampleRate:logs.sampleRate},context:{windowSeconds:context.windowSeconds,maxEntries:context.maxEntries,maxBytes:context.maxBytes},upload:{batchSize:upload.batchSize,batchMaxBytes:upload.batchMaxBytes,flushMs:upload.flushMs,timeoutMs:upload.timeoutMs,maxRetries:upload.maxRetries,offlineMaxBytes:upload.offlineMaxBytes,offlineTtlHours:upload.offlineTtlHours},privacy:{maxMessageBytes:privacy.maxMessageBytes,maxStackBytes:privacy.maxStackBytes,denyKeys:[...privacy.denyKeys],redactUrlParams:[...privacy.redactUrlParams]}}}}function parseRemoteConfig(input){if(!input||typeof input!=="object")return null;const raw=input;const c=raw.config;if(!c||typeof c!=="object")return null;const config=c;const candidate={captureClicks:config.captureClicks,captureText:config.captureText,maxTextLength:config.maxTextLength,sampleRate:config.sampleRate,allowSelectors:config.allowSelectors,denySelectors:config.denySelectors,captureHref:config.captureHref,captureTitle:config.captureTitle===void 0?true:config.captureTitle,captureAriaLabel:config.captureAriaLabel,captureRole:config.captureRole,captureName:config.captureName,captureId:config.captureId,captureDataTestId:config.captureDataTestId,capturePageviews:config.capturePageviews,capturePageleave:config.capturePageleave,capturePageDuration:config.capturePageDuration,captureVisibleDuration:config.captureVisibleDuration};const valid=bool(raw.enabled)&&number(raw.schemaVersion,1,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.schemaVersion)&&number(raw.configVersion,0,Number.MAX_SAFE_INTEGER)&&Number.isInteger(raw.configVersion)&&typeof raw.platform==="string"&&number(raw.refreshIntervalSeconds,5,3600)&&bool(candidate.captureClicks)&&bool(candidate.captureText)&&number(candidate.maxTextLength,0,512)&&Number.isInteger(candidate.maxTextLength)&&number(candidate.sampleRate,0,1)&&strings(candidate.allowSelectors)&&strings(candidate.denySelectors)&&bool(candidate.captureHref)&&bool(candidate.captureTitle)&&bool(candidate.captureAriaLabel)&&bool(candidate.captureRole)&&bool(candidate.captureName)&&bool(candidate.captureId)&&bool(candidate.captureDataTestId)&&bool(candidate.capturePageviews)&&bool(candidate.capturePageleave)&&bool(candidate.capturePageDuration)&&bool(candidate.captureVisibleDuration);if(!valid)return null;const replay=parseReplayConfig(raw.replay);const diagnostics=parseDiagnosticsConfig(raw.diagnostics);return __spreadValues(__spreadValues({schemaVersion:raw.schemaVersion,configVersion:raw.configVersion,enabled:raw.enabled,platform:raw.platform,refreshIntervalSeconds:raw.refreshIntervalSeconds,config:candidate},raw.replay===void 0?{}:{replay}),raw.diagnostics===void 0?{}:{diagnostics})}function deriveConfigEndpoint(trackEndpoint){try{const base=typeof location!=="undefined"?location.href:void 0;const url=new URL(trackEndpoint,base);url.pathname=url.pathname.replace(/\/api\/v1\/track\/?$/,"/api/v1/config");url.search="";url.hash="";return url.toString()}catch(e){return trackEndpoint.replace(/\/api\/v1\/track\/?$/,"/api/v1/config")}}var SENSITIVE_TEXT=/(\d[\d\s-]{9,}\d)|([\w.+-]+@[\w-]+\.[\w.]+)|(\d{15,19})/g;function sanitizeText(input,maxLength=64){return input.replace(/\s+/g," ").trim().replace(SENSITIVE_TEXT,"[redacted]").slice(0,maxLength)}function coerceDatasetValue(raw){if(raw===void 0)return void 0;if(raw==="true")return true;if(raw==="false")return false;if(raw==="")return raw;const n=Number(raw);return Number.isFinite(n)&&String(n)===raw?n:raw}var wxSender=(endpoint,body,headers)=>new Promise((resolve,reject)=>{wx.request({url:endpoint,method:"POST",header:headers,data:body,timeout:1e4,success:res=>{if(res.statusCode>=200&&res.statusCode<300)return resolve();const e=new Error(`HTTP ${res.statusCode}`);e.status=res.statusCode;e.retryable=res.statusCode>=500||res.statusCode===429;reject(e)},fail:err=>{const e=new Error(err.errMsg);e.retryable=true;reject(e)}})});function observedWxSender(observation){return(endpoint,body,headers,keepalive)=>__async(null,null,function*(){const finish=observation.start(body);try{yield wxSender(endpoint,body,headers,keepalive);finish==null?void 0:finish(true)}catch(error){finish==null?void 0:finish(false);throw error}})}function wxStorage(){return{get(key){try{const v=wx.getStorageSync(key);return typeof v==="string"&&v?v:null}catch(e){return null}},set(key,value){try{wx.setStorageSync(key,value)}catch(e){}},remove(key){try{wx.removeStorageSync(key)}catch(e){}}}}var QUEUE_PREFIX="yz_q_";function imul32(a,b){if(typeof Math.imul==="function")return Math.imul(a,b);const ah=a>>>16&65535;const al=a&65535;const bh=b>>>16&65535;const bl=b&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0}function stableRuntimeHash(value){let hash=2166136261;for(let index=0;index<value.length;index+=1){hash^=value.charCodeAt(index);hash=imul32(hash,16777619)}return(hash>>>0).toString(16)}function storageNamespace(endpoint,writeKey){return`yz_mp_${stableRuntimeHash(`${endpoint}|${writeKey}`)}_`}function scopedWxStorage(endpoint,writeKey){const storage=wxStorage();const namespace=storageNamespace(endpoint,writeKey);return{get:key=>storage.get(namespace+key),set:(key,value)=>storage.set(namespace+key,value),remove:key=>storage.remove(namespace+key)}}function createWxPersistence(limit,queuePrefix){let known=-1;const keys=()=>{try{return wx.getStorageInfoSync().keys.filter(k=>k.slice(0,queuePrefix.length)===queuePrefix)}catch(e){return[]}};const readAll=()=>{const out=[];for(const k of keys()){try{const r=wx.getStorageSync(k);if(r==null?void 0:r.eventId)out.push(r)}catch(e){}}return out.sort((a,b)=>a.savedAt-b.savedAt)};return{load(){return __async(this,null,function*(){const all=readAll();known=all.length;return all.map(r=>r.payload)})},add(records){for(const r of records){try{wx.setStorageSync(queuePrefix+r.eventId,r)}catch(e){}}known=known<0?keys().length:known+records.length;if(known<=limit)return;const all=readAll();for(const r of all.slice(0,all.length-limit)){try{wx.removeStorageSync(queuePrefix+r.eventId)}catch(e){}}known=Math.min(all.length,limit)},remove(eventIds){for(const id of eventIds){try{wx.removeStorageSync(queuePrefix+id)}catch(e){}}if(known>0)known=Math.max(0,known-eventIds.length)}}}function wxPersistence(limit=500){return createWxPersistence(limit,QUEUE_PREFIX)}function scopedWxPersistence(endpoint,writeKey,limit=500){return createWxPersistence(limit,`${storageNamespace(endpoint,writeKey)}q_`)}function miniProgramDeviceType(deviceType,model){const normalized=deviceType==null?void 0:deviceType.trim().toLowerCase();if(normalized==="phone")return"mobile";if(normalized==="pad"||normalized==="tablet")return"tablet";if(normalized==="pc")return"desktop";const normalizedModel=model==null?void 0:model.trim();if(!normalizedModel)return null;if(/\b(?:ipad|tablet)\b/i.test(normalizedModel))return"tablet";if(/(?:^|[\s_-])pad(?:$|[\s_-])/i.test(normalizedModel))return"tablet";return null}function wxEnvContext(){try{const i=wx.getSystemInfoSync();const ctx={$runtime:"miniprogram"};const deviceType=miniProgramDeviceType(i.deviceType,i.model);if(deviceType)ctx.$device_type=deviceType;if(i.system)ctx.$os=i.system;if(i.model)ctx.$device_model=i.model;if(i.brand)ctx.$device_brand=i.brand;if(i.SDKVersion)ctx.$mp_sdk_version=i.SDKVersion;if(i.version)ctx.$wechat_version=i.version;return ctx}catch(e){return{$runtime:"miniprogram"}}}var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;var EVENT_ID=/^[a-zA-Z0-9_-]{1,128}$/;function validateTestingOptions(options,writeKey,initialProperties){if(options===void 0)return;if(!options||options.enabled!==true||typeof options.onSenderEvent!=="function"||typeof options.validationRunId!=="string"||!UUID.test(options.validationRunId)||(initialProperties==null?void 0:initialProperties.$validation_run_id)!==options.validationRunId||!/^wk_dev_[A-Za-z0-9_-]{32}$/.test(writeKey)){throw new Error("SDK sender observation requires explicit development testing and a matching validation run")}}function createTestingObservation(options){const callback=options.onSenderEvent;const validationRunId=options.validationRunId;let healthy=true;let active=true;let pendingRequests=0;let sequence=0;function notify(phase,requestId,events){if(!active)return;try{const result=callback({phase,requestId,events:events.map(event=>__spreadValues({},event))});if(result&&(typeof result==="object"||typeof result==="function")&&typeof result.then==="function"){healthy=false;Promise.resolve(result).catch(()=>{})}}catch(e){healthy=false}}return{snapshot(observer){const available=active&&observer===callback;return{available,healthy:available&&healthy,validationRunId:available?validationRunId:null,pendingRequests:available?pendingRequests:0}},deactivate(){active=false},start(body){if(!active)return;const events=[];try{const payload=JSON.parse(body);const batch=payload==null?void 0:payload.events;if(!Array.isArray(batch)||batch.length>50){healthy=false;return}for(const value of batch){const event=value;const props=event==null?void 0:event.properties;if((props==null?void 0:props.$validation_run_id)!==validationRunId)continue;const marker=props.$validation_case_id;if(typeof event.eventId!=="string"||!EVENT_ID.test(event.eventId)||marker!==void 0&&marker!==null&&(typeof marker!=="string"||!UUID.test(marker))){healthy=false;continue}events.push({eventId:event.eventId,validationRunId,validationCaseId:typeof marker==="string"?marker:null,isAutocapture:event.eventName==="$autocapture"})}}catch(e){healthy=false;return}if(!events.length)return;const requestId=++sequence;pendingRequests+=1;notify("started",requestId,events);let finished=false;return succeeded=>{if(finished)return;finished=true;pendingRequests-=1;notify(succeeded?"succeeded":"failed",requestId,events)}}}}var SYSTEM_EVENTS=["$app_start","$app_foreground","$app_background","$pageview","$pageleave","$autocapture","$identify","$replay_diagnostic","$replay_focus","$experiment_exposure"];var isSystemEvent=name=>SYSTEM_EVENTS.includes(name);var SDK_NAME2="@yuanze_dev/tracker-miniprogram";var SDK_VERSION2="0.11.4";var instance=null;var testingObservation=null;function getTestingSenderState(observer){var _a;return(_a=testingObservation==null?void 0:testingObservation.snapshot(observer))!=null?_a:{available:false,healthy:false,validationRunId:null,pendingRequests:0}}var captureSettings=DEFAULT_CAPTURE_SETTINGS;var captureEnabled=true;var configEtag;var configTimer=null;var configStorage=null;var configOptions=true;var configEndpoint="";var configWriteKey="";var configGeneration=0;var configRequest=null;function configCacheKey(writeKey){return`yz_capture_config_${stableRuntimeHash(writeKey)}_mini_program`}function applyRemoteConfig(payload){const runtime=autoTrackRuntimeSlot();const lifecycleChanged=payload.enabled!==captureEnabled||payload.config.capturePageviews!==captureSettings.capturePageviews||payload.config.capturePageleave!==captureSettings.capturePageleave||payload.config.capturePageDuration!==captureSettings.capturePageDuration||payload.config.captureVisibleDuration!==captureSettings.captureVisibleDuration;if(runtime&&lifecycleChanged){advanceCaptureEpoch(runtime)}captureSettings=payload.config;captureEnabled=payload.enabled;instance==null?void 0:instance.setConfigVersion(payload.configVersion);if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&lifecycleChanged)resumeLifecycle(runtime)}function loadCachedRemoteConfig(){try{const raw=configStorage==null?void 0:configStorage.get(configCacheKey(configWriteKey));if(!raw)return;const cached=JSON.parse(raw);const payload=parseRemoteConfig(cached.payload);if(!payload||payload.platform!=="mini-program")return;configEtag=cached.etag;applyRemoteConfig(payload)}catch(e){}}function refreshRemoteConfig(){if(configOptions===false||!configEndpoint||!configWriteKey)return Promise.resolve();if(configRequest)return configRequest;if(configTimer){clearTimeout(configTimer);configTimer=null}const options=typeof configOptions==="object"?configOptions:{};const generation=configGeneration;const endpoint=configEndpoint;const writeKey=configWriteKey;const storage=configStorage;const etag=configEtag;const request=new Promise(resolve=>{var _a,_b;let settled=false;const complete=()=>{var _a2;if(settled)return;settled=true;if(generation===configGeneration&&configOptions!==false){configTimer=setTimeout(()=>{void refreshRemoteConfig()},(_a2=options.refreshMs)!=null?_a2:45e3)}resolve()};try{const url=`${(_a=options.endpoint)!=null?_a:endpoint}?platform=mini-program`;wx.request({url,method:"GET",header:__spreadValues({"x-write-key":writeKey},etag?{"If-None-Match":etag}:{}),timeout:(_b=options.timeoutMs)!=null?_b:3e3,success:res=>{var _a2,_b2,_c;if(generation!==configGeneration)return;try{if(res.statusCode===304)return;if(res.statusCode<200||res.statusCode>=300)return;let data=res.data;if(typeof data==="string"){try{data=JSON.parse(data)}catch(e){return}}const payload=parseRemoteConfig(data);if(!payload||payload.platform!=="mini-program")return;configEtag=(_c=(_a2=res.header)==null?void 0:_a2.ETag)!=null?_c:(_b2=res.header)==null?void 0:_b2.etag;storage==null?void 0:storage.set(configCacheKey(writeKey),JSON.stringify({etag:configEtag,savedAt:Date.now(),payload}));applyRemoteConfig(payload)}catch(e){}},fail:complete,complete})}catch(e){complete()}});const cleanup=()=>{if(configRequest===tracked)configRequest=null};const tracked=request.then(cleanup,cleanup);configRequest=tracked;return tracked}function dispose(){testingObservation==null?void 0:testingObservation.deactivate();testingObservation=null;configGeneration+=1;if(configTimer){clearTimeout(configTimer);configTimer=null}configRequest=null;configOptions=false;configEndpoint="";configWriteKey="";configEtag=void 0;configStorage=null;captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;const current=instance;instance=null;current==null?void 0:current.dispose();disableOwnedAutoTrackRuntime()}function init(options){var _b;validateTestingOptions(options.testing,options.writeKey,options.initialProperties);dispose();const _a=options,{envContext=true,persist=true,autoTrack=true,remoteConfig=true,testing}=_a,rest=__objRest(_a,["envContext","persist","autoTrack","remoteConfig","testing"]);testingObservation=testing?createTestingObservation(testing):null;configStorage=wxStorage();const identityStorage=scopedWxStorage(rest.endpoint,rest.writeKey);instance=new Tracker(__spreadProps(__spreadValues({},rest),{platform:"miniprogram",sdkName:SDK_NAME2,sdkVersion:SDK_VERSION2,sender:testingObservation?observedWxSender(testingObservation):wxSender,storage:identityStorage,persistence:persist?scopedWxPersistence(rest.endpoint,rest.writeKey,(_b=rest.maxQueueSize)!=null?_b:500):false}));if(envContext)instance.register(wxEnvContext());captureSettings=DEFAULT_CAPTURE_SETTINGS;captureEnabled=true;configEtag=void 0;configOptions=remoteConfig;configEndpoint=deriveConfigEndpoint(rest.endpoint);configWriteKey=rest.writeKey;if(remoteConfig!==false)loadCachedRemoteConfig();if(autoTrack)enableAutoTrack();else bindAutoTrackRuntime(false);if(remoteConfig!==false)void refreshRemoteConfig();return instance}function getTracker(){return instance}function ensure(){if(!instance)throw new Error("tracker 未初始化,请先在 app.js 里调用 init()");return instance}function track(name,properties={}){ensure().trackUnsafe(name,properties)}function register(props){ensure().register(props)}function identify(id,options){ensure().identify(id,options)}function reset(){ensure().reset()}function flush(){return ensure().flush()}function trackTap(e){var _a,_b;const ds=(_b=(_a=e==null?void 0:e.currentTarget)==null?void 0:_a.dataset)!=null?_b:{};const name=ds.track;if(typeof name!=="string"||!name)return;const props={};for(const k of Object.keys(ds)){if(k==="track"||TEXT_METADATA_KEYS.has(k))continue;const v=ds[k];props[k]=typeof v==="string"?coerceDatasetValue(v):v}instance==null?void 0:instance.trackUnsafe(name,props)}var TEXT_METADATA_KEYS=new Set(["yzCapture","yzOwner","yzText","yzAdapter"]);var AUTO_TRACK_RUNTIME_KEY="__yz_tracker_miniprogram_auto_track_runtime__";var MODULE_RUNTIME_OWNER={};var FALLBACK_RUNTIME_ROOT={};function runtimeRoot(){if(typeof globalThis!=="undefined"){return globalThis}if(typeof wx==="object"&&wx){return wx}return FALLBACK_RUNTIME_ROOT}function autoTrackRuntimeSlot(){var _a;return(_a=runtimeRoot()[AUTO_TRACK_RUNTIME_KEY])!=null?_a:null}function advanceCaptureEpoch(runtime){runtime.epoch=Number.isFinite(runtime.epoch)?runtime.epoch+1:1}function resumeLifecycle(runtime){try{runtime.resumeApp()}catch(e){}if(runtime.appVisible===false)return;for(const resume of runtime.visiblePages.values()){try{resume()}catch(e){}}}function disableOwnedAutoTrackRuntime(){const runtime=autoTrackRuntimeSlot();if((runtime==null?void 0:runtime.owner)===MODULE_RUNTIME_OWNER&&runtime.enabled){runtime.enabled=false;advanceCaptureEpoch(runtime)}}function bindAutoTrackRuntime(enabled){var _a,_b,_c,_d,_e;const root=runtimeRoot();const runtime=(_a=autoTrackRuntimeSlot())!=null?_a:{owner:null,enabled:false,epoch:0,interactionDepth:0,disposeOwner:null,captureState:()=>({enabled:false,epoch:0,settings:DEFAULT_CAPTURE_SETTINGS}),captureInteraction:()=>void 0,invokeInteraction:(self,args,method)=>method.apply(self,args),track:()=>void 0,flush:()=>void 0,refresh:()=>void 0,resumeApp:()=>void 0,appVisible:null,visiblePages:new Map};if(runtime.owner&&runtime.owner!==MODULE_RUNTIME_OWNER){try{(_b=runtime.disposeOwner)==null?void 0:_b.call(runtime)}catch(e){}}if(!Number.isFinite(runtime.epoch))runtime.epoch=0;if(!Number.isFinite(runtime.interactionDepth))runtime.interactionDepth=0;(_c=runtime.resumeApp)!=null?_c:runtime.resumeApp=()=>void 0;(_d=runtime.appVisible)!=null?_d:runtime.appVisible=null;(_e=runtime.visiblePages)!=null?_e:runtime.visiblePages=new Map;runtime.owner=MODULE_RUNTIME_OWNER;if(runtime.enabled!==enabled){runtime.enabled=enabled;advanceCaptureEpoch(runtime)}runtime.disposeOwner=dispose;runtime.captureState=()=>({enabled:runtime.enabled&&captureEnabled&&instance!==null,epoch:runtime.epoch,settings:captureSettings});runtime.captureInteraction=(self,event)=>{if(runtime.enabled&&runtime.interactionDepth===0)captureInteraction(self,event)};runtime.invokeInteraction=(self,args,method)=>{var _a2,_b2;if(runtime.interactionDepth>0)return method.apply(self,args);let unmarkedComponent=false;try{const context=self;const dataset=(_b2=(_a2=args[0])==null?void 0:_a2.currentTarget)==null?void 0:_b2.dataset;unmarkedComponent=!!(context==null?void 0:context.is)&&!context.route&&!context.__route__&&(dataset==null?void 0:dataset.yzCapture)!=="1"&&(dataset==null?void 0:dataset.yzCapture)!==1}catch(e){}if(unmarkedComponent)return method.apply(self,args);const epoch=runtime.epoch;const owner=runtime.owner;let properties;try{if(runtime.enabled){properties=snapshotInteraction(self,args[0])}}catch(e){}runtime.interactionDepth+=1;try{return method.apply(self,args)}finally{runtime.interactionDepth-=1;try{if(properties&&runtime.enabled&&runtime.epoch===epoch&&runtime.owner===owner&&captureEnabled&&captureSettings.captureClicks){if(!captureSettings.captureText)delete properties.$text;else if(typeof properties.$text==="string"){const text=sanitizeText(properties.$text,captureSettings.maxTextLength);if(text)properties.$text=text;else delete properties.$text}instance==null?void 0:instance.track("$autocapture",properties)}}catch(e){}}};runtime.track=(name,properties)=>{if(runtime.enabled)instance==null?void 0:instance.trackUnsafe(name,properties)};runtime.flush=(unloading=false)=>{if(runtime.enabled)void(instance==null?void 0:instance.flush(unloading).catch(()=>void 0))};runtime.refresh=()=>{if(runtime.enabled)void refreshRemoteConfig()};root[AUTO_TRACK_RUNTIME_KEY]=runtime;return runtime}var PAGE_LIFECYCLE_HOOKS=new Set(["onLoad","onShow","onReady","onHide","onUnload","onPullDownRefresh","onReachBottom","onShareAppMessage","onShareTimeline","onAddToFavorites","onPageScroll","onResize","onTabItemTap","onSaveExitState"]);var INTERACTION_WRAPPED="__yz_tracker_interaction_wrapped__";var LIFECYCLE_WRAPPED="__yz_tracker_lifecycle_wrapped__";function routeOf(self){var _a,_b;const direct=(_a=self==null?void 0:self.route)!=null?_a:self==null?void 0:self.__route__;if(direct)return direct;try{if(typeof getCurrentPages==="function"){const pages=getCurrentPages();const current=(_b=pages[pages.length-1])==null?void 0:_b.route;if(current)return current}}catch(e){}const componentPath=self==null?void 0:self.is;return componentPath?`miniprogram://component/${componentPath}`:"miniprogram://app"}var SENSITIVE_TARGET=/(?:^|[-_:])(captcha\d*|verify|verification|otp|password|passwd|credential)(?:$|[-_:])/i;var SENSITIVE_DATASET_KEYS=["sensitive","noTrack","yzSensitive","yzNoTrack","trackSensitive"];function isSensitiveInteraction(target){if(!target)return false;if(typeof target.id==="string"&&SENSITIVE_TARGET.test(target.id))return true;const dataset=target.dataset;return!!dataset&&SENSITIVE_DATASET_KEYS.some(key=>Object.prototype.hasOwnProperty.call(dataset,key))}function snapshotInteraction(self,event){var _a,_b,_c;if(!captureEnabled||!captureSettings.captureClicks||!event)return;const target=event.currentTarget;if(isSensitiveInteraction(target))return;const dataset=(_a=target==null?void 0:target.dataset)!=null?_a:{};const generated=dataset.yzCapture==="1"||dataset.yzCapture===1;const adaptedClick=generated&&dataset.yzAdapter==="tdesign-grid-item"&&event.type==="click";if(event.type!=="tap"&&event.type!=="longpress"&&event.type!=="longtap"&&!adaptedClick)return;const mark=event.mark;if(mark&&(Object.prototype.hasOwnProperty.call(mark,"yzSensitive")||typeof mark.yzNamed==="string"&&mark.yzNamed))return;if(generated&&typeof(mark==null?void 0:mark.yzOwner)==="string"&&mark.yzOwner!==dataset.yzOwner)return;if(typeof dataset.track==="string"&&dataset.track)return;const id=typeof(target==null?void 0:target.id)==="string"&&target.id?target.id:void 0;const route=routeOf(self);const componentPath=self==null?void 0:self.is;const pageRoute=(_b=self==null?void 0:self.route)!=null?_b:self==null?void 0:self.__route__;if(componentPath&&!pageRoute&&!generated)return;let text;if(captureSettings.captureText&&captureSettings.maxTextLength>0){const raw=(_c=dataset.yzText)!=null?_c:mark==null?void 0:mark.yzText;if(typeof raw==="string"&&raw.length<=4096&&!/^\d{4,8}$/.test(raw.trim())){text=sanitizeText(raw,captureSettings.maxTextLength)||void 0}}return __spreadValues(__spreadValues({$tag:"miniprogram",$selector:id?`#${id}`:`miniprogram:${route}`,$url:route,$role:event.type==="tap"||adaptedClick?"tap":"longpress"},id?{$element_id:id}:{}),text?{$text:text}:{})}function captureInteraction(self,event){const properties=snapshotInteraction(self,event);if(properties)instance==null?void 0:instance.track("$autocapture",properties)}function wrapInteractionMethods(methods,runtime,ignored=new Set){for(const name of Object.keys(methods)){const value=methods[name];if(ignored.has(name)||typeof value!=="function")continue;if(value[INTERACTION_WRAPPED])continue;const wrapped=function(...args){return runtime.invokeInteraction(this,args,value)};Object.defineProperty(wrapped,INTERACTION_WRAPPED,{value:true});methods[name]=wrapped}}function wrapPageInteractions(options,runtime){wrapInteractionMethods(options,runtime,PAGE_LIFECYCLE_HOOKS)}function wrap(hooks,name,extra){const original=hooks[name];if(typeof original==="function"&&original[LIFECYCLE_WRAPPED])return;const wrapped=function(...args){try{extra(this,args)}catch(e){}return typeof original==="function"?original.apply(this,args):void 0};Object.defineProperty(wrapped,LIFECYCLE_WRAPPED,{value:true});hooks[name]=wrapped}function installAutoTrackRuntime(enabled){const runtime=bindAutoTrackRuntime(enabled);if(typeof Page==="function"&&!Page.__yzAutoTrack){runtime.visiblePages.clear();const originalPage=Page;const patched=(options=>{const enteredAt=new WeakMap;const enter=self=>{var _a;const capture=runtime.captureState();if(runtime.appVisible===false||!capture.enabled||!capture.settings.capturePageviews)return;if(((_a=enteredAt.get(self))==null?void 0:_a.epoch)===capture.epoch)return;enteredAt.set(self,{at:Date.now(),epoch:capture.epoch});runtime.track("$pageview",{$url:routeOf(self)})};const leave=self=>{runtime.visiblePages.delete(self);const entry=enteredAt.get(self);enteredAt.delete(self);if(!entry)return;const capture=runtime.captureState();if(!capture.enabled||capture.epoch!==entry.epoch||!capture.settings.capturePageleave)return;runtime.track("$pageleave",__spreadValues({$url:routeOf(self)},capture.settings.capturePageDuration?{$duration_ms:Math.max(0,Date.now()-entry.at)}:{}));runtime.flush(runtime.appVisible===false)};try{wrap(options,"onShow",self=>{runtime.visiblePages.set(self,()=>enter(self));enter(self)});wrap(options,"onHide",self=>leave(self));wrap(options,"onUnload",self=>leave(self));wrapPageInteractions(options,runtime)}catch(e){}return originalPage(options)});for(const key of Object.keys(originalPage))patched[key]=originalPage[key];patched.__yzAutoTrack=true;try{Page=patched}catch(e){}}if(typeof Component==="function"&&!Component.__yzTextTrack){const originalComponent=Component;const patched=(options=>{try{if(options.methods&&typeof options.methods==="object"){wrapInteractionMethods(options.methods,runtime)}}catch(e){}return originalComponent(options)});for(const key of Object.keys(originalComponent))patched[key]=originalComponent[key];patched.__yzTextTrack=true;try{Component=patched}catch(e){}}if(typeof App==="function"&&!App.__yzAutoTrack){runtime.resumeApp=()=>void 0;runtime.appVisible=null;const originalApp=App;const patched=(options=>{let launched=false;let visible=false;let startRecorded=false;let launchProperties={};let foregroundAt=Date.now();let foregroundEpoch=null;const resume=()=>{const capture=runtime.captureState();if(!launched||!visible||!capture.enabled)return;if(foregroundEpoch!==capture.epoch){foregroundAt=Date.now();foregroundEpoch=capture.epoch}if(!startRecorded){startRecorded=true;runtime.track("$app_start",launchProperties);runtime.flush()}};runtime.resumeApp=resume;try{wrap(options,"onLaunch",(_self,args)=>{var _a;const launch=(_a=args[0])!=null?_a:{};launched=true;visible=true;runtime.appVisible=true;startRecorded=false;foregroundEpoch=null;launchProperties=__spreadValues(__spreadValues({},typeof launch.scene==="number"?{$scene:launch.scene}:{}),typeof launch.path==="string"&&launch.path?{$path:launch.path}:{});resume()});wrap(options,"onHide",()=>{const capture=runtime.captureState();if(visible&&capture.enabled&&foregroundEpoch===capture.epoch){runtime.track("$app_background",{$duration_ms:Math.max(0,Date.now()-foregroundAt),$state:"hidden"})}visible=false;runtime.appVisible=false;foregroundEpoch=null;runtime.flush(true)});wrap(options,"onShow",(_self,args)=>{var _a;const show=(_a=args[0])!=null?_a:{};const capture=runtime.captureState();const wasVisible=visible;visible=true;runtime.appVisible=true;if(!capture.enabled){foregroundEpoch=null;return}if(launched&&startRecorded&&!wasVisible){runtime.track("$app_foreground",__spreadProps(__spreadValues(__spreadValues({},typeof show.scene==="number"?{$scene:show.scene}:{}),typeof show.path==="string"&&show.path?{$path:show.path}:{}),{$previous_state:"hidden"}))}resume();runtime.refresh()})}catch(e){}return originalApp(options)});for(const key of Object.keys(originalApp))patched[key]=originalApp[key];patched.__yzAutoTrack=true;try{App=patched}catch(e){}}if(enabled)resumeLifecycle(runtime)}function installAutoTrack(){installAutoTrackRuntime(false)}function enableAutoTrack(){installAutoTrackRuntime(true)}var tracker={init,getTracker,getTestingSenderState,track,register,identify,reset,flush,dispose,trackTap,installAutoTrack,enableAutoTrack,refreshRemoteConfig};var index_default=tracker;
|
package/index.d.ts
CHANGED
|
@@ -84,7 +84,30 @@ export type EventProps<K extends EventName> = K extends keyof ProjectEvents
|
|
|
84
84
|
: never;
|
|
85
85
|
|
|
86
86
|
export declare const SDK_NAME: "@yuanze_dev/tracker-miniprogram";
|
|
87
|
-
export declare const SDK_VERSION: "0.
|
|
87
|
+
export declare const SDK_VERSION: "0.11.4";
|
|
88
|
+
|
|
89
|
+
export type TestingSenderEvent = {
|
|
90
|
+
phase: "started" | "succeeded" | "failed";
|
|
91
|
+
requestId: number;
|
|
92
|
+
events: Array<{
|
|
93
|
+
eventId: string;
|
|
94
|
+
validationRunId: string;
|
|
95
|
+
validationCaseId: string | null;
|
|
96
|
+
isAutocapture: boolean;
|
|
97
|
+
}>;
|
|
98
|
+
};
|
|
99
|
+
export type TestingSenderObserver = (event: TestingSenderEvent) => void;
|
|
100
|
+
export type TestingOptions = {
|
|
101
|
+
enabled: true;
|
|
102
|
+
validationRunId: string;
|
|
103
|
+
onSenderEvent: TestingSenderObserver;
|
|
104
|
+
};
|
|
105
|
+
export type TestingSenderState = {
|
|
106
|
+
available: boolean;
|
|
107
|
+
healthy: boolean;
|
|
108
|
+
validationRunId: string | null;
|
|
109
|
+
pendingRequests: number;
|
|
110
|
+
};
|
|
88
111
|
|
|
89
112
|
export type InitOptions = {
|
|
90
113
|
/** 如 https://track.example.com/api/v1/track。域名要先加进小程序后台的 request 合法域名 */
|
|
@@ -111,10 +134,14 @@ export type InitOptions = {
|
|
|
111
134
|
autoTrack?: boolean;
|
|
112
135
|
/** 默认开启;false 仅用于开发或紧急熔断 */
|
|
113
136
|
remoteConfig?: boolean | { endpoint?: string; refreshMs?: number; timeoutMs?: number };
|
|
137
|
+
/** Explicit development-only exercise observation; production write keys are rejected. */
|
|
138
|
+
testing?: TestingOptions;
|
|
114
139
|
};
|
|
115
140
|
|
|
116
141
|
export declare function init(options: InitOptions): TrackerInstance;
|
|
117
142
|
export declare function getTracker(): TrackerInstance | null;
|
|
143
|
+
/** Callback identity must match the current initialized observer. */
|
|
144
|
+
export declare function getTestingSenderState(observer: TestingSenderObserver): TestingSenderState;
|
|
118
145
|
export declare function track(name: string, properties?: Record<string, unknown>): void;
|
|
119
146
|
export declare function register(props: Record<string, unknown>): void;
|
|
120
147
|
export declare function identify(id: string, options?: IdentifyOptions): void;
|
|
@@ -177,6 +204,7 @@ export declare function wxEnvContext(): Record<string, string>;
|
|
|
177
204
|
export declare const tracker: {
|
|
178
205
|
init: typeof init;
|
|
179
206
|
getTracker: typeof getTracker;
|
|
207
|
+
getTestingSenderState: typeof getTestingSenderState;
|
|
180
208
|
track: typeof track;
|
|
181
209
|
register: typeof register;
|
|
182
210
|
identify: typeof identify;
|