Commit ed5e4b08 authored by 张九刚's avatar 张九刚

在 main.js 中集成 Sensorsdata 统计功能,配置传感器参数并全局挂载;在 Home.vue 中优化弹窗逻辑,增加对 qrInfoList 的安全访问处理,确保数据渲染的稳定性。

parent c2fe95b8
## 0.1.7 (2025-6-12)
* 修改许可协议。
## 0.1.6 (2025-5-27)
* 优化:微信小程序和支付宝小程序的原型链安全问题。
* 微信小程序更新到 v1.21.7
* 支付宝小程序更新到 v0.14.9
## 0.1.5 (2024-12-31)
* 新增:小红书小程序支持配置 identify_id。
* 在 v0.14.2 定制的小红书小程序版本
## 0.1.4 (2024-12-19)
* 新增:uniapp 支持百度小程序、抖音/头条小程序的 ID3。
* 百度小程序 SDK 、抖音/头条小程序的版本都是 v0.14.3
## 0.1.3 (2024-11-18)
* 新增:uniapp 支持 小红书 SDK。
* 小红书小程序 SDK 版本是 v0.14.3
## 0.1.2 (2023-2-1)
* 修改:去除了支持 Vue3 点击全埋点的支持说明。不建议使用这个方案,建议手动埋点。
## 0.1.1 (2023-12-27)
* 新增:获取 identities 和 resetAnonymousIdentity 接口。
* Web SDK 从 v1.24.13 更新到 v1.26.3
* 微信小程序 SDK 从 v1.18.4 更新到 v1.20.2
软件名称:神策分析 SDK
版本号:所有版本
许可协议版本:1.0
1. 商业许可协议(用于商业用途需购买许可)
任何商业用途必须获得商业许可。
商业许可协议条款:
- 商业用途:任何直接或间接产生收入的用途都需要购买商业许可。
- 付款条款:在使用本软件用于商业用途之前,您必须支付全额许可费用。具体的付款方式将在双方联系后提供。
- 商业支持:购买商业许可后,您将获得一年的技术支持和软件更新服务。
- 禁止再许可:商业用户不得再许可、转售或转让本软件。每份商业许可仅适用于单一实体或公司。
- 源代码访问:购买商业许可的用户将获得本软件的代码访问权限,并可根据业务需求进行内部修改。但不得公开发布或再分发修改后的版本。
- 使用范围限制:商业许可仅限于购买者的内部使用,不得与第三方共享或用于为第三方提供服务。任何超出许可范围的使用行为均需额外授权,并可能产生额外费用。
- 联系信息:如需购买商业许可,请联系 dv@sensorsdata.com。
- 知识产权声明:本软件的版权归神策网络科技(北京)有限公司所有。购买商业许可仅授予您使用权,所有权仍归属本公司。
- 终止条款: 如果您未支付相关费用或违反本协议的任何条款,商业许可将自动终止。您必须立即停止所有商业用途,并销毁或删除所有软件副本。
2. 附加授权规则条款
授权规则条款:
- 功能限制:未经本软件作者的明确书面许可,您不得移除、绕过或规避本软件中的任何功能限制或试用限制。
- 商标使用:未经授权,您不得在宣传、市场推广或销售产品时使用本软件的名称、商标或品牌标识。任何商标使用必须得到明确的书面许可。
- 修改条款:本协议的条款可能会不时更新,用户有责任定期检查最新版本。任何重大更改将通过项目主页或电子邮件通知用户。
3. 联系方式
如需更多信息或申请商业许可,请联系 dv@sensorsdata.com。
\ No newline at end of file
[![神策数据](https://opensource.sensorsdata.cn/wp-content/uploads/logo.png "神策数据")](https://www.sensorsdata.cn/)
<br><br>
[![License](https://img.shields.io/github/license/sensorsdata/sa-sdk-android.svg)](https://github.com/sensorsdata/sa-sdk-android/blob/master/LICENSE)
## 神策简介
[**神策数据**](https://www.sensorsdata.cn/)
(Sensors Data),隶属于神策网络科技(北京)有限公司,是一家专业的大数据分析服务公司,大数据分析行业开拓者,为客户提供深度用户行为分析平台、以及专业的咨询服务和行业解决方案,致力于帮助客户实现数据驱动。神策数据立足大数据及用户行为分析的技术与实践前沿,业务现已覆盖以互联网、金融、零售快消、高科技、制造等为代表的十多个主要行业、并可支持企业多个职能部门。公司总部在北京,并在上海、深圳、合肥、武汉等地拥有本地化的服务团队,覆盖东区及南区市场;公司拥有专业的服务团队,为客户提供一对一的客户服务。公司在大数据领域积累的核心关键技术,包括在海量数据采集、存储、清洗、分析挖掘、可视化、智能应用、安全与隐私保护等领域。 [**More**](https://www.sensorsdata.cn/about/aboutus.html)
## SDK 简介
一款支持 uni-app 项目进行埋点数据采集的 JS 插件,插件下载地址及使用教程见:[神策分析 JS 插件](https://ext.dcloud.net.cn/plugin?id=4177)
## 版本更新记录
请参见 [release 发版记录](https://github.com/sensorsdata/uni-app-sdk/releases)
## License
[License 协议](LICENSE)
\ No newline at end of file
/**
* uni-app sdk 公共方法
* 需要做类型检查,每个方法必须返回 true false,用来作为参数检查的结果
*/
let sa = {
// 提供扩展性
instance: null,
// 提供初始化和配置参数
init: () => {
console.log('common-api,当前平台不支持此方法 init');
},
setPara: () => {
/*
server_url:'setServerUrl' 字符串
show_log:'enableLog' 布尔
app_flush_network_policy:'setFlushNetworkPolicy'数字
app_flush_interval:'setFlushInterval'数字
app_flush_bulkSize:'setFlushBulkSize'数字
app_session_interval_time:'setSessionIntervalTime'数字
app_data_collect:'enableDataCollect'布尔
mp_auto_track: object
*/
console.log('common-api,当前平台不支持此方法 setPara');
},
// app专用的方法
getAppFlushInterval: () => {
console.log('common-api,当前平台不支持此方法 getAppFlushInterval');
},
getAppFlushBulkSize: () => {
console.log('common-api,当前平台不支持此方法 getAppFlushBulkSize');
},
getAppSessionIntervalTime: () => {
console.log('common-api,当前平台不支持此方法 getAppSessionIntervalTime');
},
trackAppInstall: () => {
console.log('common-api,当前平台不支持此方法 trackAppInstall');
},
appFlush: () => {
console.log('common-api,当前平台不支持此方法 appFlush');
},
removeTimer: () => {
console.log('common-api,当前平台不支持此方法 removeTimer');
},
trackTimerStart: () => {
console.log('common-api,当前平台不支持此方法 trackTimerStart');
},
trackTimerPause: () => {
console.log('common-api,当前平台不支持此方法 trackTimerPause');
},
trackTimerResume: () => {
console.log('common-api,当前平台不支持此方法 trackTimerResume');
},
trackTimerEnd: () => {
console.log('common-api,当前平台不支持此方法 trackTimerEnd');
},
clearTrackTimer: () => {
console.log('common-api,当前平台不支持此方法 clearTrackTimer');
},
trackViewScreen: () => {
console.log('common-api,当前平台不支持此方法 trackViewScreen');
},
getSuperProperties: () => {
console.log('common-api,当前平台不支持此方法 getSuperProperties');
},
enableTrackScreenOrientation: () => {
console.log('common-api,当前平台不支持此方法 enableTrackScreenOrientation');
},
resumeTrackScreenOrientation: () => {
console.log('common-api,当前平台不支持此方法 resumeTrackScreenOrientation');
},
stopTrackScreenOrientation: () => {
console.log('common-api,当前平台不支持此方法 stopTrackScreenOrientation');
},
getScreenOrientation: () => {
console.log('common-api,当前平台不支持此方法 getScreenOrientation');
},
profileUnsetPushId: () => {
console.log('common-api,当前平台不支持此方法 profileUnsetPushId');
},
profilePushId: () => {
console.log('common-api,当前平台不支持此方法 profilePushId');
},
enableDeepLinkInstallSource: () => {
console.log('common-api,当前平台不支持此方法 enableDeepLinkInstallSource');
},
trackDeepLinkLaunch: () => {
console.log('common-api,当前平台不支持此方法 trackDeepLinkLaunch');
},
// 各端通用的常用API
getDistinctID: () => {
console.log('common-api,当前平台不支持此方法 getDistinctID');
},
getAnonymousID: () => {
console.log('common-api,当前平台不支持此方法 getAnonymousID');
},
register: (para) => {
console.log('common-api,当前平台不支持此方法 register');
},
unRegister: () => {
console.log('common-api,当前平台不支持此方法 unRegister');
},
clearRegister: () => {
console.log('common-api,当前平台不支持此方法 clearRegister');
},
//各端通用的标准API
identify: () => {
console.log('common-api,当前平台不支持此方法 identify');
},
login: () => {
console.log('common-api,当前平台不支持此方法 login');
},
logout: () => {
console.log('common-api,当前平台不支持此方法 logout');
},
track: () => {
console.log('common-api,当前平台不支持此方法 track');
},
setProfile: () => {
console.log('common-api,当前平台不支持此方法 setProfile');
},
setOnceProfile: () => {
console.log('common-api,当前平台不支持此方法 setOnceProfile');
},
incrementProfile: () => {
console.log('common-api,当前平台不支持此方法 incrementProfile');
},
appendProfile: () => {
console.log('common-api,当前平台不支持此方法 appendProfile');
},
unsetProfile: () => {
console.log('common-api,当前平台不支持此方法 unsetProfile');
},
deleteProfile: () => {
console.log('common-api,当前平台不支持此方法 deleteProfile');
},
popupLoadSuccess: (callback) => {
console.log('common-api,当前平台不支持此方法 popupLoadSuccess');
},
popupClose: (callback) => {
console.log('common-api,当前平台不支持此方法 popupClose');
},
popupClick: (callback) => {
console.log('common-api,当前平台不支持此方法 popupClick');
},
popupLoadFailed: (callback) => {
console.log('common-api,当前平台不支持此方法 popupLoadFailed');
},
enablePopup: () => {
console.log('common-api,当前平台不支持此方法 enablePopup');
},
popupInit: () => {
console.log('common-api,当前平台不支持此方法 popupInit');
},
// ID-Mapping 3.0
bind: () => {
console.log('common-api,当前平台不支持此方法 bind');
},
unbind: () => {
console.log('common-api,当前平台不支持此方法 unbind');
},
loginWithKey: () => {
console.log('common-api,当前平台不支持此方法 loginWithKey');
},
resetAnonymousIdentity: () => {
console.log('common-api,当前平台不支持此方法 resetAnonymousIdentity');
},
getIdentities: () => {
console.log('common-api,当前平台不支持此方法 getIdentities');
},
// id3 微信专用
bindOpenid: () => {
console.log('common-api,当前平台不支持此方法 bindOpenid');
},
unbindOpenid: () => {
console.log('common-api,当前平台不支持此方法 unbindOpenid');
},
bindUnionid: () => {
console.log('common-api,当前平台不支持此方法 bindUnionid');
},
unbindUnionid: () => {
console.log('common-api,当前平台不支持此方法 unbindUnionid');
}
};
export default sa;
/*
* @Date: 2022-10-28 10:30:10
* @File:
*/
/**
* SensorsData uni-app SDK
* APP原生SDK所有API -> JS可用的所有API -> 各端通用的有限的桥API
* APP SDK(所有) -> JS 写的 SDK(所有) -> uni-app Bridge SDK(有限)
* 神策招聘前端后端运维分析师产品售前等职位,内推发送简历到 shengyonggen@sensorsdata.cn
*/
import commonAPI from './common-api'
// #ifdef APP-PLUS
import bridgeAPI from './middle/app.js'
// #endif
// #ifdef H5
import bridgeAPI from './middle/web.js'
// #endif
// #ifdef MP-WEIXIN
import bridgeAPI from './middle/weixin.js';
// #endif
// #ifdef MP-ALIPAY
import bridgeAPI from './middle/alipay.js';
// #endif
// #ifdef MP-BAIDU
import bridgeAPI from './middle/baidu.js';
// #endif
// #ifdef MP-TOUTIAO
import bridgeAPI from './middle/toutiao.js';
// #endif
// #ifdef MP-XHS
import bridgeAPI from './middle/xiaohongshu.js';
// #endif
import get_enableVue3MpClick from './vue3-mpclick';
let sa = {};
let lib_plugin_track_timer = 0;
let js_uniapp_version = 'js_uniapp:0.1.7';
//检查是否是支持的平台,如果不支持就使用commonAPI
if (typeof bridgeAPI === 'undefined') {
console.error('神策 uni-app SDK 不支持当前平台,数据不会发送');
sa = commonAPI;
} else {
sa = bridgeAPI;
/*
做一次common-api的遍历
如果bridgeAPI都实现了,就结束
如果bridgeAPI没有实现,从instance中获取,如果还没有就=common-api
*/
Object.keys(commonAPI).forEach((key) => {
if (!(key in bridgeAPI)) {
if (typeof bridgeAPI.instance === 'object' && typeof bridgeAPI.instance[key] === 'function') {
sa[key] = bridgeAPI.instance[key].bind(bridgeAPI.instance);
} else {
sa[key] = commonAPI[key].bind(commonAPI);
}
}
// 如果是track,先加属性
if (key === 'track') {
let oldTrack = sa.track;
sa.track = function () {
let arr = [].slice.call(arguments, 0);
if (++lib_plugin_track_timer === 1) {
if (typeof arr[1] === 'object' && arr[1] !== null) {
arr[1]['$lib_plugin_version'] = [js_uniapp_version];
} else {
arr[1] = {
$lib_plugin_version: [js_uniapp_version]
};
}
}
return oldTrack.apply(sa, arr);
};
}
});
}
const enableVue3MpClick = get_enableVue3MpClick(sa);
export default sa;
export { enableVue3MpClick };
var sa={is_first_launch:!1,launched:!1,_queue:[],mpshow_time:null,sa_referrer:'\u76f4\u63a5\u6253\u5f00',query_share_depth:0,share_distinct_id:'',share_method:'',current_scene:'',inited:!1,para:{server_url:'',send_timeout:1e3,show_log:!1,allow_amend_share_path:!0,max_string_length:5e3,datasend_timeout:3e3,source_channel:[],batch_send:{send_timeout:6e3,max_length:6},preset_properties:{}},platform:'',lib:{version:'0.14.9',name:'MiniGame',method:'code'},properties:{$lib:'MiniGame',$lib_version:'0.14.9'},currentProps:{}};const _toString=Object.prototype.toString,_hasOwnProperty=Object.prototype.hasOwnProperty,indexOf=Array.prototype.indexOf,slice=Array.prototype.slice,_isArray=Array.prototype.isArray,forEach=Array.prototype.forEach,bind=Function.prototype.bind;function isUndefined(e){return void 0===e}function isString(e){return'[object String]'==_toString.call(e)}function isDate(e){return'[object Date]'==_toString.call(e)}function isBoolean(e){return'[object Boolean]'==_toString.call(e)}function isNumber(e){return'[object Number]'==_toString.call(e)&&/[\d\\.]+/.test(String(e))}function isJSONString(e){try{JSON.parse(e)}catch(e){return!1}return!0}function isObject(e){return null!=e&&'[object Object]'===_toString.call(e)}function isPlainObject(e){return'[object Object]'===_toString.call(e)}function isArray(e){return _isArray||'[object Array]'===_toString.call(e)}function isFuction(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}}function isArguments(e){return!(!e||!_hasOwnProperty.call(e,'callee'))}function toString(e){return null==e?'':isArray(e)||isPlainObject(e)&&e.toString===_toString?JSON.stringify(e,null,2):String(e)}function each(e,t,s){if(null==e)return!1;if(forEach&&e.forEach===forEach)e.forEach(t,s);else if(e.length===+e.length){for(var n=0,r=e.length;n<r;n++)if(n in e&&t.call(s,e[n],n,e)==={})return!1}else for(var a in e)if(_hasOwnProperty.call(e,a)&&t.call(s,e[a],a,e)==={})return!1}function toArray(e,t){if(!e)return[];var s=[];return e.toArray&&(s=e.toArray()),isArray(e)&&(s=slice.call(e)),isArguments(e)&&(s=slice.call(e)),s=values(e),t&&isNumber(t)&&(s=s.slice(t)),s}function values(e){var t=[];return null==e?t:(each(e,function(e){t[t.length]=e}),t)}function include(e,t){var s=!1;return null==e?s:indexOf&&e.indexOf===indexOf?-1!=e.indexOf(t):(each(e,function(e){if(s||(s=e===t))return{}}),s)}function unique(e){for(var t,s=[],n={},r=0;r<e.length;r++)n[t=e[r]]||(n[t]=!0,s.push(t));return s}function formatDate(e){function t(e){return e<10?'0'+e:e}return e.getFullYear()+'-'+t(e.getMonth()+1)+'-'+t(e.getDate())+' '+t(e.getHours())+':'+t(e.getMinutes())+':'+t(e.getSeconds())+'.'+t(e.getMilliseconds())}function searchObjDate(e){(isObject(e)||isArray(e))&&each(e,function(t,s){isObject(t)||isArray(t)?searchObjDate(e[s]):isDate(t)&&(e[s]=formatDate(t))})}function trim(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,'')}function isFunction(e){if(!e)return!1;var t=Object.prototype.toString.call(e);return'[object Function]'==t||'[object AsyncFunction]'==t||'[object GeneratorFunction]'==t}function extend(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];if('[object Object]'===Object.prototype.toString.call(s))for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&void 0!==s[n]&&(e[n]=s[n])}return e}function extend2Lev(e){return each(slice.call(arguments,1),function(t){for(var s in t)void 0!==t[s]&&null!==t[s]&&(isObject(t[s])&&isObject(e[s])?extend(e[s],t[s]):e[s]=t[s])}),e}function isEmptyObject(e){if(isObject(e)){for(var t in e)if(_hasOwnProperty.call(e,t))return!1;return!0}return!1}function deepCopy(e){var t={};return function e(t,s){for(var n in s){var r=s[n];isArray(r)?(t[n]=[],e(t[n],r)):isObject(r)?(t[n]={},e(t[n],r)):t[n]=r}}(t,e),t}function formatString(e){return e.length>sa.para.max_string_length?(sa.log('\u5b57\u7b26\u4e32\u957f\u5ea6\u8d85\u8fc7\u9650\u5236\uff0c\u5df2\u7ecf\u505a\u622a\u53d6--'+e),e.slice(0,sa.para.max_string_length)):e}function searchObjString(e){isObject(e)&&each(e,function(t,s){isObject(t)?searchObjString(e[s]):isString(t)&&(e[s]=formatString(t))})}function encodeDates(e){return each(e,function(t,s){isDate(t)?e[s]=formatDate(t):isObject(t)&&(e[s]=encodeDates(t))}),e}function utf8Encode(e){var t,s,n,r,a='';for(t=s=0,n=(e=(e+'').replace(/\r\n/g,'\n').replace(/\r/g,'\n')).length,r=0;r<n;r++){var i=e.charCodeAt(r),o=null;i<128?s++:o=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),null!==o&&(s>t&&(a+=e.substring(t,s)),a+=o,t=s=r+1)}return s>t&&(a+=e.substring(t,e.length)),a}function base64Encode(e){var t,s,n,r,a,i='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',o=0,c=0,u='',l=[];if(!e)return e;e=utf8Encode(e);do{t=(a=e.charCodeAt(o++)<<16|e.charCodeAt(o++)<<8|e.charCodeAt(o++))>>18&63,s=a>>12&63,n=a>>6&63,r=63&a,l[c++]=i.charAt(t)+i.charAt(s)+i.charAt(n)+i.charAt(r)}while(o<e.length);switch(u=l.join(''),e.length%3){case 1:u=u.slice(0,-2)+'==';break;case 2:u=u.slice(0,-1)+'='}return u}function _decodeURIComponent(e){var t='';try{t=decodeURIComponent(e)}catch(s){t=e}return t}var SOURCE_CHANNEL_STANDARD='utm_source utm_medium utm_campaign utm_content utm_term',LATEST_SOURCE_CHANNEL=['$latest_utm_source','$latest_utm_medium','$latest_utm_campaign','$latest_utm_content','$latest_utm_term','$latest_sa_utm'],LATEST_SHARE_INFO=['$latest_share_distinct_id','$latest_share_url_path','$latest_share_depth','$latest_share_method'],IDENTITY_KEY={EMAIL:'$identity_email',MOBILE:'$identity_mobile',LOGIN:'$identity_login_id'},IDENTITIES={},RESERVE_CHANNEL=' utm_source utm_medium utm_campaign utm_content utm_term sa_utm ',meta={lib_version:'',launched:!1,lib_name:'',query_share_depth:0,page_show_time:Date.now(),mp_show_time:null,promise_list:[],current_scene:'',is_first_launch:!1,_queue:[],inited:!1,hasExeInit:!1,scene_prefix:'',share_distinct_id:'',sa_referrer:'\u76f4\u63a5\u6253\u5f00',source_channel_standard:SOURCE_CHANNEL_STANDARD,latest_source_channel:LATEST_SOURCE_CHANNEL,latest_share_info:LATEST_SHARE_INFO};function getAppId(){var e=sa.system_api.getAppInfoSync();return e&&e.appId?e.appId:''}function getObjFromQuery(e){var t=e.split('?'),s=[],n={};return t&&t[1]?(each(t[1].split('&'),function(e){(s=e.split('='))[0]&&s[1]&&(n[s[0]]=s[1])}),n):{}}function getMixedQuery(e){var t=detectOptionQuery(e),s=t.scene,n=t.q,r=t.query;for(var a in r)r[a]=_decodeURIComponent(r[a]);return s&&extend(r,getObjFromQuery(s=-1!==(s=_decodeURIComponent(s)).indexOf('?')?'?'+s.replace(/\?/g,''):'?'+s)),n&&extend(r,getObjFromQuery(_decodeURIComponent(n))),r}function detectOptionQuery(e){if(!e||!isObject(e.query))return{};var t,s,n,r,a={};return a.query=extend({},e.query),isString(a.query.scene)&&(t=a.query,s=['utm_source','utm_content','utm_medium','utm_campaign','utm_term','sa_utm'].concat(sa.para.source_channel),n=new RegExp('('+s.join('|')+')%3D','i'),1===(r=Object.keys(t)).length&&'scene'===r[0]&&n.test(t.scene))&&(a.scene=a.query.scene,delete a.query.scene),e.query.q&&e.query.scancode_time&&'101'===String(e.scene).slice(0,3)&&(a.q=String(a.query.q),delete a.query.q,delete a.query.scancode_time),a}function setUtm(e,t){var s={},n=getMixedQuery(e),r=getCustomUtmFromQuery(n,'$','_','$'),a=getCustomUtmFromQuery(n,'$latest_','_latest_','$latest_');return s.pre1=r,s.pre2=a,extend(t,r),s}function setLatestChannel(e){isEmptyObject(e)||(function(e,t){var s=!1;for(var n in t)e[t[n]]&&(s=!0);return s}(e,LATEST_SOURCE_CHANNEL)&&sa.clearAppRegister(LATEST_SOURCE_CHANNEL),sa.registerApp(e))}function getCustomUtmFromQuery(e,t,s,n){if(!isObject(e))return{};var r={};if(e.sa_utm)for(var a in e)'sa_utm'!==a?include(sa.para.source_channel,a)&&(r[s+a]=e[a]):r[n+a]=e[a];else for(var i in e)-1===(' '+SOURCE_CHANNEL_STANDARD+' ').indexOf(' '+i+' ')?include(sa.para.source_channel,i)&&(r[s+i]=e[i]):r[t+i]=e[i];return r}function existLatestUtm(){var e=!1;return each(LATEST_SOURCE_CHANNEL,function(t){sa.properties[t]&&(e=!0)}),e}function setQuery(e,t){if(e&&isObject(e)&&!isEmptyObject(e)){var s=[];return each(e,function(e,n){'q'===n&&isString(e)&&0===e.indexOf('http')||(!0===t?s.push(n+'='+e):!1===t?s.push(n+'='+encodeURIComponent(e)):s.push(n+'='+_decodeURIComponent(e)))}),s.join('&')}return''}function getCurrentPage(){var e={};try{var t=isFunction(sa.system_api.getCurrentPages)?sa.system_api.getCurrentPages():getCurrentPages();e=t[t.length-1]}catch(e){sa.log('getCurrentPage:'+e)}return e}function getCurrentPath(){var e='\u672a\u53d6\u5230';try{var t=getCurrentPage();e=t?t.route:e}catch(e){sa.log('getCurrentPath:'+e)}return e}function isPresetIdKeys(e,t){var s=['$identity_anonymous_id'];for(var n of(isArray(t)&&(s=s.concat(t)),s))if(n===e)return!0;return!1}var isSafeInteger=Number.isSafeInteger||function(e){return isInteger(e)&&Math.abs(e)<=Math.pow(2,53)-1},isInteger=Number.isInteger||function(e){return'number'==typeof e&&isFinite(e)&&Math.floor(e)===e},check={checkKeyword:function(e){return/^((?!^distinct_id$|^original_id$|^device_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i.test(e)},checkIdLength:function(e){return!(String(e).length>255)||(sa.log('id \u957f\u5ea6\u8d85\u8fc7 255 \u4e2a\u5b57\u7b26\uff01'),!1)}};function getOpenidNameByAppid(e){if(''==e||!isString(e))return sa.log('error: \u53c2\u6570\u5fc5\u987b\u662f\u6709\u6548\u503c'),!1;var t=getAppId(),s="$identity_"+e+"_openid";return t&&(s="$identity_"+e+'_'+t+"_openid"),s}function validId(e){return!isString(e)&&!isNumber(e)||''===e?(sa.log('\u8f93\u5165 ID \u7c7b\u578b\u9519\u8bef'),!1):isNumber(e)&&(e=String(e),!/^\d+$/.test(e))?(sa.log('\u8f93\u5165 ID \u7c7b\u578b\u9519\u8bef'),!1):!!check.checkIdLength(e)&&e}function isNewLoginId(e,t){return e!==sa.store._state.history_login_id.name||sa.store._state.history_login_id.value!==t}function isSameAndAnonymousID(e){var t=sa.store.getFirstId(),s=sa.store.getDistinctId();return t?e===t:e===s}function setUpperCase(e){return isString(e)?e.toLocaleUpperCase():e}function getIsFirstDay(){return!!('object'==typeof sa.store._state&&isNumber(sa.store._state.first_visit_day_time)&&sa.store._state.first_visit_day_time>(new Date).getTime())}function getPresetProperties(){if(sa.properties&&sa.properties.$lib){var e={};each(sa.properties,function(t,s){0===s.indexOf('$')&&(e[s]=t)});var t={$url_path:getCurrentPath(),$is_first_day:getIsFirstDay(),$is_first_time:meta.is_first_launch},s=extend(e,t,sa.currentProps,sa.properties,sa.store.getProps());return delete s.$lib,s}return{}}function joinUrl(e,t){return!!e&&('\u672a\u53d6\u5230'===e?'\u672a\u53d6\u5230':t?e+'?'+t:e)}function getPath(e){return e=isString(e)?e.replace(/^\//,''):'\u53d6\u503c\u5f02\u5e38'}function getAppProps(e){var t={};return e&&e.path&&(t.$url_path=getPath(e.path),t.$url_query=setQuery(e.query),t.$url=joinUrl(t.$url_path,t.$url_query)),t}function getPageProps(){var e=getCurrentPage(),t=getCurrentPath(),s=e.sensors_mp_url_query||'';return{$url_path:t,$url:joinUrl(t,s),$url_query:s}}function rot13defs(e){return rot13obfs(e=String(e),113)}function rot13obfs(e,t){t='number'==typeof t?t:13;for(var s=(e=String(e)).split(''),n=0,r=s.length;n<r;n++){s[n].charCodeAt(0)<126&&(s[n]=String.fromCharCode((s[n].charCodeAt(0)+t)%126))}return s.join('')}var decodeURIComponent$1=_decodeURIComponent;function formatSystem(e){var t=e.toLowerCase();return'ios'===t?'iOS':'android'===t?'Android':e}var getRandomBasic=function(){var e=(new Date).getTime();return function(t){return Math.ceil((e=(9301*e+49297)%233280)/233280*t)}}();function getRandom(){if('function'==typeof Uint32Array){var e='';if('undefined'!=typeof crypto?e=crypto:'undefined'!=typeof msCrypto&&(e=msCrypto),isObject(e)&&e.getRandomValues){var t=new Uint32Array(1);return e.getRandomValues(t)[0]/Math.pow(2,32)}}return getRandomBasic(1e19)/1e19}function getUUID(){return Date.now()+'-'+Math.floor(1e7*getRandom())+'-'+getRandom().toString(16).replace('.','')+'-'+String(31242*getRandom()).replace('.','').slice(0,8)}const _={getUUID:getUUID,formatSystem:formatSystem,indexOf:indexOf,slice:slice,forEach:forEach,bind:bind,_hasOwnProperty:_hasOwnProperty,_toString:_toString,isUndefined:isUndefined,isString:isString,isDate:isDate,isBoolean:isBoolean,isNumber:isNumber,isJSONString:isJSONString,isObject:isObject,isPlainObject:isPlainObject,isArray:isArray,isFuction:isFuction,isArguments:isArguments,toString:toString,unique:unique,include:include,values:values,toArray:toArray,each:each,formatDate:formatDate,searchObjDate:searchObjDate,utf8Encode:utf8Encode,decodeURIComponent:decodeURIComponent$1,encodeDates:encodeDates,base64Encode:base64Encode,trim:trim,isFunction:isFunction,extend:extend,extend2Lev:extend2Lev,isEmptyObject:isEmptyObject,searchObjString:searchObjString,formatString:formatString,setLatestChannel:setLatestChannel,getObjFromQuery:getObjFromQuery,getMixedQuery:getMixedQuery,detectOptionQuery:detectOptionQuery,setUtm:setUtm,getCustomUtmFromQuery:getCustomUtmFromQuery,existLatestUtm:existLatestUtm,setQuery:setQuery,getCurrentPage:getCurrentPage,getCurrentPath:getCurrentPath,rot13defs:rot13defs,rot13obfs:rot13obfs,isSafeInteger:isSafeInteger,isInteger:isInteger,isPresetIdKeys:isPresetIdKeys,deepCopy:deepCopy,check:check,getOpenidNameByAppid:getOpenidNameByAppid,validId:validId,isNewLoginId:isNewLoginId,isSameAndAnonymousID:isSameAndAnonymousID,setUpperCase:setUpperCase,getIsFirstDay:getIsFirstDay,getPageProps:getPageProps,getAppProps:getAppProps,getPath:getPath,joinUrl:joinUrl,getPresetProperties:getPresetProperties};function request(e){var t;e.timeout&&(t=e.timeout,delete e.timeout);var s=sa.platform_obj.request(e);setTimeout(function(){try{isObject(s)&&isFunction(s.abort)&&s.abort()}catch(e){sa.log(e)}},t)}function getStorage(e,t){try{sa.platform_obj.getStorage({key:e,success:s,fail:s})}catch(t){try{sa.platform_obj.getStorage({key:e,success:s,fail:s})}catch(e){sa.log('\u83b7\u53d6 storage \u5931\u8d25\uff01',e)}}function s(e){if(e&&e.data&&isJSONString(e.data))try{var s=JSON.parse(e.data);e.data=s}catch(e){sa.log('parse res.data \u5931\u8d25\uff01',e)}t(e)}}function setStorage(e,t){var s;try{s=JSON.stringify(t)}catch(e){sa.log('\u5e8f\u5217\u5316\u7f13\u5b58\u5bf9\u8c61\u5931\u8d25\uff01',e)}try{sa.platform_obj.setStorage({key:e,data:s})}catch(t){try{sa.platform_obj.setStorage({key:e,data:s})}catch(e){sa.log('\u8bbe\u7f6e storage \u5931\u8d25: ',e)}}}function getStorageSync(e){var t='';try{t=sa.platform_obj.getStorageSync(e)}catch(s){try{t=sa.platform_obj.getStorageSync(e)}catch(e){sa.log('\u83b7\u53d6 storage \u5931\u8d25\uff01')}}return isJSONString(t)&&(t=JSON.parse(t)),t}function setStorageSync(e,t){var s;try{s=JSON.stringify(t)}catch(e){sa.log('\u5e8f\u5217\u5316\u7f13\u5b58\u5bf9\u8c61\u5931\u8d25\uff01',e)}var n=function(){sa.platform_obj.setStorageSync(e,s)};try{n()}catch(e){sa.log('set Storage fail --',e);try{n()}catch(e){sa.log('set Storage fail again --',e)}}}function getNetworkType(){return sa.platform_obj.getNetworkType.apply(null,arguments)}function getSystemInfo(){return sa.platform_obj.getSystemInfo.apply(null,arguments)}function getAppId$1(){var e;if(sa.platform_obj.getAccountInfoSync&&(e=sa.platform_obj.getAccountInfoSync()),isObject(e)&&isObject(e.miniProgram))return e.miniProgram}var compose={request:request,getStorage:getStorage,setStorage:setStorage,getStorageSync:getStorageSync,setStorageSync:setStorageSync,getAppInfoSync:getAppId$1,getNetworkType:getNetworkType,getSystemInfo:getSystemInfo};function setStorageSync$1(e,t){return my.setStorageSync({key:e,data:t})}function getStorageSync$1(e){var t=my.getStorageSync({key:e});return null!==t.data?t.data:''}function getAppInfoSync(){if(my.getAppIdSync){var e=my.getAppIdSync();return{appId:e&&e.appId?e.appId:'',appEnv:'',appVersion:''}}return{}}var compose$1={getStorageSync:getStorageSync$1,setStorageSync:setStorageSync$1,getAppInfoSync:getAppInfoSync,onNetworkStatusChange:my.onNetworkStatusChange};function request$1(e){var t,s;if(!e||isEmptyObject(e))return!1;e.complete=function(){s&&clearTimeout(s)},t=my.canIUse('request')?my.request(e):my.httpRequest(e),s=setTimeout(function(){isObject(t)&&isFunction(t.abort)&&t.abort()},sa.para.datasend_timeout)}var compose$2={request:request$1};function getNetwork(){return new Promise(function(e){sa.system_api.getNetworkType({success(e){sa.properties.$network_type=setUpperCase(e.networkType)},fail(e){sa.log('\u83b7\u53d6\u7f51\u7edc\u72b6\u6001\u4fe1\u606f\u5931\u8d25\uff1a ',e)},complete(){e()}})})}function getSystemInfo$1(){return new Promise(e=>{sa.system_api.getSystemInfo({success(e){var t=sa.properties;if(isObject(e)){t.$manufacturer=e.brand,t.$model=e.model,t.$brand=setUpperCase(e.brand)||'',t.$screen_width=Number(e.screenWidth),t.$screen_height=Number(e.screenHeight),t.$os=formatSystem(e.platform),t.$os_version=e.system.indexOf(' ')>-1?e.system.split(' ')[1]:e.system,t.$mp_client_app_version=e.version||'';var s=e.SDKVersion||'';s&&(t.$mp_client_basic_library_version=s)}},fail(e){sa.log('\u83b7\u53d6\u7cfb\u7edf\u4fe1\u606f\u5931\u8d25: ',e)},complete(){e()}})})}var system={inited:!1,init:function(){var e=(new Date).getTimezoneOffset();isNumber(e)&&(sa.properties.$timezone_offset=e);var t=getAppId()||sa.para.app_id||sa.para.appid;t&&(sa.properties.$app_id=t);var s=getNetwork(),n=getSystemInfo$1();Promise.all([s,n]).then(function(){sa.system.inited=!0,sa.checkInit()})}},identity_id='$identity_ali_mp_id';function stripProperties(e){return isObject(e)?(each(e,function(t,s){if(isArray(t)){var n=[];each(t,function(e){if(isString(e))n.push(e);else if(isUndefined(e))n.push('null');else try{n.push(JSON.stringify(e))}catch(e){sa.log('\u60a8\u7684\u6570\u636e - '+s+':'+t+' - \u7684\u6570\u7ec4\u91cc\u7684\u503c\u6709\u9519\u8bef,\u5df2\u7ecf\u5c06\u5176\u5220\u9664')}}),e[s]=n}if(isObject(t))try{e[s]=JSON.stringify(t)}catch(n){delete e[s],sa.log('\u60a8\u7684\u6570\u636e - '+s+':'+t+' - \u7684\u6570\u636e\u503c\u6709\u9519\u8bef,\u5df2\u7ecf\u5c06\u5176\u5220\u9664')}else isString(t)||isNumber(t)||isDate(t)||isBoolean(t)||isArray(t)||(sa.log('\u60a8\u7684\u6570\u636e - ',t,'-\u683c\u5f0f\u4e0d\u6ee1\u8db3\u8981\u6c42\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u5176\u5220\u9664'),delete e[s])}),e):e}function parseSuperProperties(e){isObject(e)&&each(e,function(t,s){if(isFunction(t))try{e[s]=t(),isFunction(e[s])&&(sa.log('\u60a8\u7684\u5c5e\u6027 - '+s+' \u683c\u5f0f\u4e0d\u6ee1\u8db3\u8981\u6c42\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u5176\u5220\u9664'),delete e[s])}catch(t){delete e[s],sa.log('\u60a8\u7684\u5c5e\u6027 - '+s+' \u629b\u51fa\u4e86\u5f02\u5e38\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u5176\u5220\u9664')}})}function batchRequest(e){if(isArray(e.data)&&e.data.length>0){var t=Date.now(),s=sa.para.datasend_timeout;e.data.forEach(function(e){e._flush_time=t}),e.data=JSON.stringify(e.data);let n={url:sa.para.server_url,method:'POST',dataType:'text',data:'data_list='+encodeURIComponent(base64Encode(e.data)),timeout:s,success:function(){e.success(e.len)},fail:function(){e.fail()}};sa.system_api.request(n)}else e.success(e.len)}function onceSend(e){e._flush_time=Date.now();var t='',s=JSON.stringify(e);t=-1!==sa.para.server_url.indexOf('?')?sa.para.server_url+'&data='+encodeURIComponent(base64Encode(s)):sa.para.server_url+'?data='+encodeURIComponent(base64Encode(s));var n=sa.para.datasend_timeout;sa.system_api.request({url:t,dataType:'text',method:'GET',timeout:n})}IDENTITIES.identity_unionid='',IDENTITIES.identity_id=identity_id,IDENTITIES.openid_name='ali',IDENTITIES.bind_preset_id=[identity_id],IDENTITIES.unbind_without_check=[identity_id],IDENTITIES.login_preset_id=[identity_id];var kit={batchRequest:batchRequest,onceSend:onceSend};function batchSend(){if(sa.batch_state.sended){var e,t,s=sa.batch_state.mem;(t=(e=s.length>=100?s.slice(0,100):s).length)>0&&(sa.batch_state.sended=!1,kit.batchRequest({data:e,len:t,success:batchRemove,fail:sendFail}))}}function sendFail(){sa.batch_state.sended=!0,sa.batch_state.failTime++}function batchRemove(e){sa.batch_state.clear(e),sa.batch_state.sended=!0,sa.batch_state.changed=!0,batchWrite(),sa.batch_state.failTime=0}function batchWrite(){sa.batch_state.changed&&(sa.batch_state.is_first_batch_write&&(sa.batch_state.is_first_batch_write=!1,setTimeout(function(){batchSend()},1e3)),sa.batch_state.syncStorage&&(sa.system_api.setStorageSync('sensors_prepare_data',sa.batch_state.mem),sa.batch_state.changed=!1))}function batchInterval(){!function e(){setTimeout(function(){batchWrite(),e()},1e3)}(),function e(){setTimeout(function(){batchSend(),e()},sa.para.batch_send.send_timeout*Math.pow(2,sa.batch_state.failTime))}()}function reportEvent(e){var t='';e._flush_time=Date.now(),t=e.event?"sensors_"+e.event:"sensors_"+e.type,e.dataSource='sensors',sa.log('report_event, name: ',t,'-- key: ',e),__mp_private_api__.reportEvent(t,e)}sa.batch_state={mem:[],changed:!1,sended:!0,is_first_batch_write:!0,sync_storage:!1,failTime:0,getLength:function(){return this.mem.length},add:function(e){this.mem.push(e)},clear:function(e){this.mem.splice(0,e)}},sa.batchWrite=batchWrite,sa.prepareData=function(e){var t={distinct_id:sa.store.getDistinctId(),lib:{$lib:sa.lib.name,$lib_method:sa.lib.method,$lib_version:String(sa.lib.version)},properties:{}};if(isObject(sa.store._state.identities)&&(t.identities=extend({},sa.store.getIdentities())),'track_id_unbind'===e.type&&'$UnbindID'===e.event&&(t.identities=_.deepCopy(e.unbind_value),delete e.unbind_value),extend(t,sa.store.getUnionId(),e),isObject(e.properties)&&!isEmptyObject(e.properties)&&extend(t.properties,e.properties),'track_id_unbind'===e.type&&'$UnbindID'===e.event&&(t.login_id&&delete t.login_id,t.anonymous_id&&delete t.anonymous_id),e.type&&'profile'===e.type.slice(0,7)||(t._track_id=Number(String(getRandom()).slice(2,5)+String(getRandom()).slice(2,4)+String(Date.now()).slice(-4)),t.properties=extend({},sa.properties,sa.store.getProps(),sa.currentProps,t.properties),'track'===e.type&&(t.properties.$is_first_day=getIsFirstDay())),t.properties.$time&&isDate(t.properties.$time)?(t.time=1*t.properties.$time,delete t.properties.$time):t.time=1*new Date,sa.ee.data.emit('beforeBuildCheck',t),parseSuperProperties(t.properties),searchObjDate(t),stripProperties(t.properties),searchObjString(t),sa.ee.data.emit('finalAdjustData',t),!sa.para.server_url)return!1;sa.log(t),sa.send(t)},sa.send=function(e){if('sensorsdata2015_binance'===sa.storageName&&'native'===sa.para.data_report_type)return reportEvent(e),!1;sa.para.batch_send?(sa.batch_state.getLength()>=500&&(sa.log('\u6570\u636e\u91cf\u5b58\u50a8\u8fc7\u5927\uff0c\u6709\u5f02\u5e38'),sa.batch_state.mem.shift()),sa.batch_state.add(e),sa.batch_state.changed=!0,sa.batch_state.getLength()>=sa.para.batch_send.max_length&&batchSend()):kit.onceSend(e)},sa.log=function(){if(sa.para.show_log&&'object'==typeof console&&console.log)try{var e=Array.prototype.slice.call(arguments);return console.log.apply(console,e)}catch(e){console.log(arguments[0])}},sa.track=function(e,t,s){sa.prepareData({type:'track',event:e,properties:t},s)},sa.setProfile=function(e){sa.prepareData({type:'profile_set',properties:e})},sa.setOnceProfile=function(e,t){sa.prepareData({type:'profile_set_once',properties:e},t)},sa.login=function(e){var t=sa.store.getFirstId(),s=sa.store.getDistinctId();e!==s&&(t?sa.trackSignup(e,'$SignUp'):(sa.store.set('first_id',s),sa.trackSignup(e,'$SignUp')))},sa.logout=function(e){var t=sa.store.getFirstId();t?(sa.store.set('first_id',''),!0===e?sa.store.set('distinct_id',getUUID()):sa.store.set('distinct_id',t)):sa.log('\u6ca1\u6709first_id\uff0clogout\u5931\u8d25')},sa.identify=function(e){(e=_.validId(e))&&(sa.store.getFirstId()?sa.store.set('first_id',e):sa.store.set('distinct_id',e))},sa.trackSignup=function(e,t,s){var n,r,a,i,o;isObject(e)?(n=e.id,r=e.event_name,a=e.id_name):(n=e,r=t),sa.store.set('distinct_id',n),i=a&&a!==IDENTITY_KEY.LOGIN?a+'+'+n:n,o=sa.store.getFirstId()||sa.store.getDistinctId(),sa.prepareData({original_id:o,distinct_id:i,type:'track_signup',event:r,properties:s})},sa.registerApp=function(e){isObject(e)&&!isEmptyObject(e)&&(sa.currentProps=extend(sa.currentProps,e))},sa.clearAppRegister=function(e){isArray(e)&&each(sa.currentProps,function(t,s){include(e,s)&&delete sa.currentProps[s]})},sa.register=function(e){isObject(e)&&!isEmptyObject(e)&&sa.store.setProps(e)},sa.clearAllRegister=function(){sa.store.setProps({},!0)},sa.getPresetProperties=function(){return _.getPresetProperties()},sa.use=function(e){const t=toArray(arguments,1);return t.unshift(this),isObject(e)&&isFunction(e.init)&&e.init.apply(e,t),e},sa.usePlugin=sa.use,sa.getServerUrl=function(){return sa.para.server_url},sa.registerPropertyPlugin=function(e){isFunction(e.properties)?!e.isMatchedWithFilter||isFunction(e.isMatchedWithFilter)?sa.ee.data.on('finalAdjustData',function(t){try{isFunction(e.isMatchedWithFilter)?e.isMatchedWithFilter(t)&&e.properties(t):e.properties(t)}catch(e){sa.log('execute registerPropertyPlugin callback error:'+e)}}):sa.log('registerPropertyPlugin arguments error, isMatchedWithFilter must be function'):sa.log('registerPropertyPlugin arguments error, properties must be function')};var hasOwnProperty$1=Object.prototype.hasOwnProperty,store={inited:!0,storageInfo:null,store_queue:[],getStorage:function(){return this.storageInfo?this.storageInfo:(this.storageInfo=sa.system_api.getStorageSync(sa.storageName)||'',this.storageInfo)},_state:{},getUUID:function(){return getUUID()},toState:function(e){var t=null,s=this;function n(){t.distinct_id?s._state=t:s.set('distinct_id',getUUID())}isJSONString(e)?(t=JSON.parse(e),n()):isObject(e)?(t=e,n()):this.set('distinct_id',getUUID());var r=this._state._first_id||this._state.first_id,a=this._state._distinct_id||this._state.distinct_id,i=(this._state.history_login_id?this._state.history_login_id:{}).name;if(this._state.identities&&isString(this._state.identities)){var o=JSON.parse(rot13defs(this._state.identities));this._state.identities=o}function c(e){for(var t in store._state.identities)hasOwnProperty$1.call(store._state.identities,t)&&t!==IDENTITIES.identity_id&&t!==e&&delete store._state.identities[t]}this._state.identities&&isObject(this._state.identities)&&!isEmptyObject(this._state.identities)||(this._state.identities={},this._state.identities[IDENTITIES.identity_id]=getUUID()),r?i&&hasOwnProperty$1.call(this._state.identities,i)?this._state.identities[i]!==a&&(this._state.identities[i]=a,c(i),this._state.history_login_id.value=a):(this._state.identities[IDENTITY_KEY.LOGIN]=a,c(IDENTITY_KEY.LOGIN),this._state.history_login_id={name:IDENTITY_KEY.LOGIN,value:a}):this._state.history_login_id={name:'',value:''},this.save()},getFirstId:function(){return this._state._first_id||this._state.first_id},getDistinctId:function(){var e=this.getLoginDistinctId();return e||(this._state._distinct_id||this._state.distinct_id)},getUnionId:function(){var e={},t=this._state._first_id||this._state.first_id,s=this.getDistinctId();return t&&s?(e.login_id=s,e.anonymous_id=t):e.anonymous_id=s,e},getIdentities:function(){var e=JSON.parse(JSON.stringify(this._state.identities));return e.$identity_anonymous_id=this.getAnonymousId(),e},getAnonymousId:function(){return this.getUnionId().anonymous_id},getHistoryLoginId:function(){return isObject(this._state.history_login_id)?this._state.history_login_id:null},getLoginDistinctId:function(){var e=this.getHistoryLoginId();return isObject(e)&&e.value?e.name!==IDENTITY_KEY.LOGIN?e.name+'+'+e.value:e.value:null},getProps:function(){return this._state.props||{}},setProps:function(e,t){var s=this._state.props||{};t?this.set('props',e):(extend(s,e),this.set('props',s))},set:function(e,t){var s={};for(var n in'string'==typeof e?s[e]=t:'object'==typeof e&&(s=e),this._state=this._state||{},s)this._state[n]=s[n],'first_id'===n?delete this._state._first_id:'distinct_id'===n&&(delete this._state._distinct_id,sa.events.emit('changeDistinctId'));this.save()},identitiesSet:function(e){var t={};switch(e.type){case'login':t[IDENTITIES.identity_id]=this._state.identities[IDENTITIES.identity_id],t[e.id_name]=e.id;break;case'logout':t[IDENTITIES.identity_id]=this._state.identities[IDENTITIES.identity_id]}this.set('identities',t)},change:function(e,t){this._state['_'+e]=t},encryptStorage:function(){var e=this.getStorage(),t='data:enc;';isObject(e)?e=t+rot13obfs(JSON.stringify(e)):isString(e)&&-1===e.indexOf(t)&&(e=t+rot13obfs(e)),sa.system_api.setStorageSync(sa.storageName,e)},save:function(){var e=deepCopy(this._state),t=rot13obfs(JSON.stringify(e.identities));if(e.identities=t,delete e._first_id,delete e._distinct_id,sa.para.encrypt_storage){e='data:enc;'+rot13obfs(JSON.stringify(e))}sa.system_api.setStorageSync(sa.storageName,e)},init:function(){var e=this.getStorage(),t=getUUID();if(e)isString(e)&&-1!==e.indexOf("data:enc;")&&(e=e.substring("data:enc;".length),e=JSON.parse(rot13defs(e))),this.toState(e);else{meta.is_first_launch=!0;var s=new Date,n=s.getTime();s.setHours(23),s.setMinutes(59),s.setSeconds(60),this.set({distinct_id:t,first_visit_time:n,first_visit_day_time:s.getTime(),identities:{[IDENTITIES.identity_id]:t},history_login_id:{name:'',value:''}}),isObject(sa.para)&&isString(sa.para.identify_id)&&sa.identify(sa.para.identify_id),sa.setOnceProfile({$first_visit_time:s})}this.checkStoreInit&&this.checkStoreInit()}};function trackSignup(e,t,s){var n,r,a,i;_.isObject(e)?(n=e.id,r=e.event_name,a=e.id_name):(n=e,r=t),store.set('distinct_id',n),i=a&&a!==IDENTITY_KEY.LOGIN?a+'+'+n:n;var o=store.getFirstId()||store.getDistinctId();sa.prepareData({original_id:o,distinct_id:i,type:'track_signup',event:r,properties:s})}function bindWithoutCheck(e,t){store._state.identities[e]=t,store.save(),sa.prepareData({type:'track_id_bind',event:'$BindID'})}function bind$1(e,t){var s='';if(_.isNumber(t)){if(_.isInteger(t)&&!1===_.isSafeInteger(t))return sa.log('Value must be String'),!1;t=String(t)}if(!_.isString(e))return sa.log('Key must be String'),!1;var n=store.getHistoryLoginId(),r=n?n.name:'',a=[IDENTITY_KEY.LOGIN,r];return _.isArray(IDENTITIES.bind_preset_id)&&(a=[IDENTITY_KEY.LOGIN,r].concat(IDENTITIES.bind_preset_id)),!_.check.checkKeyword(e)||_.isPresetIdKeys(e,a)?(s='Key ['+e+'] is invalid',sa.log(s),!1):t&&''!==t?_.isString(t)?!!_.check.checkIdLength(t)&&void bindWithoutCheck(e,t):(sa.log('Value must be String'),!1):(sa.log('Value is empty or null'),!1)}function unbindWithoutCheck(e,t){hasOwnProperty.call(store._state.identities,e)&&t===store._state.identities[e]&&(IDENTITIES.unbind_without_check&&IDENTITIES.unbind_without_check.indexOf(e)<0&&delete store._state.identities[e],store.save());var s=store.getDistinctId(),n=store.getFirstId();s===e+'+'+t&&(store.set('first_id',''),store.set('distinct_id',n),store.set('history_login_id',{name:'',value:''}));var r={};r[e]=t,sa.prepareData({type:'track_id_unbind',event:'$UnbindID',unbind_value:r})}function unbind(e,t){var s='';if(_.isNumber(t)){if(_.isInteger(t)&&!1===_.isSafeInteger(t))return sa.log('Value must be String'),!1;t=String(t)}return _.isString(e)?!_.check.checkKeyword(e)||_.isPresetIdKeys(e,[IDENTITY_KEY.LOGIN])?(s='Key ['+e+'] is invalid',sa.log(s),!1):t&&''!==t?_.isString(t)?!!_.check.checkIdLength(t)&&void unbindWithoutCheck(e,t):(sa.log('Value must be String'),!1):(sa.log('Value is empty or null'),!1):(sa.log('Key must be String'),!1)}function loginWithKey(e,t){if(sa.log('loginWithKey is deprecated !!!'),!_.isString(e))return sa.log('Key must be String'),!1;var s='';if(!_.check.checkKeyword(e)&&e.length>100)s='Key ['+e+'] is invalid',sa.log(s);else if(!_.check.checkKeyword(e))return s='Key ['+e+'] is invalid',sa.log(s),!1;if(_.isPresetIdKeys(e,IDENTITIES.login_preset_id))return s='Key ['+e+'] is invalid',sa.log(s),!1;if(!(t=_.validId(t)))return!1;if(_.isSameAndAnonymousID(t))return!1;var n=store.getFirstId(),r=store.getDistinctId();_.isNewLoginId(e,t)&&(store._state.identities[e]=t,store.set('history_login_id',{name:e,value:t}),n||store.set('first_id',r),sa.trackSignup({id:t,event_name:'$SignUp',id_name:e}),store.identitiesSet({type:'login',id:t,id_name:e}))}function login(e){if(!(e=_.validId(e)))return!1;if(_.isSameAndAnonymousID(e))return!1;var t=store.getFirstId(),s=store.getDistinctId(),n=IDENTITY_KEY.LOGIN;_.isNewLoginId(n,e)&&(store._state.identities&&(store._state.identities[n]=e),store.set('history_login_id',{name:n,value:e}),t||store.set('first_id',s),sa.trackSignup({id:e,event_name:'$SignUp'}),store.identitiesSet({type:'login',id:e,id_name:n}))}function logout(){var e=store.getFirstId();store.identitiesSet({type:'logout'}),store.set('history_login_id',{name:'',value:''}),e?(store.set('first_id',''),store.set('distinct_id',e)):sa.log('\u6ca1\u6709first_id\uff0clogout\u5931\u8d25')}function getIdentities(){return _.isEmptyObject(store._state)?null:store.getIdentities()||null}function resetAnonymousIdentity(e){if(store.getFirstId())return sa.log('resetAnonymousIdentity must be used in a logout state \uff01'),!1;if('number'==typeof e&&(e=String(e)),void 0===e){var t=store.getUUID();store._state.identities[IDENTITIES.identity_id]=t,store.set('distinct_id',t)}else _.validId(e)&&(store._state.identities[IDENTITIES.identity_id]=e,store.set('distinct_id',e))}function getAnonymousID(){if(!_.isEmptyObject(sa.store._state))return sa.store._state._first_id||sa.store._state.first_id||sa.store._state._distinct_id||sa.store._state.distinct_id;sa.log('\u8bf7\u5148\u521d\u59cb\u5316SDK')}sa.store=store;var functions=Object.freeze({__proto__:null,trackSignup:trackSignup,bindWithoutCheck:bindWithoutCheck,bind:bind$1,unbindWithoutCheck:unbindWithoutCheck,unbind:unbind,loginWithKey:loginWithKey,login:login,logout:logout,getIdentities:getIdentities,resetAnonymousIdentity:resetAnonymousIdentity,getAnonymousID:getAnonymousID});for(var f in functions)sa[f]=functions[f];function isValidListener(e){return'function'==typeof e||!(!e||'object'!=typeof e)&&isValidListener(e.listener)}sa.quick=function(){var e=arguments[0],t=arguments[1],s=arguments[2],n=_.isObject(s)?s:{};'appLaunch'===e||'appShow'===e?t?sa[e](t,n):sa.log('App\u7684launch\u548cshow\uff0c\u5728sensors.quick\u7b2c\u4e8c\u4e2a\u53c2\u6570\u5fc5\u987b\u4f20\u5165App\u7684options\u53c2\u6570'):'appHide'===e&&(n=_.isObject(t)?t:{},sa[e](n))};class EventEmitterBase{constructor(){this._events={}}on(e,t){if(!e||!t)return!1;if(!isValidListener(t))throw new Error('listener must be a function');this._events[e]=this._events[e]||[];var s='object'==typeof t;return this._events[e].push(s?t:{listener:t,once:!1}),this}prepend(e,t){if(!e||!t)return!1;if(!isValidListener(t))throw new Error('listener must be a function');this._events[e]=this._events[e]||[];var s='object'==typeof t;return this._events[e].unshift(s?t:{listener:t,once:!1}),this}prependOnce(e,t){return this.prepend(e,{listener:t,once:!0})}once(e,t){return this.on(e,{listener:t,once:!0})}off(e,t){var s=this._events[e];if(!s)return!1;if('number'==typeof t)s.splice(t,1);else if('function'==typeof t)for(var n=0,r=s.length;n<r;n++)s[n]&&s[n].listener===t&&s.splice(n,1);return this}emit(e,t){var s=this._events[e];if(!s)return!1;for(var n=0;n<s.length;n++){var r=s[n];r&&(r.listener.call(this,t||{}),r.once&&this.off(e,n))}return this}removeAllListeners(e){e&&this._events[e]?this._events[e]=[]:this._events={}}listeners(e){return e&&'string'==typeof e?this._events[e]:this._events}}class EventEmitterEx extends EventEmitterBase{constructor(){super(),this.cacheEvents=[],this.maxLen=20}replay(e,t){this.on(e,t),this.cacheEvents.length>0&&this.cacheEvents.forEach(function(s){s.type===e&&t.call(null,s.data)})}emit(e,t){super.emit.apply(this,arguments),this.cacheEvents.push({type:e,data:t}),this.cacheEvents.length>this.maxLen&&this.cacheEvents.shift()}}var ee={};ee.sdk=new EventEmitterEx,ee.data=new EventEmitterEx;var eventEmitter=function(){this.sub=[]};eventEmitter.prototype={add:function(e){this.sub.push(e)},emit:function(e,t){this.sub.forEach(function(s){s.on(e,t)})}};var eventSub=function(e){sa.events.add(this),this._events=[],this.handle=e,this.ready=!1};eventSub.prototype={on:function(e,t){if(this.ready){if(isFunction(this.handle))try{this.handle(e,t)}catch(e){sa.log(e)}}else this._events.push({event:e,data:t})},isReady:function(){var e=this;e.ready=!0,e._events.forEach(function(t){if(isFunction(e.handle))try{e.handle(t.event,t.data)}catch(e){sa.log(e)}})}},sa.ee=ee,sa.meta=meta,sa.kit=kit,sa.modules={},sa.eventSub=eventSub,sa.events=new eventEmitter,sa.init=function(e){if(!0===meta.hasExeInit)return!1;e&&isObject(e)&&sa.setPara(e),meta.hasExeInit=!0,e&&isObject(e)&&sa.setPara(e),ee.sdk.emit('afterInitPara'),sa.store.init(),sa.system.init(),sa.para.batch_send&&(sa.system_api.getStorage('sensors_prepare_data',function(e){var t=[];e&&e.data&&isArray(e.data)&&(t=e.data,sa.batch_state.mem=t.concat(sa.batch_state.mem)),sa.batch_state.syncStorage=!0}),batchInterval())},sa.setPara=function(e){sa.para=extend2Lev(sa.para,e);var t=[];if(isArray(sa.para.source_channel))for(var s=sa.para.source_channel.length,n=0;n<s;n++)-1===RESERVE_CHANNEL.indexOf(' '+sa.para.source_channel[n]+' ')&&t.push(sa.para.source_channel[n]);sa.para.source_channel=t,'number'!=typeof sa.para.send_timeout&&(sa.para.send_timeout=1e3);var r={send_timeout:6e3,max_length:6};e&&e.datasend_timeout||sa.para.batch_send&&(sa.para.datasend_timeout=1e4),!0===sa.para.batch_send?sa.para.batch_send=extend({},r):isObject(sa.para.batch_send)&&(sa.para.batch_send=extend({},r,sa.para.batch_send)),sa.para.server_url?sa.para.preset_properties=isObject(sa.para.preset_properties)?sa.para.preset_properties:{}:sa.log('\u8bf7\u4f7f\u7528 setPara() \u65b9\u6cd5\u8bbe\u7f6e server_url \u6570\u636e\u63a5\u6536\u5730\u5740,\u8be6\u60c5\u53ef\u67e5\u770bhttps://www.sensorsdata.cn/manual/mp_sdk_new.html#112-%E5%BC%95%E5%85%A5%E5%B9%B6%E9%85%8D%E7%BD%AE%E5%8F%82%E6%95%B0')},sa.checkInit=function(){!0===sa.system.inited&&!0===sa.store.inited&&(sa.inited=!0,sa._queue.length>0&&(each(sa._queue,function(e){sa[e[0]].apply(sa,slice.call(e[1]))}),sa._queue=[]))},each(['setProfile','setOnceProfile','track','identify','bind','unbind','login','logout','registerApp','clearAppRegister'],function(e){var t=sa[e];sa[e]=function(){sa.inited?t.apply(sa,arguments):sa._queue.push([e,arguments])}});const forEach$1=Array.prototype.forEach,slice$1=Array.prototype.slice,_hasOwnProperty$1=Object.prototype.hasOwnProperty,_toString$1=Object.prototype.toString;function extend$1(e){return each$1(slice$1.call(arguments,1),function(t){for(var s in t)void 0!==t[s]&&(e[s]=t[s])}),e}function isObject$1(e){return null!==e&&'object'==typeof e}function isFunction$1(e){if(!e)return!1;var t=Object.prototype.toString.call(e);return'[object Function]'==t||'[object AsyncFunction]'==t||'[object GeneratorFunction]'==t}function isString$1(e){return'[object String]'==_toString$1.call(e)}function each$1(e,t,s){if(null==e)return!1;if(forEach$1&&e.forEach===forEach$1)e.forEach(t,s);else if(e.length===+e.length){for(var n=0,r=e.length;n<r;n++)if(n in e&&t.call(s,e[n],n,e)==={})return!1}else for(var a in e)if(_hasOwnProperty$1.call(e,a)&&t.call(s,e[a],a,e)==={})return!1}var global={},lifeCycleHook=['appOnLaunch','appOnShow','appOnHide','pageOnShow','pageOnLoad'],miniLifeCycleAPI={};function registerLifeCycleHook(e){Object.assign(miniLifeCycleAPI,e)}function getScene(e,t){if(!isObject$1(t))return!1;var s=t.meta.scene_prefix;return!(!s||!isString$1(s))&&('number'==typeof e||'string'==typeof e&&''!==e?e=s+String(e):'\u672a\u53d6\u5230\u503c')}function hookFunc(e,t,s){var n=e[t];e[t]=function(e){isFunction$1(s)&&s.call(this,e),n&&isFunction$1(n)&&n.call(this,e)}}function hookAppFunc(e){hookFunc(e,'onLaunch',miniLifeCycleAPI.appOnLaunch),hookFunc(e,'onShow',miniLifeCycleAPI.appOnShow),hookFunc(e,'onHide',miniLifeCycleAPI.appOnHide)}function proxyApp(e,t){function s(e){var s=App;App=function(n){try{e&&e(n),n[t.para.name]=t,s.apply(this,arguments)}catch(e){s.apply(this,arguments),global.sensors.log('App:'+e)}}}isObject$1(t)&&isFunction$1(t.platform_obj.onAppShow)&&isFunction$1(t.platform_obj.onAppHide)&&(!t.config||isObject$1(t.config)&&t.config.is_support_onshow)?(s(),t.platform_obj.onAppShow(function(e){if(!t.para.launched){var s=e||isFunction$1(t.platform_obj.getLaunchOptionsSync)&&t.platform_obj.getLaunchOptionsSync()||{};miniLifeCycleAPI.appOnLaunch(s),t.para.launched=!0}miniLifeCycleAPI.appOnShow(e)}),t.platform_obj.onAppHide(function(){miniLifeCycleAPI.appOnHide()})):s(e)}function appOnLaunch(e,t){if(isObject$1(e)){var s={};if(e&&e.path&&extend$1(s,global.sensors._.getAppProps(e)),e&&e.scene){var n=getScene(e.scene,global.sensors);n&&(s.$scene=n,global.sensors.meta.current_scene=n,global.sensors.registerApp({$latest_scene:n}))}else s.$scene='\u672a\u53d6\u5230\u503c';var r=global.sensors._.setUtm(e,s);global.sensors.meta.is_first_launch?(s.$is_first_time=!0,global.sensors._.isEmptyObject(r.pre1)||global.sensors.setOnceProfile(r.pre1)):s.$is_first_time=!1,global.sensors._.isEmptyObject(r.pre2)||global.sensors._.setLatestChannel(r.pre2),isObject$1(t)&&(s=extend$1(s,t)),global.sensors.para&&global.sensors.para.autoTrack&&global.sensors.para.autoTrack.appLaunch&&global.sensors.track('$MPLaunch',s)}else global.sensors.log('appOnLaunch:\u8bf7\u4f20\u5165\u6b63\u786e\u7684\u53c2\u6570')}function appOnShow(e,t){var s={};global.sensors.meta.mp_show_time=(new Date).getTime(),e&&e.path&&extend$1(s,global.sensors._.getAppProps(e));var n=global.sensors._.setUtm(e,s);if(global.sensors._.isEmptyObject(n.pre2)||global.sensors._.setLatestChannel(n.pre2),e&&e.scene){var r=getScene(e.scene,global.sensors);r&&(s.$scene=r,global.sensors.registerApp({$latest_scene:r}))}isObject$1(t)&&(s=extend$1(s,t)),global.sensors.para&&global.sensors.para.autoTrack&&global.sensors.para.autoTrack.appShow&&global.sensors.track('$MPShow',s)}function appOnHide(e){var t=(new Date).getTime(),s={};isObject$1(e)&&(s=extend$1(s,e)),extend$1(s,global.sensors._.getPageProps());var n=global.sensors.meta.mp_show_time;n&&t-n>0&&(t-n)/36e5<24&&(s.event_duration=(t-n)/1e3),global.sensors.para&&global.sensors.para.autoTrack&&global.sensors.para.autoTrack.appHide&&global.sensors.track('$MPHide',s)}lifeCycleHook.forEach(function(e){miniLifeCycleAPI[e]=function(){throw new Error(`\u9700\u8981\u5148\u5b9a\u4e49 '${e}' \u624d\u80fd\u4f7f\u7528`)}});var presetEvents={appLaunch:!0,appShow:!0,appHide:!0},AutoTrackApp={name:'AutoTrackApp'};function getMixedQuery$1(e){var t={};if(e&&global.sensors._.isObject(e.query)&&(t=global.sensors._.extend({},e.query),e.query.qrCode&&global.sensors._.extend(t,global.sensors._.getObjFromQuery(global.sensors._.decodeURIComponent(e.query.qrCode)))),e&&global.sensors._.isObject(e.referrerInfo)&&e.referrerInfo.extraData){var s={};global.sensors._.isObject(e.referrerInfo.extraData)&&!global.sensors._.isEmptyObject(e.referrerInfo.extraData)?s=e.referrerInfo.extraData:global.sensors._.isJSONString(e.referrerInfo.extraData)&&(s=JSON.parse(e.referrerInfo.extraData)),global.sensors._.extend(t,s)}return t}function setUtm$1(e,t){var s={},n=getMixedQuery$1(e),r=global.sensors._.getCustomUtmFromQuery(n,'$','_','$'),a=global.sensors._.getCustomUtmFromQuery(n,'$latest_','_latest_','$latest_');return s.pre1=r,s.pre2=a,global.sensors._.extend(t,r),s}function appOnLaunch$1(e,t){if(isObject$1(e)){var s={};if(e&&e.path&&extend$1(s,global.sensors._.getAppProps(e)),e&&e.scene){var n=getScene(e.scene,global.sensors);n&&(s.$scene=n,global.sensors.meta.current_scene=n,global.sensors.registerApp({$latest_scene:n}))}else s.$scene='\u672a\u53d6\u5230\u503c';var r=global.sensors.para&&global.sensors.para.autoTrack&&global.sensors.para.autoTrack.appLaunch,a=setUtm$1(e,s);global.sensors.meta.is_first_launch?(s.$is_first_time=!0,global.sensors._.isEmptyObject(a.pre1)||r&&global.sensors.setOnceProfile(a.pre1)):s.$is_first_time=!1,global.sensors._.isEmptyObject(a.pre2)||global.sensors._.setLatestChannel(a.pre2),s.$url_query=global.sensors._.setQuery(e.query),isObject$1(t)&&(s=extend$1(s,t)),r&&global.sensors.track('$MPLaunch',s)}else global.sensors.log('appOnLaunch:\u8bf7\u4f20\u5165\u6b63\u786e\u7684\u53c2\u6570')}function appOnShow$1(e,t){var s={};global.sensors.meta.mp_show_time=(new Date).getTime(),e&&e.path&&extend$1(s,global.sensors._.getAppProps(e));var n=setUtm$1(e,s);if(global.sensors._.isEmptyObject(n.pre2)||global.sensors._.setLatestChannel(n.pre2),e&&e.scene){var r=getScene(e.scene,global.sensors);r&&(s.$scene=r,global.sensors.registerApp({$latest_scene:r}))}isObject$1(t)&&(s=extend$1(s,t)),global.sensors.para&&global.sensors.para.autoTrack&&global.sensors.para.autoTrack.appShow&&global.sensors.track('$MPShow',s)}AutoTrackApp.init=function(e,t){if(!e)return console.log('\u8bf7\u6b63\u786e\u521d\u59cb\u5316 sensorsdata\uff0c\u624d\u80fd\u4f7f\u7528\u63d2\u4ef6'),!1;global.sensors=e,global.sensors.para.autoTrack=extend$1(presetEvents,t),AutoTrackApp.lifeCycleAPI(),AutoTrackApp.proxyFrameworkInterface()},AutoTrackApp.lifeCycleAPI=function(){var e={};e.appOnLaunch=appOnLaunch,e.appOnShow=appOnShow,e.appOnHide=appOnHide,registerLifeCycleHook(e)},AutoTrackApp.proxyFrameworkInterface=function(){proxyApp(hookAppFunc,global.sensors)},AutoTrackApp.lifeCycleAPI=function(){var e={};e.appOnLaunch=appOnLaunch$1,e.appOnShow=appOnShow$1,e.appOnHide=appOnHide,registerLifeCycleHook(e)};var global$1={};function getCurrentPath$1(e){var t='\u672a\u53d6\u5230',s=getCurrentPage$1(e);return s&&s.route&&(t=s.route),t}function getCurrentPage$1(e){var t,s={};if(e)try{s=(t=isFunction$1(e.platform_obj.getCurrentPages)?e.platform_obj.getCurrentPages():getCurrentPages())[t.length-1]}catch(t){e.log(t)}else console.log('getCurrentPage:\u8bf7\u4f20\u5165 sa \u5bf9\u8c61');return s}function isClick(e){return!!{tap:1,longtap:1,longpress:1}[e]}function createClickData(e){var t={},s={},n=e.currentTarget||{},r=n.dataset||{};return t.$element_id=n.id,t.$element_type=r.type,t.$element_content=r.content,t.$element_name=r.name,isObject$1(e.event_prop)&&(s=e.event_prop),t.$url_path=getCurrentPath$1(global$1.sensors),t.$url=global$1.sensors._.getPageProps().$url,t=extend$1(t,s)}var ClickTrack={track:function(e){var t=createClickData(e),s=e.currentTarget||{},n=e.target||{},r=e.type,a=global$1.sensors.para;if(isObject$1(a.framework)&&isObject$1(a.framework.taro)&&!a.framework.taro.createApp&&n.id&&s.id&&n.id!==s.id)return!1;if(isObject$1(t)&&r&&isClick(r)){if(a.preset_events&&a.preset_events.collect_element&&!1===a.preset_events.collect_element(arguments[0]))return!1;global$1.sensors.track('$MPClick',t)}}},MP_HOOKS={data:1,onLoad:1,onShow:1,onReady:1,onPullDownRefresh:1,onReachBottom:1,onShareAppMessage:1,onPageScroll:1,onResize:1,onTabItemTap:1,onHide:1,onUnload:1};function clickProxy(e,t){var s=e[t];e[t]=function(){var e=s.apply(this,arguments),t=arguments[0];return isObject$1(t)&&ClickTrack.track(t),e}}function monitorClick(e){var t=[],s=global$1.sensors.para.autoTrack;if(s&&s.mpClick){t=getMethods(e),tabProxy(e);for(var n=t.length,r=0;r<n;r++)clickProxy(e,t[r])}}function tabProxy(e){var t=e.onTabItemTap;e.onTabItemTap=function(e){t&&t.apply(this,arguments);var s={};e&&(s.$element_content=e.text||''),s.$element_type='tabBar',s.$url_path=e.pagePath?e.pagePath:global$1.sensors._.getCurrentPath(),global$1.sensors.track('$MPClick',s)}}function getMethods(e){var t=[];for(var s in e)'function'!=typeof e[s]||MP_HOOKS[s]||t.push(s);return t}function hookPageFunc(e){hookFunc(e,'onShow',miniLifeCycleAPI.pageOnShow),hookFunc(e,'onLoad',miniLifeCycleAPI.pageOnLoad),hookFunc(e,'onUnload',miniLifeCycleAPI.pageOnUnload),hookFunc(e,'onHide',miniLifeCycleAPI.pageOnHide)}function proxyPage(e,t){var s=Page;Page=function(n){try{n||(n={}),isFunction$1(e)&&e(n),isFunction$1(t)&&t(n),s.apply(this,arguments)}catch(e){s.apply(this,arguments),console.log('Page:'+e)}};var n=Component;Component=function(s){try{s||(s={}),s.methods||(s.methods={}),isFunction$1(e)&&e(s.methods),isFunction$1(t)&&t(s.methods),n.apply(this,arguments)}catch(e){n.apply(this,arguments),console.log('Component:'+e)}}}var pageLeave=function(){if(global$1.sensors.para.autoTrack&&global$1.sensors.para.autoTrack.pageLeave){var e={},t='';try{t=(e=getCurrentPage$1(global$1.sensors))?e.route:''}catch(e){global$1.sensors.log(e)}if(global$1.sensors.meta.page_show_time>=0&&''!==t){var s={},n=(Date.now()-global$1.sensors.meta.page_show_time)/1e3;(isNaN(n)||n<0)&&(n=0),extend$1(s,global$1.sensors._.getPageProps()),s.event_duration=n,global$1.sensors.track('$MPPageLeave',s),global$1.sensors.meta.page_show_time=-1}}};function pageOnLoad(e){var t=this;if(global$1.sensors._.isObject(e)){try{t=getCurrentPage$1(global$1.sensors)}catch(e){global$1.sensors.log('pageOnLoad:'+e)}t.sensors_mp_url_query=global$1.sensors._.setQuery(e),t.sensors_mp_encode_url_query=global$1.sensors._.setQuery(e,!0)}}function pageOnShow(){global$1.sensors.meta.page_show_time=Date.now();var e={},t='';try{var s=getCurrentPage$1(global$1.sensors);t=s?s.route:''}catch(e){global$1.sensors.log('pageOnShow:'+e)}extend$1(e,global$1.sensors._.getPageProps()),e.$referrer=global$1.sensors.meta.sa_referrer,global$1.sensors.para&&global$1.sensors.para.autoTrack&&global$1.sensors.para.autoTrack.pageShow&&global$1.sensors.track('$MPViewScreen',e),global$1.sensors.meta.sa_referrer=t}function pageOnUnload(){pageLeave()}function pageOnHide(){pageLeave()}var presetEvents$1={pageShow:!0,mpClick:!0,pageLeave:!1},AutoTrackPage={name:'AutoTrackPage',init:function(e,t){if(!e)return console.log('\u8bf7\u6b63\u786e\u521d\u59cb\u5316 sensorsdata\uff0c\u624d\u80fd\u4f7f\u7528\u63d2\u4ef6'),!1;global$1.sensors=e,global$1.sensors.para.autoTrack=extend$1(presetEvents$1,t),AutoTrackPage.lifeCycleAPI(),AutoTrackPage.proxyFrameworkInterface()},lifeCycleAPI:function(){var e={};e.pageOnShow=pageOnShow,e.pageOnLoad=pageOnLoad,e.pageOnUnload=pageOnUnload,e.pageOnHide=pageOnHide,registerLifeCycleHook(e)},proxyFrameworkInterface:function(){proxyPage(hookPageFunc,monitorClick)}},presetEvents$2={appLaunch:!0,appShow:!0,appHide:!0,pageShow:!0,mpClick:!0,pageLeave:!1},AutoTrack={name:'AutoTrack',init:function(e,t){if(!e)return console.log('\u8bf7\u6b63\u786e\u521d\u59cb\u5316 sensorsdata\uff0c\u624d\u80fd\u4f7f\u7528\u63d2\u4ef6'),!1;e.ee.sdk.on('afterInitPara',function(){var s=extend$1(presetEvents$2,e.para.autoTrack,t);e.use(AutoTrackApp,s),e.use(AutoTrackPage,s)})}};sa.platform_obj=my,sa._=_,sa.system=system,sa.system_api=Object.assign(compose,compose$1,compose$2),sa.lib.name='AlipayMini',sa.properties.$lib='AlipayMini',sa.storageName='sensorsdata2015_zfb',sa.meta.scene_prefix='ali-',sa.use(AutoTrack);export default sa;
\ No newline at end of file
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
var sa = {
is_first_launch: false,
launched: false, // 需接口中也做调整,
_queue: [],
mpshow_time: null,
sa_referrer: '直接打开',
query_share_depth: 0,
share_distinct_id: '',
share_method: '',
current_scene: '',
inited: false
};
sa.para = {
// 神策分析数据接收地址
server_url: '',
//默认使用队列发数据时候,两条数据发送间的最大间隔
send_timeout: 1000,
// 是否允许控制台打印查看埋点数据(建议开启查看)
show_log: false,
// 是否允许修改onShareMessage里return的path,用来增加(用户id,分享层级,当前的path),在app onshow中自动获取这些参数来查看具体分享来源,层级等
allow_amend_share_path: true,
max_string_length: 500,
datasend_timeout: 3000,
source_channel: [],
batch_send: {
send_timeout: 6000,
max_length: 6
},
preset_properties: {}
};
sa.platform = '';
sa.lib = {
version: '0.14.3',
name: 'MiniGame',
method: 'code'
};
sa.properties = {
$lib: 'MiniGame',
$lib_version: '0.14.3'
};
sa.currentProps = {};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
const _toString = Object.prototype.toString,
_hasOwnProperty = Object.prototype.hasOwnProperty,
indexOf = Array.prototype.indexOf,
slice = Array.prototype.slice,
_isArray = Array.prototype.isArray,
forEach = Array.prototype.forEach,
bind = Function.prototype.bind;
function isUndefined(obj) {
return obj === void 0;
}
function isString(obj) {
return _toString.call(obj) == '[object String]';
}
function isDate(obj) {
return _toString.call(obj) == '[object Date]';
}
function isBoolean(obj) {
return _toString.call(obj) == '[object Boolean]';
}
function isNumber(obj) {
return _toString.call(obj) == '[object Number]' && /[\d\\.]+/.test(String(obj));
}
function isJSONString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function isObject(obj) {
if (obj == null) {
return false;
} else {
return _toString.call(obj) === '[object Object]';
}
}
function isPlainObject(obj) {
return _toString.call(obj) === '[object Object]';
}
function isArray(obj) {
return _isArray || _toString.call(obj) === '[object Array]';
}
function isFuction(f) {
try {
return /^\s*\bfunction\b/.test(f);
} catch (x) {
return false;
}
}
function isArguments(obj) {
return !!(obj && _hasOwnProperty.call(obj, 'callee'));
}
function toString(val) {
return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val);
}
function each(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach && obj.forEach === forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
function toArray(iterable, start) {
if (!iterable) {
return [];
}
var ret = [];
if (iterable.toArray) {
ret = iterable.toArray();
}
if (isArray(iterable)) {
ret = slice.call(iterable);
}
if (isArguments(iterable)) {
ret = slice.call(iterable);
}
ret = values(iterable);
if (start && isNumber(start)) {
ret = ret.slice(start);
}
return ret;
}
function values(obj) {
var results = [];
if (obj == null) {
return results;
}
each(obj, function (value) {
results[results.length] = value;
});
return results;
}
// include 函数,如果对象包含属性,就返回空对象 {}
function include(obj, target) {
var found = false;
if (obj == null) {
return found;
}
if (indexOf && obj.indexOf === indexOf) {
return obj.indexOf(target) != -1;
}
each(obj, function (value) {
if (found || (found = value === target)) {
return {};
}
});
return found;
}
function unique(arr) {
var temp,
n = [],
o = {};
for (var i = 0; i < arr.length; i++) {
temp = arr[i];
if (!o[temp]) {
o[temp] = true;
n.push(temp);
}
}
return n;
}
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function formatDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds());
}
function searchObjDate(o) {
if (isObject(o) || isArray(o)) {
each(o, function (a, b) {
if (isObject(a) || isArray(a)) {
searchObjDate(o[b]);
} else {
if (isDate(a)) {
o[b] = formatDate(a);
}
}
});
}
}
function trim(str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
function isFunction(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
// 浅复制
function extend(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
// 深复制
function extend2Lev(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0 && source[prop] !== null) {
if (isObject(source[prop]) && isObject(obj[prop])) {
extend(obj[prop], source[prop]);
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
}
function isEmptyObject(obj) {
if (isObject(obj)) {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
return false;
}
/**
* 深复制对象
* @param {object} obj
* @returns
*/
function deepCopy(obj) {
var temp = {};
function deepClone(target, source) {
for (var k in source) {
var item = source[k];
if (isArray(item)) {
target[k] = [];
deepClone(target[k], item);
} else if (isObject(item)) {
target[k] = {};
deepClone(target[k], item);
} else {
target[k] = item;
}
}
}
deepClone(temp, obj);
return temp;
}
function formatString(str) {
if (str.length > sa.para.max_string_length) {
sa.log('字符串长度超过限制,已经做截取--' + str);
return str.slice(0, sa.para.max_string_length);
} else {
return str;
}
}
function searchObjString(o) {
if (isObject(o)) {
each(o, function (a, b) {
if (isObject(a)) {
searchObjString(o[b]);
} else {
if (isString(a)) {
o[b] = formatString(a);
}
}
});
}
}
function encodeDates(obj) {
each(obj, function (v, k) {
if (isDate(v)) {
obj[k] = formatDate(v);
} else if (isObject(v)) {
obj[k] = encodeDates(v);
}
});
return obj;
}
function utf8Encode(string) {
string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var utftext = '',
start,
end;
var stringl = 0,
n;
start = end = 0;
stringl = string.length;
for (n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
}
function base64Encode(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = utf8Encode(data);
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = (o1 << 16) | (o2 << 8) | o3;
h1 = (bits >> 18) & 0x3f;
h2 = (bits >> 12) & 0x3f;
h3 = (bits >> 6) & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}
return enc;
}
/*
* @Date: 2022-11-01 19:18:40
* @File:
*/
function _decodeURIComponent(val) {
var result = '';
try {
result = decodeURIComponent(val);
} catch (e) {
result = val;
}
return result;
}
/*
* @Date: 2022-06-09 11:36:17
* @File:
*/
var SOURCE_CHANNEL_STANDARD = 'utm_source utm_medium utm_campaign utm_content utm_term';
var LATEST_SOURCE_CHANNEL = ['$latest_utm_source', '$latest_utm_medium', '$latest_utm_campaign', '$latest_utm_content', '$latest_utm_term', '$latest_sa_utm'];
var LATEST_SHARE_INFO = ['$latest_share_distinct_id', '$latest_share_url_path', '$latest_share_depth', '$latest_share_method'];
var IDENTITY_KEY = {
EMAIL: '$identity_email',
MOBILE: '$identity_mobile',
LOGIN: '$identity_login_id'
};
var IDENTITIES = {}; //ID3 用户相关的配置
var RESERVE_CHANNEL = ' utm_source utm_medium utm_campaign utm_content utm_term sa_utm ';
var REQUEST = {};
/*
* @Date: 2022-08-12 14:18:53
* @File: 内部使用全局变量
*/
var meta = {
lib_version: '',
launched: false, // 需接口中也做调整,
lib_name: '',
query_share_depth: 0,
page_show_time: Date.now(), //页面停留时长
mp_show_time: null, //小程序停留时长
promise_list: [],
current_scene: '',
is_first_launch: false,
_queue: [],
inited: false,
hasExeInit: false,
scene_prefix: '', //场景值
share_distinct_id: '',
sa_referrer: '直接打开',
source_channel_standard: SOURCE_CHANNEL_STANDARD,
latest_source_channel: LATEST_SOURCE_CHANNEL,
latest_share_info: LATEST_SHARE_INFO
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getAppId() {
var info = sa.system_api.getAppInfoSync();
if (info && info.appId) {
return info.appId;
}
return '';
}
/*
* @Date: 2022-08-19 15:15:42
* @File: 业务相关模块
*/
function getObjFromQuery(str) {
var query = str.split('?');
var arr = [];
var obj = {};
if (query && query[1]) {
each(query[1].split('&'), function (value) {
arr = value.split('=');
if (arr[0] && arr[1]) {
obj[arr[0]] = arr[1];
}
});
} else {
return {};
}
return obj;
}
// 从query,q,scene三个参数中,解析得到一个整合的query对象
function getMixedQuery(para) {
var obj = detectOptionQuery(para);
var scene = obj.scene;
var q = obj.q;
// query
var query = obj.query;
for (var i in query) {
query[i] = _decodeURIComponent(query[i]);
}
// scene
if (scene) {
scene = _decodeURIComponent(scene);
if (scene.indexOf('?') !== -1) {
scene = '?' + scene.replace(/\?/g, '');
} else {
scene = '?' + scene;
}
extend(query, getObjFromQuery(scene));
}
// 普通二维码的q
if (q) {
extend(query, getObjFromQuery(_decodeURIComponent(q)));
}
return query;
}
// 筛选检测出para里的query,q,scene
function detectOptionQuery(para) {
if (!para || !isObject(para.query)) {
return {};
}
var result = {};
// path的query
result.query = extend({}, para.query);
function isBScene(obj) {
var source = ['utm_source', 'utm_content', 'utm_medium', 'utm_campaign', 'utm_term', 'sa_utm'];
var source_keyword = source.concat(sa.para.source_channel);
var reg = new RegExp('(' + source_keyword.join('|') + ')%3D', 'i');
var keys = Object.keys(obj);
if (keys.length === 1 && keys[0] === 'scene' && reg.test(obj.scene)) {
return true;
} else {
return false;
}
}
//如果query有scene,认为scene是b接口传过来的
if (isString(result.query.scene) && isBScene(result.query)) {
result.scene = result.query.scene;
delete result.query.scene;
}
//如果query有q
if (para.query.q && para.query.scancode_time && String(para.scene).slice(0, 3) === '101') {
result.q = String(result.query.q);
delete result.query.q;
delete result.query.scancode_time;
}
return result;
}
// 解析参数中的utm,并添加
function setUtm(para, prop) {
var utms = {};
var query = getMixedQuery(para);
var pre1 = getCustomUtmFromQuery(query, '$', '_', '$');
var pre2 = getCustomUtmFromQuery(query, '$latest_', '_latest_', '$latest_');
utms.pre1 = pre1;
utms.pre2 = pre2;
extend(prop, pre1);
return utms;
}
function setLatestChannel(channel) {
if (!isEmptyObject(channel)) {
if (includeChannel(channel, LATEST_SOURCE_CHANNEL)) {
sa.clearAppRegister(LATEST_SOURCE_CHANNEL);
}
sa.registerApp(channel);
}
function includeChannel(channel, arr) {
var found = false;
for (var i in arr) {
if (channel[arr[i]]) {
found = true;
}
}
return found;
}
}
// 从参数中解析来源参数
function getCustomUtmFromQuery(query, utm_prefix, source_channel_prefix, sautm_prefix) {
if (!isObject(query)) {
return {};
}
var result = {};
if (query['sa_utm']) {
for (var i in query) {
if (i === 'sa_utm') {
result[sautm_prefix + i] = query[i];
continue;
}
if (include(sa.para.source_channel, i)) {
result[source_channel_prefix + i] = query[i];
}
}
} else {
for (var k in query) {
if ((' ' + SOURCE_CHANNEL_STANDARD + ' ').indexOf(' ' + k + ' ') !== -1) {
result[utm_prefix + k] = query[k];
continue;
}
if (include(sa.para.source_channel, k)) {
result[source_channel_prefix + k] = query[k];
}
}
}
return result;
}
// 是否已经存在 latest utm
function existLatestUtm() {
var exit = false;
each(LATEST_SOURCE_CHANNEL, function (value) {
if (sa.properties[value]) {
exit = true;
}
});
return exit;
}
// query 解析
function setQuery(params, isEncode) {
var url_query = '';
if (params && isObject(params) && !isEmptyObject(params)) {
var arr = [];
each(params, function (value, item) {
// 防止传统二维码的para.q这种异常query。另外异常的para.scene 不好判断,直接去掉。建议不要使用这个容易异意的参数
if (!(item === 'q' && isString(value) && value.indexOf('http') === 0)) {
if (isEncode) {
arr.push(item + '=' + value);
} else {
arr.push(item + '=' + _decodeURIComponent(value));
}
}
});
return arr.join('&');
} else {
return url_query;
}
}
function getCurrentPage() {
var obj = {};
try {
var pages = isFunction(sa.system_api.getCurrentPages) ? sa.system_api.getCurrentPages() : getCurrentPages();
obj = pages[pages.length - 1];
} catch (e) {
sa.log('getCurrentPage:' + e);
}
return obj;
}
function getCurrentPath() {
var url = '未取到';
try {
var currentPage = getCurrentPage();
url = currentPage ? currentPage.route : url;
} catch (e) {
sa.log('getCurrentPath:' + e);
}
return url;
}
/**
* 判断是否为预置的 ID key,可以通过 ids 传入 id key 的列表,自定义预置的 key 值
* @param {string} name
* @param {array} ids
* @returns {boolean}
*/
function isPresetIdKeys(name, ids) {
// 预置 ID key 列表
var keyList = ['$identity_anonymous_id'];
if (isArray(ids)) {
keyList = keyList.concat(ids);
}
for (var item of keyList) {
if (item === name) {
return true;
}
}
return false;
}
/**
* 判断是否为安全整数类型
*/
var isSafeInteger =
Number.isSafeInteger ||
function (value) {
return isInteger(value) && Math.abs(value) <= Math.pow(2, 53) - 1;
};
/**
* 判断是否为整数类型
*/
var isInteger =
Number.isInteger ||
function (value) {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
};
var check = {
// 检查关键字
checkKeyword: function (para) {
var reg = /^((?!^distinct_id$|^original_id$|^device_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i;
return reg.test(para);
},
// 检查 id 字符串长度
checkIdLength: function (str) {
var temp = String(str);
if (temp.length > 255) {
sa.log('id 长度超过 255 个字符!');
return false;
}
return true;
}
};
/**
*
* @param {*} app 表示不同小程序平台
* @returns 返回 ID
*/
function getOpenidNameByAppid(app) {
if (app == '' || !isString(app)) {
sa.log('error: 参数必须是有效值');
return false;
}
var appid = getAppId();
var _identity = '$identity_';
var _openid = '_openid';
var name = _identity + app + _openid;
if (appid) {
name = _identity + app + '_' + appid + _openid;
}
return name;
}
function validId(id) {
if ((!isString(id) && !isNumber(id)) || id === '') {
sa.log('输入 ID 类型错误');
return false;
}
if (isNumber(id)) {
id = String(id);
if (!/^\d+$/.test(id)) {
sa.log('输入 ID 类型错误');
return false;
}
}
if (!check.checkIdLength(id)) {
return false;
}
return id;
}
/**
* 判断是否为新的 login id
* @param {*} name
* @param {*} id
* @returns
*/
function isNewLoginId(name, id) {
// 当当前 ID 的 name 与上一个登录 ID 的 name 相同,且当前 ID 值与上一个 ID 的值相同时,则认为是同一个 ID,否则是一个新的 ID
// return !(name === store._state.history_login_id.name && store._state.history_login_id.value === id);
// 判断当前 ID 的 name 是否和上一个 ID 的 name 值相同,若不相同,则继续判断 id 值
if (name === sa.store._state.history_login_id.name) {
if (sa.store._state.history_login_id.value === id) {
return false;
}
}
return true;
}
/**
* 判断是否和匿名 id 相同
* @param {*} id
*/
function isSameAndAnonymousID(id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (firstId) {
return id === firstId;
} else {
return id === distinctId;
}
}
/**
* 字符串转换成大写
* value 必须是字符串
*/
function setUpperCase(value) {
if (isString(value)) {
return value.toLocaleUpperCase();
}
return value;
}
// 获取是否首日访问属性
function getIsFirstDay() {
if (typeof sa.store._state === 'object' && isNumber(sa.store._state.first_visit_day_time) && sa.store._state.first_visit_day_time > new Date().getTime()) {
return true;
} else {
return false;
}
}
function getPresetProperties() {
if (sa.properties && sa.properties.$lib) {
var builtinProps = {};
each(sa.properties, function (value, item) {
if (item.indexOf('$') === 0) {
builtinProps[item] = value;
}
});
var propertyObj = {
$url_path: getCurrentPath(),
$is_first_day: getIsFirstDay(),
$is_first_time: meta.is_first_launch
};
var obj = extend(builtinProps, propertyObj, sa.properties, sa.store.getProps());
delete obj.$lib;
return obj;
} else {
return {};
}
}
/**
* 拼接 URL
* @param {URL path} path
* @param {URL query} query
* @returns
*/
function joinUrl(path, query) {
if (!path) {
return false;
}
if (path === '未取到') {
return '未取到';
}
if (!query) {
return path;
} else {
return path + '?' + query;
}
}
// 统一path的格式
function getPath(path) {
if (isString(path)) {
path = path.replace(/^\//, '');
} else {
path = '取值异常';
}
return path;
}
/**
* 获取页面
* @param {app 生命周期参数} para
* @returns
*/
function getAppProps(para) {
var prop = {};
if (para && para.path) {
prop.$url_path = getPath(para.path);
prop.$url_query = setQuery(para.query);
prop.$url = joinUrl(prop.$url_path, prop.$url_query);
}
return prop;
}
/**
*
* @returns
*/
function getPageProps() {
var pages = getCurrentPage();
var path = getCurrentPath();
var query = pages.sensors_mp_url_query || '';
var url = joinUrl(path, query);
return {
$url_path: path,
$url: url,
$url_query: query
};
}
/*
* @Date: 2022-07-05 12:07:14
* @File:
*/
/**
* De-obfuscate an obfuscated string with the method above.
*/
function rot13defs(str) {
var code_len = 13,
n = 126;
str = String(str);
return rot13obfs(str, n - code_len);
}
/**
* Obfuscate a plaintext string with a simple rotation algorithm similar to
* the rot13 cipher.
*/
function rot13obfs(str, code_len) {
str = String(str);
code_len = typeof code_len === 'number' ? code_len : 13;
var n = 126;
var chars = str.split('');
for (var i = 0, len = chars.length; i < len; i++) {
var c = chars[i].charCodeAt(0);
if (c < n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + code_len) % n);
}
}
return chars.join('');
}
var decodeURIComponent$1 = _decodeURIComponent;
function formatSystem(system) {
var _system = system.toLowerCase();
if (_system === 'ios') {
return 'iOS';
} else if (_system === 'android') {
return 'Android';
} else {
return system;
}
}
/**
* 返回 rand 方法
* @param {number} 10^19 必传参数
* @return {number}
*/
var getRandomBasic = (function () {
var today = new Date();
var seed = today.getTime();
function rnd() {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280.0;
}
return function rand(number) {
return Math.ceil(rnd() * number);
};
})();
/**
* 生成一个随机数
* @return {number}
*/
function getRandom() {
if (typeof Uint32Array === 'function') {
var cry = '';
if (typeof crypto !== 'undefined') {
cry = crypto;
} else if (typeof msCrypto !== 'undefined') {
cry = msCrypto;
}
if (isObject(cry) && cry.getRandomValues) {
var typedArray = new Uint32Array(1);
var randomNumber = cry.getRandomValues(typedArray)[0];
var integerLimit = Math.pow(2, 32);
return randomNumber / integerLimit;
}
}
return getRandomBasic(10000000000000000000) / 10000000000000000000;
}
function getUUID() {
return (
'' +
Date.now() +
'-' +
Math.floor(1e7 * getRandom()) +
'-' +
getRandom().toString(16).replace('.', '') +
'-' +
String(getRandom() * 31242)
.replace('.', '')
.slice(0, 8)
);
}
const _ = {
getUUID,
formatSystem,
indexOf,
slice,
forEach,
bind,
_hasOwnProperty,
_toString,
isUndefined,
isString,
isDate,
isBoolean,
isNumber,
isJSONString,
isObject,
isPlainObject,
isArray,
isFuction,
isArguments,
toString,
unique,
include,
values,
toArray,
each,
formatDate,
searchObjDate,
utf8Encode,
decodeURIComponent: decodeURIComponent$1,
encodeDates,
base64Encode,
trim,
isFunction,
extend,
extend2Lev,
isEmptyObject,
searchObjString,
formatString,
setLatestChannel,
getObjFromQuery,
getMixedQuery,
detectOptionQuery,
setUtm,
getCustomUtmFromQuery,
existLatestUtm,
setQuery,
getCurrentPage,
getCurrentPath,
rot13defs,
rot13obfs,
isSafeInteger,
isInteger,
isPresetIdKeys,
deepCopy,
check,
getOpenidNameByAppid,
validId,
isNewLoginId,
isSameAndAnonymousID,
setUpperCase,
getIsFirstDay,
getPageProps,
getAppProps,
getPath,
joinUrl,
getPresetProperties
};
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function stripProperties(p) {
if (!isObject(p)) {
return p;
}
each(p, function (v, k) {
// 如果是数组,把值自动转换成string
if (isArray(v)) {
var temp = [];
each(v, function (arrv) {
if (isString(arrv)) {
temp.push(arrv);
} else if (isUndefined(arrv)) {
temp.push('null');
} else {
try {
temp.push(JSON.stringify(arrv));
} catch (error) {
sa.log('您的数据 - ' + k + ':' + v + ' - 的数组里的值有错误,已经将其删除');
}
}
});
p[k] = temp;
}
//如果是多层结构对象,直接序列化为字符串
if (isObject(v)) {
try {
p[k] = JSON.stringify(v);
} catch (error) {
delete p[k];
sa.log('您的数据 - ' + k + ':' + v + ' - 的数据值有错误,已经将其删除');
}
} else if (!(isString(v) || isNumber(v) || isDate(v) || isBoolean(v) || isArray(v))) {
// 只能是字符串,数字,日期,布尔,数组
sa.log('您的数据 - ', v, '-格式不满足要求,我们已经将其删除');
delete p[k];
}
});
return p;
}
// 处理动态公共属性
function parseSuperProperties(obj) {
if (isObject(obj)) {
each(obj, function (value, item) {
if (isFunction(value)) {
try {
obj[item] = value();
if (isFunction(obj[item])) {
sa.log('您的属性 - ' + item + ' 格式不满足要求,我们已经将其删除');
delete obj[item];
}
} catch (e) {
delete obj[item];
sa.log('您的属性 - ' + item + ' 抛出了异常,我们已经将其删除');
}
}
});
}
}
/*
* @Date: 2022-10-13 18:04:01
* @File: 批量发送数据发送模块
*/
function batchRequest(option) {
if (isArray(option.data) && option.data.length > 0) {
var now = Date.now(),
timeout = sa.para.datasend_timeout;
option.data.forEach(function (v) {
v._flush_time = now;
});
option.data = JSON.stringify(option.data);
let params = {
url: sa.para.server_url,
method: 'POST',
dataType: 'text',
data: 'data_list=' + encodeURIComponent(base64Encode(option.data)),
timeout: timeout,
success: function () {
option.success(option.len);
},
fail: function () {
option.fail();
}
};
if (REQUEST.header) {
params.header = REQUEST.header;
}
sa.system_api.request(params);
} else {
option.success(option.len);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-10-12 17:36:49
* @File: 单条发送
*/
function onceSend(data) {
data._flush_time = Date.now();
var url = '';
var str_t = JSON.stringify(data);
if (sa.para.server_url.indexOf('?') !== -1) {
url = sa.para.server_url + '&data=' + encodeURIComponent(base64Encode(str_t));
} else {
url = sa.para.server_url + '?data=' + encodeURIComponent(base64Encode(str_t));
}
var timeout = sa.para.datasend_timeout;
sa.system_api.request({
url: url,
dataType: 'text',
method: 'GET',
timeout: timeout
});
}
/*
* @Date: 2022-11-01 21:18:52
* @File: 批量发送 & 单条发送 模块
*/
var kit = {
batchRequest: batchRequest,
onceSend: onceSend
};
/**
* 批量发送
*/
sa.batch_state = {
mem: [],
changed: false,
sended: true,
is_first_batch_write: true,
sync_storage: false, // 在初始化时将 storage 存的数据同步到当前暂存队列中的操作是否完成
failTime: 0, // 发送数据失败次数
getLength: function () {
return this.mem.length;
},
add: function (data) {
this.mem.push(data);
},
clear: function (len) {
this.mem.splice(0, len);
}
};
function batchSend() {
if (sa.batch_state.sended) {
var data,
len,
mData = sa.batch_state.mem;
if (mData.length >= 100) {
data = mData.slice(0, 100);
} else {
data = mData;
}
len = data.length;
if (len > 0) {
sa.batch_state.sended = false;
kit.batchRequest({
data: data,
len: len,
success: batchRemove,
fail: sendFail
});
}
}
}
function sendFail() {
sa.batch_state.sended = true;
sa.batch_state.failTime++;
}
function batchRemove(len) {
sa.batch_state.clear(len);
sa.batch_state.sended = true;
sa.batch_state.changed = true;
batchWrite();
sa.batch_state.failTime = 0;
}
function batchWrite() {
if (sa.batch_state.changed) {
// 如果是首次写入数据,等待1s后,优先发送,优化那些来了就跑的人
if (sa.batch_state.is_first_batch_write) {
sa.batch_state.is_first_batch_write = false;
setTimeout(function () {
batchSend();
}, 1000);
}
if (sa.batch_state.syncStorage) {
sa.system_api.setStorageSync('sensors_prepare_data', sa.batch_state.mem);
sa.batch_state.changed = false;
}
}
}
sa.batchWrite = batchWrite;
function batchInterval() {
// 每隔1秒,写入数据
function loopWrite() {
setTimeout(function () {
batchWrite();
loopWrite();
}, 1000);
}
// 默认每隔6秒,发送数据
function loopSend() {
setTimeout(function () {
batchSend();
loopSend();
}, sa.para.batch_send.send_timeout * Math.pow(2, sa.batch_state.failTime));
}
loopWrite();
loopSend();
}
sa.prepareData = function (p) {
var data = {
distinct_id: sa.store.getDistinctId(),
lib: {
$lib: sa.lib.name,
$lib_method: sa.lib.method,
$lib_version: String(sa.lib.version)
},
properties: {}
};
//兼容是否有 ID3 的小程序
if (isObject(sa.store._state.identities)) {
data.identities = extend({}, sa.store.getIdentities());
}
// unbind 额外属性修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
data.identities = _.deepCopy(p.unbind_value);
delete p.unbind_value;
}
extend(data, sa.store.getUnionId(), p);
// 合并properties里的属性
if (isObject(p.properties) && !isEmptyObject(p.properties)) {
extend(data.properties, p.properties);
}
// unbind 额外id修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
if (data.login_id) {
delete data.login_id;
}
if (data.anonymous_id) {
delete data.anonymous_id;
}
}
// profile时不传公用属性
if (!p.type || p.type.slice(0, 7) !== 'profile') {
data._track_id = Number(String(getRandom()).slice(2, 5) + String(getRandom()).slice(2, 4) + String(Date.now()).slice(-4));
// 传入的属性 > 当前页面的属性 > session的属性 > cookie的属性 > 预定义属性
data.properties = extend({}, sa.properties, sa.store.getProps(), sa.currentProps, data.properties);
// 当上报的是事件的数据设置 $is_first_day 属性,对于上报用户属性相关的事件均不上报 $is_first_day 属性
if (p.type === 'track') {
data.properties.$is_first_day = getIsFirstDay();
}
}
if (data.properties.$time && isDate(data.properties.$time)) {
data.time = data.properties.$time * 1;
delete data.properties.$time;
} else {
data.time = new Date() * 1;
}
sa.ee.data.emit('beforeBuildCheck', data);
parseSuperProperties(data.properties);
searchObjDate(data);
stripProperties(data.properties);
searchObjString(data);
sa.ee.data.emit('finalAdjustData', data);
if (!sa.para.server_url) {
return false;
}
sa.log(data);
sa.send(data);
};
sa.send = function (t) {
// t._nocache = (String(getRandom()) + String(getRandom()) + String(getRandom())).slice(2, 15);
if (sa.storageName === 'sensorsdata2015_binance') {
if (sa.para.data_report_type === 'native') {
reportEvent(t);
return false;
}
}
if (sa.para.batch_send) {
if (sa.batch_state.getLength() >= 500) {
sa.log('数据量存储过大,有异常');
sa.batch_state.mem.shift();
}
sa.batch_state.add(t);
sa.batch_state.changed = true;
if (sa.batch_state.getLength() >= sa.para.batch_send.max_length) {
batchSend();
}
} else {
kit.onceSend(t);
}
};
function reportEvent(data) {
var event_name_prefix = 'sensors_';
var event_name = '';
data._flush_time = Date.now();
if (data.event) {
event_name = event_name_prefix + data.event;
} else {
event_name = event_name_prefix + data.type;
}
data.dataSource = 'sensors';
sa.log('report_event, name: ', event_name, '-- key: ', data);
__mp_private_api__.reportEvent(event_name, data);
}
// request 直接调用 sa.request
sa.log = function () {
if (sa.para.show_log) {
if (typeof console === 'object' && console.log) {
try {
var arg = Array.prototype.slice.call(arguments);
return console.log.apply(console, arg);
} catch (e) {
console.log(arguments[0]);
}
}
}
};
sa.track = function (e, p, c) {
sa.prepareData(
{
type: 'track',
event: e,
properties: p
},
c
);
};
sa.setProfile = function (p) {
sa.prepareData({
type: 'profile_set',
properties: p
});
};
sa.setOnceProfile = function (p, c) {
sa.prepareData(
{
type: 'profile_set_once',
properties: p
},
c
);
};
sa.login = function (id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (id !== distinctId) {
if (firstId) {
sa.trackSignup(id, '$SignUp');
} else {
sa.store.set('first_id', distinctId);
sa.trackSignup(id, '$SignUp');
}
}
};
sa.logout = function (isChangeId) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', '');
if (isChangeId === true) {
sa.store.set('distinct_id', getUUID());
} else {
sa.store.set('distinct_id', firstId);
}
} else {
sa.log('没有first_id,logout失败');
}
};
sa.identify = function (id) {
id = _.validId(id);
if (id) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', id);
} else {
sa.store.set('distinct_id', id);
}
}
};
/**
*
* @param {object} idObj 分别为 id: id 值、event_name: 事件名、id_name: 自定义 ID 的 name
* @param {*} e 事件类型
* @param {*} p 数据
* 原传参方式通过 4 个参数来实现,但使用过程中并未传入 p 和 c 参数,故不做处理
* 兼容原有 ID 处理逻辑,判断第一个参数是否为一个对象,是对象则为新 3.0 的接口,需要按 3.0 的传参逻辑进行参数获取
* 在现逻辑中为了不修改老 3.0 中调用 trackSignup 逻辑,若登录 ID key 为默认的 $identity_login_id 则不传 idName 参数
*/
sa.trackSignup = function (idObj, e, p) {
var currentId, eventName, idName, distinctId, originalId;
if (isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
sa.store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
originalId = sa.store.getFirstId() || sa.store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
};
sa.registerApp = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.currentProps = extend(sa.currentProps, obj);
}
};
sa.clearAppRegister = function (arr) {
if (isArray(arr)) {
each(sa.currentProps, function (value, key) {
if (include(arr, key)) {
delete sa.currentProps[key];
}
});
}
};
sa.register = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.store.setProps(obj);
}
};
sa.clearAllRegister = function () {
sa.store.setProps({}, true);
};
sa.use = function (plugin) {
const args = toArray(arguments, 1);
args.unshift(this);
if (isObject(plugin) && isFunction(plugin.init)) {
plugin.init.apply(plugin, args);
}
return plugin;
};
// sa 上挂载 use & usePlugin 保持小程序插件使用 API 的统一
sa.usePlugin = sa.use;
sa.getServerUrl = function () {
return sa.para.server_url;
};
sa.registerPropertyPlugin = function (arg) {
if (!isFunction(arg.properties)) {
sa.log('registerPropertyPlugin arguments error, properties must be function');
return;
}
if (arg.isMatchedWithFilter && !isFunction(arg.isMatchedWithFilter)) {
sa.log('registerPropertyPlugin arguments error, isMatchedWithFilter must be function');
return;
}
sa.ee.data.on('finalAdjustData', function (data) {
try {
if (isFunction(arg.isMatchedWithFilter)) {
arg.isMatchedWithFilter(data) && arg.properties(data);
} else {
arg.properties(data);
}
} catch (e) {
sa.log('execute registerPropertyPlugin callback error:' + e);
}
});
};
/*
* @Date: 2022-11-01 19:03:46
* @File: 用户生态系统 通用版本
*/
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var store = {
inited: true,
// 防止重复请求
storageInfo: null,
store_queue: [],
getStorage: function () {
if (this.storageInfo) {
return this.storageInfo;
} else {
this.storageInfo = sa.system_api.getStorageSync(sa.storageName) || '';
return this.storageInfo;
}
},
_state: {},
getUUID: function () {
return getUUID();
},
toState: function (ds) {
var state = null;
var _this = this;
function isStateDistinctId() {
if (state.distinct_id) {
_this._state = state;
} else {
_this.set('distinct_id', getUUID());
}
}
if (isJSONString(ds)) {
state = JSON.parse(ds);
isStateDistinctId();
} else if (isObject(ds)) {
state = ds;
isStateDistinctId();
} else {
this.set('distinct_id', getUUID());
}
// 在初始化同步 storage ID 属性到内存中时,将对应的 identities 对象进行处理
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this._state._distinct_id || this._state.distinct_id;
var history_login_id = this._state.history_login_id ? this._state.history_login_id : {};
var old_login_id_name = history_login_id.name;
// 解密 iddentities
if (this._state.identities && isString(this._state.identities)) {
var identities = JSON.parse(rot13defs(this._state.identities));
this._state.identities = identities;
}
// 初始化处理匿名 ID 及 初始化 identities
if (!this._state.identities || !isObject(this._state.identities) || isEmptyObject(this._state.identities)) {
this._state.identities = {};
this._state.identities[IDENTITIES.identity_id] = getUUID();
}
function delIdentitiesProp(value) {
for (var identitiesProp in store._state.identities) {
if (hasOwnProperty$1.call(store._state.identities, identitiesProp)) {
if (identitiesProp !== IDENTITIES.identity_id && identitiesProp !== value) {
delete store._state.identities[identitiesProp];
}
}
}
}
// 以下处理登录 ID 的相关逻辑
if (first_id) {
// 处理存在老的 3.0 登录 ID 逻辑,及不存在登录 ID 的情况
if (old_login_id_name && hasOwnProperty$1.call(this._state.identities, old_login_id_name)) {
if (this._state.identities[old_login_id_name] !== distinct_id) {
this._state.identities[old_login_id_name] = distinct_id;
delIdentitiesProp(old_login_id_name);
this._state.history_login_id.value = distinct_id;
}
} else {
this._state.identities[IDENTITY_KEY.LOGIN] = distinct_id;
delIdentitiesProp(IDENTITY_KEY.LOGIN);
this._state.history_login_id = {
name: IDENTITY_KEY.LOGIN,
value: distinct_id
};
}
} else {
this._state.history_login_id = {
name: '',
value: ''
};
}
this.save();
},
getFirstId: function () {
return this._state._first_id || this._state.first_id;
},
/**
* 获取当前 distinct_id,如果有 IDM3 状态下的登录的 distinctId 则返回此 ID 值,若没有则返回当前的匿名 ID
* @returns distinct_id
*/
getDistinctId: function () {
var loginDistinctId = this.getLoginDistinctId();
if (loginDistinctId) {
return loginDistinctId;
} else {
return this._state._distinct_id || this._state.distinct_id;
}
},
getUnionId: function () {
var obj = {};
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this.getDistinctId();
if (first_id && distinct_id) {
obj['login_id'] = distinct_id;
obj['anonymous_id'] = first_id;
} else {
obj['anonymous_id'] = distinct_id;
}
return obj;
},
// 区别于 identities,这里会加入 $identities_anonymous_id
getIdentities: function () {
var iden = JSON.parse(JSON.stringify(this._state.identities));
iden.$identity_anonymous_id = this.getAnonymousId();
return iden;
},
getAnonymousId: function () {
return this.getUnionId().anonymous_id;
},
/**
* 新增 getHistoryLoginId 接口,用以获取到老的登录用户 ID 标识
*/
getHistoryLoginId: function () {
if (isObject(this._state.history_login_id)) {
return this._state.history_login_id;
} else {
return null;
}
},
/**
* 获取当前的登录情况下的 distinctId
* 获取当前 distinct_id,如果为 IDM3 登录 ID,则值为登录 ID 的 name + value 的格式
* 如果为非登录状态,则直接返回 null,标识无值
*/
getLoginDistinctId: function () {
var historyLoginId = this.getHistoryLoginId();
// 存在登录 ID 对象,且登录 ID 值为真(排除登录后登出,保存 history_login_id 对象,但清空属性值的情况);否则为未登录状态,直接取当前的 distinct_id
if (isObject(historyLoginId) && historyLoginId.value) {
if (historyLoginId.name !== IDENTITY_KEY.LOGIN) {
return historyLoginId.name + '+' + historyLoginId.value;
} else {
return historyLoginId.value;
}
} else {
return null;
}
},
getProps: function () {
return this._state.props || {};
},
setProps: function (newp, isCover) {
var props = this._state.props || {};
if (!isCover) {
extend(props, newp);
this.set('props', props);
} else {
this.set('props', newp);
}
},
set: function (name, value) {
var obj = {};
if (typeof name === 'string') {
obj[name] = value;
} else if (typeof name === 'object') {
obj = name;
}
this._state = this._state || {};
for (var i in obj) {
this._state[i] = obj[i];
// 如果set('first_id') 或者 set('distinct_id'),删除对应的临时属性
if (i === 'first_id') {
delete this._state._first_id;
} else if (i === 'distinct_id') {
delete this._state._distinct_id;
// deprecated 不推荐使用,即将废弃
sa.events.emit('changeDistinctId');
}
}
this.save();
},
identitiesSet: function (params) {
var identities = {};
switch (params.type) {
case 'login':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
identities[params.id_name] = params.id;
break;
case 'logout':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
break;
// donoting
}
this.set('identities', identities);
},
change: function (name, value) {
this._state['_' + name] = value;
},
encryptStorage: function () {
var copyState = this.getStorage();
var flag = 'data:enc;';
if (isObject(copyState)) {
copyState = flag + rot13obfs(JSON.stringify(copyState));
} else if (isString(copyState)) {
if (copyState.indexOf(flag) === -1) {
copyState = flag + rot13obfs(copyState);
}
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
save: function () {
// 深拷贝避免修改原对象
var copyState = deepCopy(this._state);
// 对 identitie 进行加密
var identities = rot13obfs(JSON.stringify(copyState.identities));
copyState.identities = identities;
// 删除临时属性避免写入微信 storage
delete copyState._first_id;
delete copyState._distinct_id;
// 是否开启本地存储加密
if (sa.para.encrypt_storage) {
var flag = 'data:enc;';
copyState = flag + rot13obfs(JSON.stringify(copyState));
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
init: function () {
var info = this.getStorage();
var flag = 'data:enc;';
var uuid = getUUID();
if (info) {
if (isString(info)) {
//判断是否有加密的字段 有就解密
if (info.indexOf(flag) !== -1) {
info = info.substring(flag.length);
info = JSON.parse(rot13defs(info));
}
}
this.toState(info);
} else {
meta.is_first_launch = true;
var time = new Date();
var visit_time = time.getTime();
time.setHours(23);
time.setMinutes(59);
time.setSeconds(60);
this.set({
distinct_id: uuid,
first_visit_time: visit_time,
first_visit_day_time: time.getTime(),
identities: {
[IDENTITIES.identity_id]: uuid
},
history_login_id: {
name: '',
value: ''
}
});
sa.setOnceProfile({ $first_visit_time: time });
}
this.checkStoreInit && this.checkStoreInit();
}
};
sa.store = store;
/*
* @Date: 2022-12-05 16:21:58
* @File: 通用 ID2 、ID3 相关 API
*/
function trackSignup(idObj, e, p) {
var currentId, eventName, idName, distinctId;
if (_.isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
var originalId = store.getFirstId() || store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
}
function bindWithoutCheck(name, value) {
var identities = store._state.identities;
identities[name] = value;
store.save();
sa.prepareData({
type: 'track_id_bind',
event: '$BindID'
});
}
function bind$1(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 获取当前的 login_id key
var historyLoginId = store.getHistoryLoginId();
var currentLoginIdName = historyLoginId ? historyLoginId.name : '';
var presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName];
if (_.isArray(IDENTITIES.bind_preset_id)) {
presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName].concat(IDENTITIES.bind_preset_id);
}
// 通过 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, presetIdKeys)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
bindWithoutCheck(name, value);
}
function unbindWithoutCheck(name, value) {
if (hasOwnProperty.call(store._state.identities, name) && value === store._state.identities[name]) {
if (IDENTITIES.unbind_without_check && IDENTITIES.unbind_without_check.indexOf(name) < 0) {
delete store._state.identities[name];
}
store.save();
}
var distinctId = store.getDistinctId();
var firstId = store.getFirstId();
var unbindDistinctId = name + '+' + value;
if (distinctId === unbindDistinctId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
store.set('history_login_id', {
name: '',
value: ''
});
}
var para = {};
para[name] = value;
sa.prepareData({
type: 'track_id_unbind',
event: '$UnbindID',
unbind_value: para
});
}
function unbind(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 通过 isPresetIdKeys 判断是否是预置的 id key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, [IDENTITY_KEY.LOGIN])) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
unbindWithoutCheck(name, value);
}
/**
* 通过自定义的登录 ID 的 key(name)值进行登录
* @param {string} name
* @param {string} id
* @returns
*/
function loginWithKey(name, id) {
sa.log('loginWithKey is deprecated !!!');
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 这个单独判断 name 的 length 是为了符合测试提出的多端检查统一,保证判断 loginWithKey 的 key 值时长度超过 100 打印日志,但继续做后续 ID 绑定
// 同时 checkKeyword 未做修改,是为了保持原有统一检查逻辑不变,以免影响到其他检查
// 在 name 的 length 的值小于 100 的情况下,若其他检查不符,会做 return 处理
var info = '';
if (!_.check.checkKeyword(name) && name.length > 100) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
} else if (!_.check.checkKeyword(name)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (_.isPresetIdKeys(name, IDENTITIES.login_preset_id)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
id = _.validId(id);
// 如果 ID 不合法,直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
// 通过 isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(name, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
store._state.identities[name] = id;
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: name,
value: id
});
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp',
id_name: name
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将 login 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: name
});
}
}
function login(id) {
id = _.validId(id);
// 如果 ID 不合法直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
var idName = IDENTITY_KEY.LOGIN;
// 通过 _.isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(idName, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
if (store._state.identities) {
store._state.identities[idName] = id;
}
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: idName,
value: id
});
// 处理 trackSignup 逻辑,其中 newDistinctId 作为 2.0 的 distinct_id 通过 trackSignup 进行保存
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp'
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将登录 id 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: idName
});
}
}
function logout() {
var firstId = store.getFirstId();
// IDM3 ID identities 先做更新,然后更新外层的 ID
store.identitiesSet({ type: 'logout' });
// 删除 history_login_id 的登录 ID
store.set('history_login_id', {
name: '',
value: ''
});
if (firstId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
} else {
sa.log('没有first_id,logout失败');
}
}
// export function bindOpenid(openid) {
// openid = _.validId(openid);
// if (!openid) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// bind(name, openid);
// }
// export function unbindOpenid(val) {
// var id = _.validId(val);
// if (!id) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// // 不管本地有没有都要 unbind
// unbind(name, val);
// }
function getIdentities() {
if (_.isEmptyObject(store._state)) {
return null;
} else {
return store.getIdentities() || null;
}
}
// 重置 id3 匿名 id,只有在未登录情况下可以使用!!!
function resetAnonymousIdentity(id) {
// 登录则 return
var firstId = store.getFirstId();
if (firstId) {
sa.log('resetAnonymousIdentity must be used in a logout state !');
return false;
}
if (typeof id === 'number') {
id = String(id);
}
// id 有值则替换,没值则重置
if (typeof id === 'undefined') {
var uuid = store.getUUID();
store._state.identities[IDENTITIES.identity_id] = uuid;
store.set('distinct_id', uuid);
} else if (_.validId(id)) {
store._state.identities[IDENTITIES.identity_id] = id;
store.set('distinct_id', id);
}
}
function getPresetProperties$1() {
return _.getPresetProperties();
}
function getAnonymousID() {
if (_.isEmptyObject(sa.store._state)) {
sa.log('请先初始化SDK');
} else {
return sa.store._state._first_id || sa.store._state.first_id || sa.store._state._distinct_id || sa.store._state.distinct_id;
}
}
var functions = /*#__PURE__*/Object.freeze({
__proto__: null,
trackSignup: trackSignup,
bindWithoutCheck: bindWithoutCheck,
bind: bind$1,
unbindWithoutCheck: unbindWithoutCheck,
unbind: unbind,
loginWithKey: loginWithKey,
login: login,
logout: logout,
getIdentities: getIdentities,
resetAnonymousIdentity: resetAnonymousIdentity,
getPresetProperties: getPresetProperties$1,
getAnonymousID: getAnonymousID
});
/*
* @Date: 2022-12-13 18:50:04
* @File:
*/
//对外 API 设置
for (var f in functions) {
sa[f] = functions[f];
}
var identity_id = '$identity_baidu_mp_id';
IDENTITIES.identity_unionid = '';
IDENTITIES.identity_id = identity_id; //配置平台默认匿名 ID
IDENTITIES.openid_name = 'baidu'; //配置平台 name
IDENTITIES.bind_preset_id = [identity_id]; //配置 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
IDENTITIES.unbind_without_check = [identity_id]; //unbindWithoutCheck 过滤 ID 配置
IDENTITIES.login_preset_id = [identity_id]; //loginWithKey 预设ID 校验
REQUEST.header = { 'Content-Type': 'text/plain' };
function isValidListener(listener) {
if (typeof listener === 'function') {
return true;
} else if (listener && typeof listener === 'object') {
return isValidListener(listener.listener);
} else {
return false;
}
}
/**
* @class EventEmitter
* @category Event
* @example
* var e = new EventEmitter()
* e.on('HelloEvent',function(data){
* console.log('Hello Event happens',data);
* })
*
* e.emit('HelloEvent',123);
* // Hello Event happens , 123
*/
class EventEmitterBase {
constructor() {
this._events = {};
}
/**
* 添加事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
on(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].push(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prepend(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].unshift(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头,回调只执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prependOnce(eventName, listener) {
return this.prepend(eventName, {
listener: listener,
once: true
});
}
/**
* 添加事件,该事件只能被执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
once(eventName, listener) {
return this.on(eventName, {
listener: listener,
once: true
});
}
/**
* 删除事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
off(eventName, listener) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
if (typeof listener === 'number') {
listeners.splice(listener, 1);
} else if (typeof listener === 'function') {
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i] && listeners[i].listener === listener) {
listeners.splice(i, 1);
}
}
}
return this;
}
/**
* 触发事件
* @param {String} eventName 事件名称
* @param {Array} args 传入监听器函数的参数,使用数组形式传入
* @return {Object} 可链式调用
*/
emit(eventName, args) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
if (listener) {
listener.listener.call(this, args || {});
if (listener.once) {
this.off(eventName, i);
}
}
}
return this;
}
/**
* 删除某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
removeAllListeners(eventName) {
if (eventName && this._events[eventName]) {
this._events[eventName] = [];
} else {
this._events = {};
}
}
/**
* 返回某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
listeners(eventName) {
if (eventName && typeof eventName === 'string') {
return this._events[eventName];
} else {
return this._events;
}
}
}
/**
* ex 扩展
*/
class EventEmitterEx extends EventEmitterBase {
constructor() {
super();
this.cacheEvents = [];
this.maxLen = 20;
}
replay(eventName, listener) {
this.on(eventName, listener);
if (this.cacheEvents.length > 0) {
this.cacheEvents.forEach(function (val) {
if (val.type === eventName) {
listener.call(null, val.data);
}
});
}
}
emit(eventName, args) {
super.emit.apply(this, arguments);
this.cacheEvents.push({ type: eventName, data: args });
this.cacheEvents.length > this.maxLen ? this.cacheEvents.shift() : null;
}
}
/*
* @Date: 2022-07-07 14:20:38
* @File:
*/
var ee = {};
ee.sdk = new EventEmitterEx();
ee.data = new EventEmitterEx();
/*
* @Date: 2022-06-08 18:59:23
* @File: 老版的事件订阅发布
*/
var eventEmitter = function () {
this.sub = [];
};
eventEmitter.prototype = {
add: function (item) {
this.sub.push(item);
},
emit: function (event, data) {
this.sub.forEach(function (temp) {
temp.on(event, data);
});
}
};
var eventSub = function (handle) {
sa.events.add(this);
this._events = [];
this.handle = handle;
this.ready = false;
};
eventSub.prototype = {
on: function (event, data) {
if (this.ready) {
if (isFunction(this.handle)) {
try {
this.handle(event, data);
} catch (error) {
sa.log(error);
}
}
} else {
this._events.push({
event,
data
});
}
},
isReady: function () {
var that = this;
that.ready = true;
that._events.forEach(function (item) {
if (isFunction(that.handle)) {
try {
that.handle(item.event, item.data);
} catch (error) {
sa.log(error);
}
}
});
}
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
//事件发布订阅监听
sa.ee = ee;
//内部全局变量
sa.meta = meta;
sa.kit = kit;
// use 插件存储
sa.modules = {};
//兼容老版的事件发布订阅
sa.eventSub = eventSub;
sa.events = new eventEmitter();
sa.init = function (obj) {
// 是否执行过init,防止重复执行
if (meta.hasExeInit === true) {
return false;
}
if (obj && isObject(obj)) {
sa.setPara(obj);
}
meta.hasExeInit = true;
if (obj && isObject(obj)) {
sa.setPara(obj);
}
// ------------- 全局参数准备完毕
// 可以使用 param
ee.sdk.emit('afterInitPara');
sa.store.init();
sa.system.init();
if (sa.para.batch_send) {
sa.system_api.getStorage('sensors_prepare_data', function (res) {
var queue = [];
if (res && res.data && isArray(res.data)) {
queue = res.data;
sa.batch_state.mem = queue.concat(sa.batch_state.mem);
}
sa.batch_state.syncStorage = true;
});
batchInterval();
}
};
sa.setPara = function (para) {
sa.para = extend2Lev(sa.para, para);
var channel = [];
if (isArray(sa.para.source_channel)) {
var len = sa.para.source_channel.length;
for (var c = 0; c < len; c++) {
if (RESERVE_CHANNEL.indexOf(' ' + sa.para.source_channel[c] + ' ') === -1) {
channel.push(sa.para.source_channel[c]);
}
}
}
sa.para.source_channel = channel;
if (typeof sa.para.send_timeout !== 'number') {
sa.para.send_timeout = 1000;
}
var batch_send_default = {
send_timeout: 6000,
max_length: 6
};
// 如果已经配置为批量发送,且未定义请求撤销时间的情况下,设置请求撤销时间为 10s
if (para && para.datasend_timeout); else if (sa.para.batch_send) {
sa.para.datasend_timeout = 10000;
}
// 如果是true,转换成对象
if (sa.para.batch_send === true) {
sa.para.batch_send = extend({}, batch_send_default);
} else if (isObject(sa.para.batch_send)) {
sa.para.batch_send = extend({}, batch_send_default, sa.para.batch_send);
}
if (!sa.para.server_url) {
sa.log('请使用 setPara() 方法设置 server_url 数据接收地址,详情可查看https://www.sensorsdata.cn/manual/mp_sdk_new.html#112-%E5%BC%95%E5%85%A5%E5%B9%B6%E9%85%8D%E7%BD%AE%E5%8F%82%E6%95%B0');
return;
}
sa.para.preset_properties = isObject(sa.para.preset_properties) ? sa.para.preset_properties : {};
};
sa.checkInit = function () {
if (sa.system.inited === true && sa.store.inited === true) {
sa.inited = true;
if (sa._queue.length > 0) {
each(sa._queue, function (content) {
sa[content[0]].apply(sa, slice.call(content[1]));
});
sa._queue = [];
}
}
};
each(['setProfile', 'setOnceProfile', 'track', 'identify', 'bind', 'unbind', 'login', 'logout', 'registerApp', 'clearAppRegister'], function (method) {
var temp = sa[method];
sa[method] = function () {
if (sa.inited) {
temp.apply(sa, arguments);
} else {
sa._queue.push([method, arguments]);
//sa.log(`[sensorsdata]: 请先调用 sensors.init,再调用 ${method} api`);
}
};
});
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getNetwork() {
return new Promise(function (resolve) {
sa.system_api.getNetworkType({
success(t) {
sa.properties.$network_type = setUpperCase(t['networkType']);
},
fail(e) {
sa.log('获取网络状态信息失败: ', e);
},
complete() {
resolve();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getSystemInfo() {
return new Promise((reslove) => {
sa.system_api.getSystemInfo({
success(res) {
var p = sa.properties;
if (isObject(res)) {
p.$manufacturer = res['brand'];
p.$model = res['model'];
p.$brand = setUpperCase(res['brand']) || '';
p.$screen_width = Number(res['screenWidth']);
p.$screen_height = Number(res['screenHeight']);
p.$os = formatSystem(res['platform']);
p.$os_version = res['system'].indexOf(' ') > -1 ? res['system'].split(' ')[1] : res['system'];
p.$mp_client_app_version = res['version'] || '';
var sdk_version = res['SDKVersion'] || '';
if (sdk_version) {
p.$mp_client_basic_library_version = sdk_version;
}
}
},
fail(e) {
sa.log('获取系统信息失败: ', e);
},
complete() {
reslove();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
var system = {
inited: false,
init: function () {
var timeZoneOffset = new Date().getTimezoneOffset();
if (isNumber(timeZoneOffset)) {
sa.properties.$timezone_offset = timeZoneOffset;
}
var app_id = getAppId() || sa.para.app_id || sa.para.appid;
if (app_id) {
sa.properties.$app_id = app_id;
}
var network = getNetwork();
var sysytemInfo = getSystemInfo();
Promise.all([network, sysytemInfo]).then(function () {
sa.system.inited = true;
sa.checkInit();
});
}
};
function request(para) {
var timeout;
if (para.timeout) {
timeout = para.timeout;
delete para.timeout;
}
var rq = sa.platform_obj.request(para);
setTimeout(function () {
try {
if (isObject(rq) && isFunction(rq.abort)) {
rq.abort();
}
} catch (error) {
sa.log(error);
}
}, timeout);
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getStorage(key, complete) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (e) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (err) {
sa.log('获取 storage 失败!', err);
}
}
function parseRes(res) {
if (res && res.data && isJSONString(res.data)) {
try {
var data = JSON.parse(res.data);
res.data = data;
} catch (err) {
sa.log('parse res.data 失败!', err);
}
}
complete(res);
}
}
function setStorage(item, val) {
var value;
try {
value = JSON.stringify(val);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
sa.log('设置 storage 失败: ', err);
}
}
}
function getStorageSync(key) {
var store = '';
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e) {
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e2) {
sa.log('获取 storage 失败!');
}
}
if (isJSONString(store)) {
store = JSON.parse(store);
}
return store;
}
function setStorageSync(key, value) {
var item;
try {
item = JSON.stringify(value);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
var fn = function () {
sa.platform_obj.setStorageSync(key, item);
};
try {
fn();
} catch (e) {
sa.log('set Storage fail --', e);
try {
fn();
} catch (e2) {
sa.log('set Storage fail again --', e2);
}
}
}
/*
* @Date: 2021-10-13 15:29:49
* @File: 内部 API 统一
*/
function getNetworkType() {
return sa.platform_obj.getNetworkType.apply(null, arguments);
}
function getSystemInfo$1() {
return sa.platform_obj.getSystemInfo.apply(null, arguments);
}
function getAppId$1() {
var info;
if (sa.platform_obj.getAccountInfoSync) {
info = sa.platform_obj.getAccountInfoSync();
}
if (isObject(info) && isObject(info.miniProgram)) {
return info.miniProgram;
}
}
var compose = {
request: request,
getStorage: getStorage,
setStorage: setStorage,
getStorageSync: getStorageSync,
setStorageSync: setStorageSync,
getAppInfoSync: getAppId$1,
getNetworkType: getNetworkType,
getSystemInfo: getSystemInfo$1
};
compose.getAppInfoSync = function getAppInfoSync() {
if (isFunction(swan.getEnvInfoSync)) {
var info = swan.getEnvInfoSync();
if (info) {
return {
appId: info.appKey,
appEnv: info.env,
appVersion: info.appVersion
};
}
}
return {};
};
const forEach$1 = Array.prototype.forEach,
slice$1 = Array.prototype.slice,
_hasOwnProperty$1 = Object.prototype.hasOwnProperty,
_toString$1 = Object.prototype.toString;
function extend$1(obj) {
each$1(slice$1.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
function isObject$1(obj) {
return obj !== null && typeof obj === 'object';
}
function isFunction$1(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
function isString$1(obj) {
return _toString$1.call(obj) == '[object String]';
}
function each$1(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach$1 && obj.forEach === forEach$1) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty$1.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-03 08:05:52
* @File: SDK 内部 生命周期钩子统一接口
*/
var lifeCycleHook = ['appOnLaunch', 'appOnShow', 'appOnHide', 'pageOnShow', 'pageOnLoad'];
// 内部统一生命周期 API
var miniLifeCycleAPI = {};
lifeCycleHook.forEach(function (key) {
miniLifeCycleAPI[key] = function () {
throw new Error(`需要先定义 '${key}' 才能使用`);
};
});
/**
* 按照不同平台混入内部调用的 API (初始化时调用)
*
* @public
* @param {Object} mixinAPI 需混入的 API
* @returns {void}
*/
function registerLifeCycleHook(mixinAPI) {
Object.assign(miniLifeCycleAPI, mixinAPI);
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:56
* @File:
*/
function getScene(scene_value, sa) {
if (!isObject$1(sa)) {
return false;
}
var scene_prefix = sa.meta.scene_prefix;
// 判断是否存在 scene_prefix 来确定当前小程序是否采集 scene 场景值
if (!scene_prefix || !isString$1(scene_prefix)) {
return false;
}
if (typeof scene_value === 'number' || (typeof scene_value === 'string' && scene_value !== '')) {
scene_value = scene_prefix + String(scene_value);
return scene_value;
} else {
return '未取到值';
}
}
/**
* hook function
*
* @public
* @param {Object} obj 待 hook 对象
* @param {name} method 方法名
* @param {Function} hook hook 方法
* @returns {void}
* */
function hookFunc(obj, method, hook) {
var oldMethod = obj[method];
obj[method] = function (args) {
if (isFunction$1(hook)) {
hook.call(this, args);
}
oldMethod && isFunction$1(oldMethod) && oldMethod.call(this, args);
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: app 重写逻辑
*/
function hookAppFunc(option) {
hookFunc(option, 'onLaunch', miniLifeCycleAPI['appOnLaunch']);
hookFunc(option, 'onShow', miniLifeCycleAPI['appOnShow']);
hookFunc(option, 'onHide', miniLifeCycleAPI['appOnHide']);
}
/**
* hook app
* sa 引入主 SDK
* hookAppFunc 需要监听的生命周期
*/
function proxyApp(hookAppFunc, sa) {
function initAppGlobalName(callback) {
var oldApp = App;
App = function (option) {
try {
callback && callback(option);
option[sa.para.name] = sa;
oldApp.apply(this, arguments);
} catch (error) {
oldApp.apply(this, arguments);
global.sensors.log('App:' + error);
}
};
}
//有部分小程序提供如下 API,可以在app.js 没有生命 onshow,onHide 的情况下能监听到如下生命周期
if (isObject$1(sa) && isFunction$1(sa.platform_obj.onAppShow) && isFunction$1(sa.platform_obj.onAppHide)) {
initAppGlobalName();
sa.platform_obj.onAppShow(function (para) {
if (!sa.para.launched) {
var option = para || (isFunction$1(sa.platform_obj.getLaunchOptionsSync) && sa.platform_obj.getLaunchOptionsSync()) || {};
miniLifeCycleAPI.appOnLaunch(option);
sa.para.launched = true;
}
miniLifeCycleAPI.appOnShow(para);
});
sa.platform_obj.onAppHide(function () {
miniLifeCycleAPI.appOnHide();
});
} else {
initAppGlobalName(hookAppFunc);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:55:28
* @File: app 生命周期数据上报模块
*/
function appOnLaunch(option, prop) {
if (!isObject$1(option)) {
global.sensors.log('appOnLaunch:请传入正确的参数');
return;
}
var obj = {};
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.meta.current_scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
} else {
obj.$scene = '未取到值';
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (global.sensors.meta.is_first_launch) {
obj.$is_first_time = true;
if (!global.sensors._.isEmptyObject(utms.pre1)) {
global.sensors.setOnceProfile(utms.pre1);
}
} else {
obj.$is_first_time = false;
}
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appLaunch) {
global.sensors.track('$MPLaunch', obj);
}
}
function appOnShow(option, prop) {
var obj = {};
global.sensors.meta.mp_show_time = new Date().getTime();
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appShow) {
global.sensors.track('$MPShow', obj);
}
}
function appOnHide(prop) {
var current_time = new Date().getTime();
var obj = {};
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
extend$1(obj, global.sensors._.getPageProps());
var mpShowTime = global.sensors.meta.mp_show_time;
if (mpShowTime && current_time - mpShowTime > 0 && (current_time - mpShowTime) / 3600000 < 24) {
obj.event_duration = (current_time - mpShowTime) / 1000;
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appHide) {
global.sensors.track('$MPHide', obj);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 全埋点 appOnHide, appOnShow, appOnLaunch 通用版本使用
*/
var presetEvents = {
appLaunch: true,
appShow: true,
appHide: true
};
var AutoTrackApp = {
name: 'AutoTrackApp'
};
AutoTrackApp.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global.sensors = sensorsdata;
global.sensors.para.autoTrack = extend$1(presetEvents, para);
//初始化全埋点埋点方法
AutoTrackApp.lifeCycleAPI();
AutoTrackApp.proxyFrameworkInterface();
};
AutoTrackApp.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.appOnLaunch = appOnLaunch;
lifeCycleAPI.appOnShow = appOnShow;
lifeCycleAPI.appOnHide = appOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackApp.proxyFrameworkInterface = function () {
proxyApp(hookAppFunc, global.sensors);
};
/*
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global$1 = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:43
* @File:
*/
/**
* sa 引入主 SDK
*/
function getCurrentPath$1(sa) {
var url = '未取到';
var current_page = getCurrentPage$1(sa);
if (current_page && current_page.route) {
url = current_page.route;
}
return url;
}
/**
* sa 引入主 SDK
*/
function getCurrentPage$1(sa) {
var currentPage = {};
var pages;
if (sa) {
try {
pages = isFunction$1(sa.platform_obj.getCurrentPages) ? sa.platform_obj.getCurrentPages() : getCurrentPages();
currentPage = pages[pages.length - 1];
} catch (e) {
sa.log(e);
}
} else {
console.log('getCurrentPage:请传入 sa 对象');
}
return currentPage;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:35:22
* @File: 全埋点点击事件,数据处理模块
*/
function isClick(type) {
const TYPES = {
tap: 1,
longtap: 1,
longpress: 1
};
return !!TYPES[type];
}
function createClickData(events) {
var prop = {},
event_prop = {};
var current_target = events.currentTarget || {};
var dataset = current_target.dataset || {};
prop['$element_id'] = current_target.id;
prop['$element_type'] = dataset['type'];
prop['$element_content'] = dataset['content'];
prop['$element_name'] = dataset['name'];
if (isObject$1(events.event_prop)) {
event_prop = events.event_prop;
}
prop['$url_path'] = getCurrentPath$1(global$1.sensors);
prop['$url'] = global$1.sensors._.getPageProps().$url;
prop = extend$1(prop, event_prop);
return prop;
}
var ClickTrack = {};
ClickTrack.track = function (events) {
var prop = createClickData(events);
var current_target = events.currentTarget || {};
var target = events.target || {};
var type = events['type'];
var saPara = global$1.sensors.para;
if (isObject$1(saPara.framework) && isObject$1(saPara.framework.taro) && !saPara.framework.taro.createApp) {
if (target.id && current_target.id && target.id !== current_target.id) {
return false;
}
}
if (isObject$1(prop) && type && isClick(type)) {
if (saPara.preset_events && saPara.preset_events.collect_element && saPara.preset_events.collect_element(arguments[0]) === false) {
return false;
}
global$1.sensors.track('$MPClick', prop);
}
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:20:42
* @File: 全埋点点击事件核心逻辑模块
*/
var MP_HOOKS = {
data: 1,
onLoad: 1,
onShow: 1,
onReady: 1,
onPullDownRefresh: 1,
onReachBottom: 1,
onShareAppMessage: 1,
onPageScroll: 1,
onResize: 1,
onTabItemTap: 1,
onHide: 1,
onUnload: 1
};
// 重点注意 clickProxy 不能使用 return false
function clickProxy(option, method) {
var oldFunc = option[method];
option[method] = function () {
// 在重写 oldFunc 之前就已经判断是一个方法类型,此处是做一次重复的校验
var res = oldFunc.apply(this, arguments);
var args = arguments[0];
if (isObject$1(args)) {
ClickTrack.track(args);
}
return res;
};
}
function monitorClick(option) {
var methods = [];
var autoTrack = global$1.sensors.para.autoTrack;
if (autoTrack && autoTrack.mpClick) {
methods = getMethods(option);
tabProxy(option);
var len = methods.length;
for (var i = 0; i < len; i++) {
clickProxy(option, methods[i]);
}
}
}
// 监听重写 tabBar
function tabProxy(option) {
var oldTab = option['onTabItemTap'];
option['onTabItemTap'] = function (item) {
if (oldTab) {
oldTab.apply(this, arguments);
}
var prop = {};
if (item) {
prop['$element_content'] = item.text || '';
}
prop['$element_type'] = 'tabBar';
prop['$url_path'] = item.pagePath ? item.pagePath : global$1.sensors._.getCurrentPath();
global$1.sensors.track('$MPClick', prop);
};
}
// 对 page 所有事件进行清理
function getMethods(option) {
var methods = [];
for (var m in option) {
if (typeof option[m] === 'function' && !MP_HOOKS[m]) {
methods.push(m);
}
}
return methods;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: Page Component 重写逻辑模块
*/
// option是 Page(option) option={onLoad(){},onShow(){}}
function hookPageFunc(option) {
hookFunc(option, 'onShow', miniLifeCycleAPI['pageOnShow']);
hookFunc(option, 'onLoad', miniLifeCycleAPI['pageOnLoad']);
hookFunc(option, 'onUnload', miniLifeCycleAPI['pageOnUnload']);
hookFunc(option, 'onHide', miniLifeCycleAPI['pageOnHide']);
}
/**
* hook Page
*/
function proxyPage(hookPageFunc, monitorClick) {
var oldPage = Page;
Page = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
isFunction$1(hookPageFunc) && hookPageFunc(option);
isFunction$1(monitorClick) && monitorClick(option);
oldPage.apply(this, arguments);
} catch (error) {
oldPage.apply(this, arguments);
console.log('Page:' + error);
}
};
var oldComponent = Component;
Component = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
if (!option.methods) {
option.methods = {};
}
isFunction$1(monitorClick) && monitorClick(option.methods);
oldComponent.apply(this, arguments);
} catch (e) {
oldComponent.apply(this, arguments);
console.log('Component:' + e);
}
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:21:53
* @File:
*/
var pageLeave = function () {
if (global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageLeave) {
var currentPage = {};
var router = '';
try {
currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log(error);
}
if (global$1.sensors.meta.page_show_time >= 0 && router !== '') {
var prop = {};
var page_stay_time = (Date.now() - global$1.sensors.meta.page_show_time) / 1000;
if (isNaN(page_stay_time) || page_stay_time < 0) {
page_stay_time = 0;
}
extend$1(prop, global$1.sensors._.getPageProps());
prop.event_duration = page_stay_time;
// 数据上报前,判断当前页面是否采集
global$1.sensors.track('$MPPageLeave', prop);
global$1.sensors.meta.page_show_time = -1;
}
}
};
function pageOnLoad(option) {
var currentPage = this;
if (global$1.sensors._.isObject(option)) {
try {
currentPage = getCurrentPage$1(global$1.sensors);
} catch (error) {
global$1.sensors.log('pageOnLoad:' + error);
}
currentPage.sensors_mp_url_query = global$1.sensors._.setQuery(option);
currentPage.sensors_mp_encode_url_query = global$1.sensors._.setQuery(option, true);
}
}
function pageOnShow() {
global$1.sensors.meta.page_show_time = Date.now();
var obj = {};
var router = '';
try {
var currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log('pageOnShow:' + error);
}
extend$1(obj, global$1.sensors._.getPageProps());
obj.$referrer = global$1.sensors.meta.sa_referrer;
if (global$1.sensors.para && global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageShow) {
global$1.sensors.track('$MPViewScreen', obj);
}
global$1.sensors.meta.sa_referrer = router;
}
function pageOnUnload() {
pageLeave();
}
function pageOnHide() {
pageLeave();
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 通用全埋点事件入口,如果需要定制化,在对应平台入口进行定制化初始化
*/
var presetEvents$1 = {
pageShow: true,
mpClick: true,
pageLeave: false
};
var AutoTrackPage = {
name: 'AutoTrackPage'
};
AutoTrackPage.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global$1.sensors = sensorsdata;
global$1.sensors.para.autoTrack = extend$1(presetEvents$1, para);
//初始化全埋点埋点方法
AutoTrackPage.lifeCycleAPI();
AutoTrackPage.proxyFrameworkInterface();
};
AutoTrackPage.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.pageOnShow = pageOnShow;
lifeCycleAPI.pageOnLoad = pageOnLoad;
lifeCycleAPI.pageOnUnload = pageOnUnload;
lifeCycleAPI.pageOnHide = pageOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackPage.proxyFrameworkInterface = function () {
proxyPage(hookPageFunc, monitorClick);
};
var presetEvents$2 = {
appLaunch: true,
appShow: true,
appHide: true,
pageShow: true,
mpClick: true
};
var AutoTrack = {};
var oldPage = Page;
var oldApp = App;
AutoTrack.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
var autoTrackConfig = extend$1(presetEvents$2, para);
sensorsdata.use(AutoTrackApp, autoTrackConfig);
sensorsdata.use(AutoTrackPage, autoTrackConfig);
Object.assign(App, oldApp);
Object.assign(Page, oldPage);
};
sa.lib.name = 'SmartProgram';
sa.properties.$lib = 'SmartProgram';
sa.properties.$data_ingestion_source = ['SmartProgram'];
sa.system = system;
sa.system_api = compose;
sa._ = _;
sa.storageName = 'sensorsdata2015_baidu';
sa.meta.scene_prefix = 'baidu-';
sa.platform_obj = swan;
sa.use(AutoTrack);
export default sa;
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
var sa = {
is_first_launch: false,
launched: false, // 需接口中也做调整,
_queue: [],
mpshow_time: null,
sa_referrer: '直接打开',
query_share_depth: 0,
share_distinct_id: '',
share_method: '',
current_scene: '',
inited: false
};
sa.para = {
// 神策分析数据接收地址
server_url: '',
//默认使用队列发数据时候,两条数据发送间的最大间隔
send_timeout: 1000,
// 是否允许控制台打印查看埋点数据(建议开启查看)
show_log: false,
// 是否允许修改onShareMessage里return的path,用来增加(用户id,分享层级,当前的path),在app onshow中自动获取这些参数来查看具体分享来源,层级等
allow_amend_share_path: true,
max_string_length: 500,
datasend_timeout: 3000,
source_channel: [],
batch_send: {
send_timeout: 6000,
max_length: 6
},
preset_properties: {}
};
sa.platform = '';
sa.lib = {
version: '0.14.3',
name: 'MiniGame',
method: 'code'
};
sa.properties = {
$lib: 'MiniGame',
$lib_version: '0.14.3'
};
sa.currentProps = {};
/*
* @Date: 2022-06-09 11:36:17
* @File:
*/
var SOURCE_CHANNEL_STANDARD = 'utm_source utm_medium utm_campaign utm_content utm_term';
var LATEST_SOURCE_CHANNEL = ['$latest_utm_source', '$latest_utm_medium', '$latest_utm_campaign', '$latest_utm_content', '$latest_utm_term', '$latest_sa_utm'];
var LATEST_SHARE_INFO = ['$latest_share_distinct_id', '$latest_share_url_path', '$latest_share_depth', '$latest_share_method'];
var IDENTITY_KEY = {
EMAIL: '$identity_email',
MOBILE: '$identity_mobile',
LOGIN: '$identity_login_id'
};
var IDENTITIES = {}; //ID3 用户相关的配置
var RESERVE_CHANNEL = ' utm_source utm_medium utm_campaign utm_content utm_term sa_utm ';
var REQUEST = {};
/*
* @Date: 2022-12-13 10:26:40
* @File:
*/
var identity_id = '$identity_byte_mp_id';
IDENTITIES.identity_id = identity_id; //配置平台默认匿名 ID
IDENTITIES.bind_preset_id = [identity_id]; //配置 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
IDENTITIES.unbind_without_check = [identity_id]; //unbindWithoutCheck 过滤 ID 配置
IDENTITIES.login_preset_id = [identity_id]; //loginWithKey 预设ID 校验
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
const _toString = Object.prototype.toString,
_hasOwnProperty = Object.prototype.hasOwnProperty,
indexOf = Array.prototype.indexOf,
slice = Array.prototype.slice,
_isArray = Array.prototype.isArray,
forEach = Array.prototype.forEach,
bind = Function.prototype.bind;
function isUndefined(obj) {
return obj === void 0;
}
function isString(obj) {
return _toString.call(obj) == '[object String]';
}
function isDate(obj) {
return _toString.call(obj) == '[object Date]';
}
function isBoolean(obj) {
return _toString.call(obj) == '[object Boolean]';
}
function isNumber(obj) {
return _toString.call(obj) == '[object Number]' && /[\d\\.]+/.test(String(obj));
}
function isJSONString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function isObject(obj) {
if (obj == null) {
return false;
} else {
return _toString.call(obj) === '[object Object]';
}
}
function isPlainObject(obj) {
return _toString.call(obj) === '[object Object]';
}
function isArray(obj) {
return _isArray || _toString.call(obj) === '[object Array]';
}
function isFuction(f) {
try {
return /^\s*\bfunction\b/.test(f);
} catch (x) {
return false;
}
}
function isArguments(obj) {
return !!(obj && _hasOwnProperty.call(obj, 'callee'));
}
function toString(val) {
return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val);
}
function each(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach && obj.forEach === forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
function toArray(iterable, start) {
if (!iterable) {
return [];
}
var ret = [];
if (iterable.toArray) {
ret = iterable.toArray();
}
if (isArray(iterable)) {
ret = slice.call(iterable);
}
if (isArguments(iterable)) {
ret = slice.call(iterable);
}
ret = values(iterable);
if (start && isNumber(start)) {
ret = ret.slice(start);
}
return ret;
}
function values(obj) {
var results = [];
if (obj == null) {
return results;
}
each(obj, function (value) {
results[results.length] = value;
});
return results;
}
// include 函数,如果对象包含属性,就返回空对象 {}
function include(obj, target) {
var found = false;
if (obj == null) {
return found;
}
if (indexOf && obj.indexOf === indexOf) {
return obj.indexOf(target) != -1;
}
each(obj, function (value) {
if (found || (found = value === target)) {
return {};
}
});
return found;
}
function unique(arr) {
var temp,
n = [],
o = {};
for (var i = 0; i < arr.length; i++) {
temp = arr[i];
if (!o[temp]) {
o[temp] = true;
n.push(temp);
}
}
return n;
}
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function formatDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds());
}
function searchObjDate(o) {
if (isObject(o) || isArray(o)) {
each(o, function (a, b) {
if (isObject(a) || isArray(a)) {
searchObjDate(o[b]);
} else {
if (isDate(a)) {
o[b] = formatDate(a);
}
}
});
}
}
function trim(str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
function isFunction(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
// 浅复制
function extend(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
// 深复制
function extend2Lev(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0 && source[prop] !== null) {
if (isObject(source[prop]) && isObject(obj[prop])) {
extend(obj[prop], source[prop]);
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
}
function isEmptyObject(obj) {
if (isObject(obj)) {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
return false;
}
/**
* 深复制对象
* @param {object} obj
* @returns
*/
function deepCopy(obj) {
var temp = {};
function deepClone(target, source) {
for (var k in source) {
var item = source[k];
if (isArray(item)) {
target[k] = [];
deepClone(target[k], item);
} else if (isObject(item)) {
target[k] = {};
deepClone(target[k], item);
} else {
target[k] = item;
}
}
}
deepClone(temp, obj);
return temp;
}
function formatString(str) {
if (str.length > sa.para.max_string_length) {
sa.log('字符串长度超过限制,已经做截取--' + str);
return str.slice(0, sa.para.max_string_length);
} else {
return str;
}
}
function searchObjString(o) {
if (isObject(o)) {
each(o, function (a, b) {
if (isObject(a)) {
searchObjString(o[b]);
} else {
if (isString(a)) {
o[b] = formatString(a);
}
}
});
}
}
function encodeDates(obj) {
each(obj, function (v, k) {
if (isDate(v)) {
obj[k] = formatDate(v);
} else if (isObject(v)) {
obj[k] = encodeDates(v);
}
});
return obj;
}
function utf8Encode(string) {
string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var utftext = '',
start,
end;
var stringl = 0,
n;
start = end = 0;
stringl = string.length;
for (n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
}
function base64Encode(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = utf8Encode(data);
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = (o1 << 16) | (o2 << 8) | o3;
h1 = (bits >> 18) & 0x3f;
h2 = (bits >> 12) & 0x3f;
h3 = (bits >> 6) & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}
return enc;
}
/*
* @Date: 2022-11-01 19:18:40
* @File:
*/
function _decodeURIComponent(val) {
var result = '';
try {
result = decodeURIComponent(val);
} catch (e) {
result = val;
}
return result;
}
/*
* @Date: 2022-08-12 14:18:53
* @File: 内部使用全局变量
*/
var meta = {
lib_version: '',
launched: false, // 需接口中也做调整,
lib_name: '',
query_share_depth: 0,
page_show_time: Date.now(), //页面停留时长
mp_show_time: null, //小程序停留时长
promise_list: [],
current_scene: '',
is_first_launch: false,
_queue: [],
inited: false,
hasExeInit: false,
scene_prefix: '', //场景值
share_distinct_id: '',
sa_referrer: '直接打开',
source_channel_standard: SOURCE_CHANNEL_STANDARD,
latest_source_channel: LATEST_SOURCE_CHANNEL,
latest_share_info: LATEST_SHARE_INFO
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getAppId() {
var info = sa.system_api.getAppInfoSync();
if (info && info.appId) {
return info.appId;
}
return '';
}
/*
* @Date: 2022-08-19 15:15:42
* @File: 业务相关模块
*/
function getObjFromQuery(str) {
var query = str.split('?');
var arr = [];
var obj = {};
if (query && query[1]) {
each(query[1].split('&'), function (value) {
arr = value.split('=');
if (arr[0] && arr[1]) {
obj[arr[0]] = arr[1];
}
});
} else {
return {};
}
return obj;
}
// 从query,q,scene三个参数中,解析得到一个整合的query对象
function getMixedQuery(para) {
var obj = detectOptionQuery(para);
var scene = obj.scene;
var q = obj.q;
// query
var query = obj.query;
for (var i in query) {
query[i] = _decodeURIComponent(query[i]);
}
// scene
if (scene) {
scene = _decodeURIComponent(scene);
if (scene.indexOf('?') !== -1) {
scene = '?' + scene.replace(/\?/g, '');
} else {
scene = '?' + scene;
}
extend(query, getObjFromQuery(scene));
}
// 普通二维码的q
if (q) {
extend(query, getObjFromQuery(_decodeURIComponent(q)));
}
return query;
}
// 筛选检测出para里的query,q,scene
function detectOptionQuery(para) {
if (!para || !isObject(para.query)) {
return {};
}
var result = {};
// path的query
result.query = extend({}, para.query);
function isBScene(obj) {
var source = ['utm_source', 'utm_content', 'utm_medium', 'utm_campaign', 'utm_term', 'sa_utm'];
var source_keyword = source.concat(sa.para.source_channel);
var reg = new RegExp('(' + source_keyword.join('|') + ')%3D', 'i');
var keys = Object.keys(obj);
if (keys.length === 1 && keys[0] === 'scene' && reg.test(obj.scene)) {
return true;
} else {
return false;
}
}
//如果query有scene,认为scene是b接口传过来的
if (isString(result.query.scene) && isBScene(result.query)) {
result.scene = result.query.scene;
delete result.query.scene;
}
//如果query有q
if (para.query.q && para.query.scancode_time && String(para.scene).slice(0, 3) === '101') {
result.q = String(result.query.q);
delete result.query.q;
delete result.query.scancode_time;
}
return result;
}
// 解析参数中的utm,并添加
function setUtm(para, prop) {
var utms = {};
var query = getMixedQuery(para);
var pre1 = getCustomUtmFromQuery(query, '$', '_', '$');
var pre2 = getCustomUtmFromQuery(query, '$latest_', '_latest_', '$latest_');
utms.pre1 = pre1;
utms.pre2 = pre2;
extend(prop, pre1);
return utms;
}
function setLatestChannel(channel) {
if (!isEmptyObject(channel)) {
if (includeChannel(channel, LATEST_SOURCE_CHANNEL)) {
sa.clearAppRegister(LATEST_SOURCE_CHANNEL);
}
sa.registerApp(channel);
}
function includeChannel(channel, arr) {
var found = false;
for (var i in arr) {
if (channel[arr[i]]) {
found = true;
}
}
return found;
}
}
// 从参数中解析来源参数
function getCustomUtmFromQuery(query, utm_prefix, source_channel_prefix, sautm_prefix) {
if (!isObject(query)) {
return {};
}
var result = {};
if (query['sa_utm']) {
for (var i in query) {
if (i === 'sa_utm') {
result[sautm_prefix + i] = query[i];
continue;
}
if (include(sa.para.source_channel, i)) {
result[source_channel_prefix + i] = query[i];
}
}
} else {
for (var k in query) {
if ((' ' + SOURCE_CHANNEL_STANDARD + ' ').indexOf(' ' + k + ' ') !== -1) {
result[utm_prefix + k] = query[k];
continue;
}
if (include(sa.para.source_channel, k)) {
result[source_channel_prefix + k] = query[k];
}
}
}
return result;
}
// 是否已经存在 latest utm
function existLatestUtm() {
var exit = false;
each(LATEST_SOURCE_CHANNEL, function (value) {
if (sa.properties[value]) {
exit = true;
}
});
return exit;
}
// query 解析
function setQuery(params, isEncode) {
var url_query = '';
if (params && isObject(params) && !isEmptyObject(params)) {
var arr = [];
each(params, function (value, item) {
// 防止传统二维码的para.q这种异常query。另外异常的para.scene 不好判断,直接去掉。建议不要使用这个容易异意的参数
if (!(item === 'q' && isString(value) && value.indexOf('http') === 0)) {
if (isEncode) {
arr.push(item + '=' + value);
} else {
arr.push(item + '=' + _decodeURIComponent(value));
}
}
});
return arr.join('&');
} else {
return url_query;
}
}
function getCurrentPage() {
var obj = {};
try {
var pages = isFunction(sa.system_api.getCurrentPages) ? sa.system_api.getCurrentPages() : getCurrentPages();
obj = pages[pages.length - 1];
} catch (e) {
sa.log('getCurrentPage:' + e);
}
return obj;
}
function getCurrentPath() {
var url = '未取到';
try {
var currentPage = getCurrentPage();
url = currentPage ? currentPage.route : url;
} catch (e) {
sa.log('getCurrentPath:' + e);
}
return url;
}
/**
* 判断是否为预置的 ID key,可以通过 ids 传入 id key 的列表,自定义预置的 key 值
* @param {string} name
* @param {array} ids
* @returns {boolean}
*/
function isPresetIdKeys(name, ids) {
// 预置 ID key 列表
var keyList = ['$identity_anonymous_id'];
if (isArray(ids)) {
keyList = keyList.concat(ids);
}
for (var item of keyList) {
if (item === name) {
return true;
}
}
return false;
}
/**
* 判断是否为安全整数类型
*/
var isSafeInteger =
Number.isSafeInteger ||
function (value) {
return isInteger(value) && Math.abs(value) <= Math.pow(2, 53) - 1;
};
/**
* 判断是否为整数类型
*/
var isInteger =
Number.isInteger ||
function (value) {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
};
var check = {
// 检查关键字
checkKeyword: function (para) {
var reg = /^((?!^distinct_id$|^original_id$|^device_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i;
return reg.test(para);
},
// 检查 id 字符串长度
checkIdLength: function (str) {
var temp = String(str);
if (temp.length > 255) {
sa.log('id 长度超过 255 个字符!');
return false;
}
return true;
}
};
/**
*
* @param {*} app 表示不同小程序平台
* @returns 返回 ID
*/
function getOpenidNameByAppid(app) {
if (app == '' || !isString(app)) {
sa.log('error: 参数必须是有效值');
return false;
}
var appid = getAppId();
var _identity = '$identity_';
var _openid = '_openid';
var name = _identity + app + _openid;
if (appid) {
name = _identity + app + '_' + appid + _openid;
}
return name;
}
function validId(id) {
if ((!isString(id) && !isNumber(id)) || id === '') {
sa.log('输入 ID 类型错误');
return false;
}
if (isNumber(id)) {
id = String(id);
if (!/^\d+$/.test(id)) {
sa.log('输入 ID 类型错误');
return false;
}
}
if (!check.checkIdLength(id)) {
return false;
}
return id;
}
/**
* 判断是否为新的 login id
* @param {*} name
* @param {*} id
* @returns
*/
function isNewLoginId(name, id) {
// 当当前 ID 的 name 与上一个登录 ID 的 name 相同,且当前 ID 值与上一个 ID 的值相同时,则认为是同一个 ID,否则是一个新的 ID
// return !(name === store._state.history_login_id.name && store._state.history_login_id.value === id);
// 判断当前 ID 的 name 是否和上一个 ID 的 name 值相同,若不相同,则继续判断 id 值
if (name === sa.store._state.history_login_id.name) {
if (sa.store._state.history_login_id.value === id) {
return false;
}
}
return true;
}
/**
* 判断是否和匿名 id 相同
* @param {*} id
*/
function isSameAndAnonymousID(id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (firstId) {
return id === firstId;
} else {
return id === distinctId;
}
}
/**
* 字符串转换成大写
* value 必须是字符串
*/
function setUpperCase(value) {
if (isString(value)) {
return value.toLocaleUpperCase();
}
return value;
}
// 获取是否首日访问属性
function getIsFirstDay() {
if (typeof sa.store._state === 'object' && isNumber(sa.store._state.first_visit_day_time) && sa.store._state.first_visit_day_time > new Date().getTime()) {
return true;
} else {
return false;
}
}
function getPresetProperties() {
if (sa.properties && sa.properties.$lib) {
var builtinProps = {};
each(sa.properties, function (value, item) {
if (item.indexOf('$') === 0) {
builtinProps[item] = value;
}
});
var propertyObj = {
$url_path: getCurrentPath(),
$is_first_day: getIsFirstDay(),
$is_first_time: meta.is_first_launch
};
var obj = extend(builtinProps, propertyObj, sa.properties, sa.store.getProps());
delete obj.$lib;
return obj;
} else {
return {};
}
}
/**
* 拼接 URL
* @param {URL path} path
* @param {URL query} query
* @returns
*/
function joinUrl(path, query) {
if (!path) {
return false;
}
if (path === '未取到') {
return '未取到';
}
if (!query) {
return path;
} else {
return path + '?' + query;
}
}
// 统一path的格式
function getPath(path) {
if (isString(path)) {
path = path.replace(/^\//, '');
} else {
path = '取值异常';
}
return path;
}
/**
* 获取页面
* @param {app 生命周期参数} para
* @returns
*/
function getAppProps(para) {
var prop = {};
if (para && para.path) {
prop.$url_path = getPath(para.path);
prop.$url_query = setQuery(para.query);
prop.$url = joinUrl(prop.$url_path, prop.$url_query);
}
return prop;
}
/**
*
* @returns
*/
function getPageProps() {
var pages = getCurrentPage();
var path = getCurrentPath();
var query = pages.sensors_mp_url_query || '';
var url = joinUrl(path, query);
return {
$url_path: path,
$url: url,
$url_query: query
};
}
/*
* @Date: 2022-07-05 12:07:14
* @File:
*/
/**
* De-obfuscate an obfuscated string with the method above.
*/
function rot13defs(str) {
var code_len = 13,
n = 126;
str = String(str);
return rot13obfs(str, n - code_len);
}
/**
* Obfuscate a plaintext string with a simple rotation algorithm similar to
* the rot13 cipher.
*/
function rot13obfs(str, code_len) {
str = String(str);
code_len = typeof code_len === 'number' ? code_len : 13;
var n = 126;
var chars = str.split('');
for (var i = 0, len = chars.length; i < len; i++) {
var c = chars[i].charCodeAt(0);
if (c < n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + code_len) % n);
}
}
return chars.join('');
}
var decodeURIComponent$1 = _decodeURIComponent;
function formatSystem(system) {
var _system = system.toLowerCase();
if (_system === 'ios') {
return 'iOS';
} else if (_system === 'android') {
return 'Android';
} else {
return system;
}
}
/**
* 返回 rand 方法
* @param {number} 10^19 必传参数
* @return {number}
*/
var getRandomBasic = (function () {
var today = new Date();
var seed = today.getTime();
function rnd() {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280.0;
}
return function rand(number) {
return Math.ceil(rnd() * number);
};
})();
/**
* 生成一个随机数
* @return {number}
*/
function getRandom() {
if (typeof Uint32Array === 'function') {
var cry = '';
if (typeof crypto !== 'undefined') {
cry = crypto;
} else if (typeof msCrypto !== 'undefined') {
cry = msCrypto;
}
if (isObject(cry) && cry.getRandomValues) {
var typedArray = new Uint32Array(1);
var randomNumber = cry.getRandomValues(typedArray)[0];
var integerLimit = Math.pow(2, 32);
return randomNumber / integerLimit;
}
}
return getRandomBasic(10000000000000000000) / 10000000000000000000;
}
function getUUID() {
return (
'' +
Date.now() +
'-' +
Math.floor(1e7 * getRandom()) +
'-' +
getRandom().toString(16).replace('.', '') +
'-' +
String(getRandom() * 31242)
.replace('.', '')
.slice(0, 8)
);
}
const _ = {
getUUID,
formatSystem,
indexOf,
slice,
forEach,
bind,
_hasOwnProperty,
_toString,
isUndefined,
isString,
isDate,
isBoolean,
isNumber,
isJSONString,
isObject,
isPlainObject,
isArray,
isFuction,
isArguments,
toString,
unique,
include,
values,
toArray,
each,
formatDate,
searchObjDate,
utf8Encode,
decodeURIComponent: decodeURIComponent$1,
encodeDates,
base64Encode,
trim,
isFunction,
extend,
extend2Lev,
isEmptyObject,
searchObjString,
formatString,
setLatestChannel,
getObjFromQuery,
getMixedQuery,
detectOptionQuery,
setUtm,
getCustomUtmFromQuery,
existLatestUtm,
setQuery,
getCurrentPage,
getCurrentPath,
rot13defs,
rot13obfs,
isSafeInteger,
isInteger,
isPresetIdKeys,
deepCopy,
check,
getOpenidNameByAppid,
validId,
isNewLoginId,
isSameAndAnonymousID,
setUpperCase,
getIsFirstDay,
getPageProps,
getAppProps,
getPath,
joinUrl,
getPresetProperties
};
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function stripProperties(p) {
if (!isObject(p)) {
return p;
}
each(p, function (v, k) {
// 如果是数组,把值自动转换成string
if (isArray(v)) {
var temp = [];
each(v, function (arrv) {
if (isString(arrv)) {
temp.push(arrv);
} else if (isUndefined(arrv)) {
temp.push('null');
} else {
try {
temp.push(JSON.stringify(arrv));
} catch (error) {
sa.log('您的数据 - ' + k + ':' + v + ' - 的数组里的值有错误,已经将其删除');
}
}
});
p[k] = temp;
}
//如果是多层结构对象,直接序列化为字符串
if (isObject(v)) {
try {
p[k] = JSON.stringify(v);
} catch (error) {
delete p[k];
sa.log('您的数据 - ' + k + ':' + v + ' - 的数据值有错误,已经将其删除');
}
} else if (!(isString(v) || isNumber(v) || isDate(v) || isBoolean(v) || isArray(v))) {
// 只能是字符串,数字,日期,布尔,数组
sa.log('您的数据 - ', v, '-格式不满足要求,我们已经将其删除');
delete p[k];
}
});
return p;
}
// 处理动态公共属性
function parseSuperProperties(obj) {
if (isObject(obj)) {
each(obj, function (value, item) {
if (isFunction(value)) {
try {
obj[item] = value();
if (isFunction(obj[item])) {
sa.log('您的属性 - ' + item + ' 格式不满足要求,我们已经将其删除');
delete obj[item];
}
} catch (e) {
delete obj[item];
sa.log('您的属性 - ' + item + ' 抛出了异常,我们已经将其删除');
}
}
});
}
}
/*
* @Date: 2022-10-13 18:04:01
* @File: 批量发送数据发送模块
*/
function batchRequest(option) {
if (isArray(option.data) && option.data.length > 0) {
var now = Date.now(),
timeout = sa.para.datasend_timeout;
option.data.forEach(function (v) {
v._flush_time = now;
});
option.data = JSON.stringify(option.data);
let params = {
url: sa.para.server_url,
method: 'POST',
dataType: 'text',
data: 'data_list=' + encodeURIComponent(base64Encode(option.data)),
timeout: timeout,
success: function () {
option.success(option.len);
},
fail: function () {
option.fail();
}
};
if (REQUEST.header) {
params.header = REQUEST.header;
}
sa.system_api.request(params);
} else {
option.success(option.len);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-10-12 17:36:49
* @File: 单条发送
*/
function onceSend(data) {
data._flush_time = Date.now();
var url = '';
var str_t = JSON.stringify(data);
if (sa.para.server_url.indexOf('?') !== -1) {
url = sa.para.server_url + '&data=' + encodeURIComponent(base64Encode(str_t));
} else {
url = sa.para.server_url + '?data=' + encodeURIComponent(base64Encode(str_t));
}
var timeout = sa.para.datasend_timeout;
sa.system_api.request({
url: url,
dataType: 'text',
method: 'GET',
timeout: timeout
});
}
/*
* @Date: 2022-11-01 21:18:52
* @File: 批量发送 & 单条发送 模块
*/
var kit = {
batchRequest: batchRequest,
onceSend: onceSend
};
/**
* 批量发送
*/
sa.batch_state = {
mem: [],
changed: false,
sended: true,
is_first_batch_write: true,
sync_storage: false, // 在初始化时将 storage 存的数据同步到当前暂存队列中的操作是否完成
failTime: 0, // 发送数据失败次数
getLength: function () {
return this.mem.length;
},
add: function (data) {
this.mem.push(data);
},
clear: function (len) {
this.mem.splice(0, len);
}
};
function batchSend() {
if (sa.batch_state.sended) {
var data,
len,
mData = sa.batch_state.mem;
if (mData.length >= 100) {
data = mData.slice(0, 100);
} else {
data = mData;
}
len = data.length;
if (len > 0) {
sa.batch_state.sended = false;
kit.batchRequest({
data: data,
len: len,
success: batchRemove,
fail: sendFail
});
}
}
}
function sendFail() {
sa.batch_state.sended = true;
sa.batch_state.failTime++;
}
function batchRemove(len) {
sa.batch_state.clear(len);
sa.batch_state.sended = true;
sa.batch_state.changed = true;
batchWrite();
sa.batch_state.failTime = 0;
}
function batchWrite() {
if (sa.batch_state.changed) {
// 如果是首次写入数据,等待1s后,优先发送,优化那些来了就跑的人
if (sa.batch_state.is_first_batch_write) {
sa.batch_state.is_first_batch_write = false;
setTimeout(function () {
batchSend();
}, 1000);
}
if (sa.batch_state.syncStorage) {
sa.system_api.setStorageSync('sensors_prepare_data', sa.batch_state.mem);
sa.batch_state.changed = false;
}
}
}
sa.batchWrite = batchWrite;
function batchInterval() {
// 每隔1秒,写入数据
function loopWrite() {
setTimeout(function () {
batchWrite();
loopWrite();
}, 1000);
}
// 默认每隔6秒,发送数据
function loopSend() {
setTimeout(function () {
batchSend();
loopSend();
}, sa.para.batch_send.send_timeout * Math.pow(2, sa.batch_state.failTime));
}
loopWrite();
loopSend();
}
sa.prepareData = function (p) {
var data = {
distinct_id: sa.store.getDistinctId(),
lib: {
$lib: sa.lib.name,
$lib_method: sa.lib.method,
$lib_version: String(sa.lib.version)
},
properties: {}
};
//兼容是否有 ID3 的小程序
if (isObject(sa.store._state.identities)) {
data.identities = extend({}, sa.store.getIdentities());
}
// unbind 额外属性修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
data.identities = _.deepCopy(p.unbind_value);
delete p.unbind_value;
}
extend(data, sa.store.getUnionId(), p);
// 合并properties里的属性
if (isObject(p.properties) && !isEmptyObject(p.properties)) {
extend(data.properties, p.properties);
}
// unbind 额外id修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
if (data.login_id) {
delete data.login_id;
}
if (data.anonymous_id) {
delete data.anonymous_id;
}
}
// profile时不传公用属性
if (!p.type || p.type.slice(0, 7) !== 'profile') {
data._track_id = Number(String(getRandom()).slice(2, 5) + String(getRandom()).slice(2, 4) + String(Date.now()).slice(-4));
// 传入的属性 > 当前页面的属性 > session的属性 > cookie的属性 > 预定义属性
data.properties = extend({}, sa.properties, sa.store.getProps(), sa.currentProps, data.properties);
// 当上报的是事件的数据设置 $is_first_day 属性,对于上报用户属性相关的事件均不上报 $is_first_day 属性
if (p.type === 'track') {
data.properties.$is_first_day = getIsFirstDay();
}
}
if (data.properties.$time && isDate(data.properties.$time)) {
data.time = data.properties.$time * 1;
delete data.properties.$time;
} else {
data.time = new Date() * 1;
}
sa.ee.data.emit('beforeBuildCheck', data);
parseSuperProperties(data.properties);
searchObjDate(data);
stripProperties(data.properties);
searchObjString(data);
sa.ee.data.emit('finalAdjustData', data);
if (!sa.para.server_url) {
return false;
}
sa.log(data);
sa.send(data);
};
sa.send = function (t) {
// t._nocache = (String(getRandom()) + String(getRandom()) + String(getRandom())).slice(2, 15);
if (sa.storageName === 'sensorsdata2015_binance') {
if (sa.para.data_report_type === 'native') {
reportEvent(t);
return false;
}
}
if (sa.para.batch_send) {
if (sa.batch_state.getLength() >= 500) {
sa.log('数据量存储过大,有异常');
sa.batch_state.mem.shift();
}
sa.batch_state.add(t);
sa.batch_state.changed = true;
if (sa.batch_state.getLength() >= sa.para.batch_send.max_length) {
batchSend();
}
} else {
kit.onceSend(t);
}
};
function reportEvent(data) {
var event_name_prefix = 'sensors_';
var event_name = '';
data._flush_time = Date.now();
if (data.event) {
event_name = event_name_prefix + data.event;
} else {
event_name = event_name_prefix + data.type;
}
data.dataSource = 'sensors';
sa.log('report_event, name: ', event_name, '-- key: ', data);
__mp_private_api__.reportEvent(event_name, data);
}
// request 直接调用 sa.request
sa.log = function () {
if (sa.para.show_log) {
if (typeof console === 'object' && console.log) {
try {
var arg = Array.prototype.slice.call(arguments);
return console.log.apply(console, arg);
} catch (e) {
console.log(arguments[0]);
}
}
}
};
sa.track = function (e, p, c) {
sa.prepareData(
{
type: 'track',
event: e,
properties: p
},
c
);
};
sa.setProfile = function (p) {
sa.prepareData({
type: 'profile_set',
properties: p
});
};
sa.setOnceProfile = function (p, c) {
sa.prepareData(
{
type: 'profile_set_once',
properties: p
},
c
);
};
sa.login = function (id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (id !== distinctId) {
if (firstId) {
sa.trackSignup(id, '$SignUp');
} else {
sa.store.set('first_id', distinctId);
sa.trackSignup(id, '$SignUp');
}
}
};
sa.logout = function (isChangeId) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', '');
if (isChangeId === true) {
sa.store.set('distinct_id', getUUID());
} else {
sa.store.set('distinct_id', firstId);
}
} else {
sa.log('没有first_id,logout失败');
}
};
sa.identify = function (id) {
id = _.validId(id);
if (id) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', id);
} else {
sa.store.set('distinct_id', id);
}
}
};
/**
*
* @param {object} idObj 分别为 id: id 值、event_name: 事件名、id_name: 自定义 ID 的 name
* @param {*} e 事件类型
* @param {*} p 数据
* 原传参方式通过 4 个参数来实现,但使用过程中并未传入 p 和 c 参数,故不做处理
* 兼容原有 ID 处理逻辑,判断第一个参数是否为一个对象,是对象则为新 3.0 的接口,需要按 3.0 的传参逻辑进行参数获取
* 在现逻辑中为了不修改老 3.0 中调用 trackSignup 逻辑,若登录 ID key 为默认的 $identity_login_id 则不传 idName 参数
*/
sa.trackSignup = function (idObj, e, p) {
var currentId, eventName, idName, distinctId, originalId;
if (isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
sa.store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
originalId = sa.store.getFirstId() || sa.store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
};
sa.registerApp = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.currentProps = extend(sa.currentProps, obj);
}
};
sa.clearAppRegister = function (arr) {
if (isArray(arr)) {
each(sa.currentProps, function (value, key) {
if (include(arr, key)) {
delete sa.currentProps[key];
}
});
}
};
sa.register = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.store.setProps(obj);
}
};
sa.clearAllRegister = function () {
sa.store.setProps({}, true);
};
sa.use = function (plugin) {
const args = toArray(arguments, 1);
args.unshift(this);
if (isObject(plugin) && isFunction(plugin.init)) {
plugin.init.apply(plugin, args);
}
return plugin;
};
// sa 上挂载 use & usePlugin 保持小程序插件使用 API 的统一
sa.usePlugin = sa.use;
sa.getServerUrl = function () {
return sa.para.server_url;
};
sa.registerPropertyPlugin = function (arg) {
if (!isFunction(arg.properties)) {
sa.log('registerPropertyPlugin arguments error, properties must be function');
return;
}
if (arg.isMatchedWithFilter && !isFunction(arg.isMatchedWithFilter)) {
sa.log('registerPropertyPlugin arguments error, isMatchedWithFilter must be function');
return;
}
sa.ee.data.on('finalAdjustData', function (data) {
try {
if (isFunction(arg.isMatchedWithFilter)) {
arg.isMatchedWithFilter(data) && arg.properties(data);
} else {
arg.properties(data);
}
} catch (e) {
sa.log('execute registerPropertyPlugin callback error:' + e);
}
});
};
/*
* @Date: 2022-11-01 19:03:46
* @File: 用户生态系统 通用版本
*/
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var store = {
inited: true,
// 防止重复请求
storageInfo: null,
store_queue: [],
getStorage: function () {
if (this.storageInfo) {
return this.storageInfo;
} else {
this.storageInfo = sa.system_api.getStorageSync(sa.storageName) || '';
return this.storageInfo;
}
},
_state: {},
getUUID: function () {
return getUUID();
},
toState: function (ds) {
var state = null;
var _this = this;
function isStateDistinctId() {
if (state.distinct_id) {
_this._state = state;
} else {
_this.set('distinct_id', getUUID());
}
}
if (isJSONString(ds)) {
state = JSON.parse(ds);
isStateDistinctId();
} else if (isObject(ds)) {
state = ds;
isStateDistinctId();
} else {
this.set('distinct_id', getUUID());
}
// 在初始化同步 storage ID 属性到内存中时,将对应的 identities 对象进行处理
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this._state._distinct_id || this._state.distinct_id;
var history_login_id = this._state.history_login_id ? this._state.history_login_id : {};
var old_login_id_name = history_login_id.name;
// 解密 iddentities
if (this._state.identities && isString(this._state.identities)) {
var identities = JSON.parse(rot13defs(this._state.identities));
this._state.identities = identities;
}
// 初始化处理匿名 ID 及 初始化 identities
if (!this._state.identities || !isObject(this._state.identities) || isEmptyObject(this._state.identities)) {
this._state.identities = {};
this._state.identities[IDENTITIES.identity_id] = getUUID();
}
function delIdentitiesProp(value) {
for (var identitiesProp in store._state.identities) {
if (hasOwnProperty$1.call(store._state.identities, identitiesProp)) {
if (identitiesProp !== IDENTITIES.identity_id && identitiesProp !== value) {
delete store._state.identities[identitiesProp];
}
}
}
}
// 以下处理登录 ID 的相关逻辑
if (first_id) {
// 处理存在老的 3.0 登录 ID 逻辑,及不存在登录 ID 的情况
if (old_login_id_name && hasOwnProperty$1.call(this._state.identities, old_login_id_name)) {
if (this._state.identities[old_login_id_name] !== distinct_id) {
this._state.identities[old_login_id_name] = distinct_id;
delIdentitiesProp(old_login_id_name);
this._state.history_login_id.value = distinct_id;
}
} else {
this._state.identities[IDENTITY_KEY.LOGIN] = distinct_id;
delIdentitiesProp(IDENTITY_KEY.LOGIN);
this._state.history_login_id = {
name: IDENTITY_KEY.LOGIN,
value: distinct_id
};
}
} else {
this._state.history_login_id = {
name: '',
value: ''
};
}
this.save();
},
getFirstId: function () {
return this._state._first_id || this._state.first_id;
},
/**
* 获取当前 distinct_id,如果有 IDM3 状态下的登录的 distinctId 则返回此 ID 值,若没有则返回当前的匿名 ID
* @returns distinct_id
*/
getDistinctId: function () {
var loginDistinctId = this.getLoginDistinctId();
if (loginDistinctId) {
return loginDistinctId;
} else {
return this._state._distinct_id || this._state.distinct_id;
}
},
getUnionId: function () {
var obj = {};
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this.getDistinctId();
if (first_id && distinct_id) {
obj['login_id'] = distinct_id;
obj['anonymous_id'] = first_id;
} else {
obj['anonymous_id'] = distinct_id;
}
return obj;
},
// 区别于 identities,这里会加入 $identities_anonymous_id
getIdentities: function () {
var iden = JSON.parse(JSON.stringify(this._state.identities));
iden.$identity_anonymous_id = this.getAnonymousId();
return iden;
},
getAnonymousId: function () {
return this.getUnionId().anonymous_id;
},
/**
* 新增 getHistoryLoginId 接口,用以获取到老的登录用户 ID 标识
*/
getHistoryLoginId: function () {
if (isObject(this._state.history_login_id)) {
return this._state.history_login_id;
} else {
return null;
}
},
/**
* 获取当前的登录情况下的 distinctId
* 获取当前 distinct_id,如果为 IDM3 登录 ID,则值为登录 ID 的 name + value 的格式
* 如果为非登录状态,则直接返回 null,标识无值
*/
getLoginDistinctId: function () {
var historyLoginId = this.getHistoryLoginId();
// 存在登录 ID 对象,且登录 ID 值为真(排除登录后登出,保存 history_login_id 对象,但清空属性值的情况);否则为未登录状态,直接取当前的 distinct_id
if (isObject(historyLoginId) && historyLoginId.value) {
if (historyLoginId.name !== IDENTITY_KEY.LOGIN) {
return historyLoginId.name + '+' + historyLoginId.value;
} else {
return historyLoginId.value;
}
} else {
return null;
}
},
getProps: function () {
return this._state.props || {};
},
setProps: function (newp, isCover) {
var props = this._state.props || {};
if (!isCover) {
extend(props, newp);
this.set('props', props);
} else {
this.set('props', newp);
}
},
set: function (name, value) {
var obj = {};
if (typeof name === 'string') {
obj[name] = value;
} else if (typeof name === 'object') {
obj = name;
}
this._state = this._state || {};
for (var i in obj) {
this._state[i] = obj[i];
// 如果set('first_id') 或者 set('distinct_id'),删除对应的临时属性
if (i === 'first_id') {
delete this._state._first_id;
} else if (i === 'distinct_id') {
delete this._state._distinct_id;
// deprecated 不推荐使用,即将废弃
sa.events.emit('changeDistinctId');
}
}
this.save();
},
identitiesSet: function (params) {
var identities = {};
switch (params.type) {
case 'login':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
identities[params.id_name] = params.id;
break;
case 'logout':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
break;
// donoting
}
this.set('identities', identities);
},
change: function (name, value) {
this._state['_' + name] = value;
},
encryptStorage: function () {
var copyState = this.getStorage();
var flag = 'data:enc;';
if (isObject(copyState)) {
copyState = flag + rot13obfs(JSON.stringify(copyState));
} else if (isString(copyState)) {
if (copyState.indexOf(flag) === -1) {
copyState = flag + rot13obfs(copyState);
}
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
save: function () {
// 深拷贝避免修改原对象
var copyState = deepCopy(this._state);
// 对 identitie 进行加密
var identities = rot13obfs(JSON.stringify(copyState.identities));
copyState.identities = identities;
// 删除临时属性避免写入微信 storage
delete copyState._first_id;
delete copyState._distinct_id;
// 是否开启本地存储加密
if (sa.para.encrypt_storage) {
var flag = 'data:enc;';
copyState = flag + rot13obfs(JSON.stringify(copyState));
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
init: function () {
var info = this.getStorage();
var flag = 'data:enc;';
var uuid = getUUID();
if (info) {
if (isString(info)) {
//判断是否有加密的字段 有就解密
if (info.indexOf(flag) !== -1) {
info = info.substring(flag.length);
info = JSON.parse(rot13defs(info));
}
}
this.toState(info);
} else {
meta.is_first_launch = true;
var time = new Date();
var visit_time = time.getTime();
time.setHours(23);
time.setMinutes(59);
time.setSeconds(60);
this.set({
distinct_id: uuid,
first_visit_time: visit_time,
first_visit_day_time: time.getTime(),
identities: {
[IDENTITIES.identity_id]: uuid
},
history_login_id: {
name: '',
value: ''
}
});
sa.setOnceProfile({ $first_visit_time: time });
}
this.checkStoreInit && this.checkStoreInit();
}
};
sa.store = store;
/*
* @Date: 2022-12-05 16:21:58
* @File: 通用 ID2 、ID3 相关 API
*/
function trackSignup(idObj, e, p) {
var currentId, eventName, idName, distinctId;
if (_.isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
var originalId = store.getFirstId() || store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
}
function bindWithoutCheck(name, value) {
var identities = store._state.identities;
identities[name] = value;
store.save();
sa.prepareData({
type: 'track_id_bind',
event: '$BindID'
});
}
function bind$1(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 获取当前的 login_id key
var historyLoginId = store.getHistoryLoginId();
var currentLoginIdName = historyLoginId ? historyLoginId.name : '';
var presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName];
if (_.isArray(IDENTITIES.bind_preset_id)) {
presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName].concat(IDENTITIES.bind_preset_id);
}
// 通过 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, presetIdKeys)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
bindWithoutCheck(name, value);
}
function unbindWithoutCheck(name, value) {
if (hasOwnProperty.call(store._state.identities, name) && value === store._state.identities[name]) {
if (IDENTITIES.unbind_without_check && IDENTITIES.unbind_without_check.indexOf(name) < 0) {
delete store._state.identities[name];
}
store.save();
}
var distinctId = store.getDistinctId();
var firstId = store.getFirstId();
var unbindDistinctId = name + '+' + value;
if (distinctId === unbindDistinctId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
store.set('history_login_id', {
name: '',
value: ''
});
}
var para = {};
para[name] = value;
sa.prepareData({
type: 'track_id_unbind',
event: '$UnbindID',
unbind_value: para
});
}
function unbind(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 通过 isPresetIdKeys 判断是否是预置的 id key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, [IDENTITY_KEY.LOGIN])) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
unbindWithoutCheck(name, value);
}
/**
* 通过自定义的登录 ID 的 key(name)值进行登录
* @param {string} name
* @param {string} id
* @returns
*/
function loginWithKey(name, id) {
sa.log('loginWithKey is deprecated !!!');
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 这个单独判断 name 的 length 是为了符合测试提出的多端检查统一,保证判断 loginWithKey 的 key 值时长度超过 100 打印日志,但继续做后续 ID 绑定
// 同时 checkKeyword 未做修改,是为了保持原有统一检查逻辑不变,以免影响到其他检查
// 在 name 的 length 的值小于 100 的情况下,若其他检查不符,会做 return 处理
var info = '';
if (!_.check.checkKeyword(name) && name.length > 100) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
} else if (!_.check.checkKeyword(name)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (_.isPresetIdKeys(name, IDENTITIES.login_preset_id)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
id = _.validId(id);
// 如果 ID 不合法,直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
// 通过 isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(name, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
store._state.identities[name] = id;
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: name,
value: id
});
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp',
id_name: name
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将 login 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: name
});
}
}
function login(id) {
id = _.validId(id);
// 如果 ID 不合法直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
var idName = IDENTITY_KEY.LOGIN;
// 通过 _.isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(idName, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
if (store._state.identities) {
store._state.identities[idName] = id;
}
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: idName,
value: id
});
// 处理 trackSignup 逻辑,其中 newDistinctId 作为 2.0 的 distinct_id 通过 trackSignup 进行保存
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp'
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将登录 id 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: idName
});
}
}
function logout() {
var firstId = store.getFirstId();
// IDM3 ID identities 先做更新,然后更新外层的 ID
store.identitiesSet({ type: 'logout' });
// 删除 history_login_id 的登录 ID
store.set('history_login_id', {
name: '',
value: ''
});
if (firstId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
} else {
sa.log('没有first_id,logout失败');
}
}
// export function bindOpenid(openid) {
// openid = _.validId(openid);
// if (!openid) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// bind(name, openid);
// }
// export function unbindOpenid(val) {
// var id = _.validId(val);
// if (!id) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// // 不管本地有没有都要 unbind
// unbind(name, val);
// }
function getIdentities() {
if (_.isEmptyObject(store._state)) {
return null;
} else {
return store.getIdentities() || null;
}
}
// 重置 id3 匿名 id,只有在未登录情况下可以使用!!!
function resetAnonymousIdentity(id) {
// 登录则 return
var firstId = store.getFirstId();
if (firstId) {
sa.log('resetAnonymousIdentity must be used in a logout state !');
return false;
}
if (typeof id === 'number') {
id = String(id);
}
// id 有值则替换,没值则重置
if (typeof id === 'undefined') {
var uuid = store.getUUID();
store._state.identities[IDENTITIES.identity_id] = uuid;
store.set('distinct_id', uuid);
} else if (_.validId(id)) {
store._state.identities[IDENTITIES.identity_id] = id;
store.set('distinct_id', id);
}
}
function getPresetProperties$1() {
return _.getPresetProperties();
}
function getAnonymousID() {
if (_.isEmptyObject(sa.store._state)) {
sa.log('请先初始化SDK');
} else {
return sa.store._state._first_id || sa.store._state.first_id || sa.store._state._distinct_id || sa.store._state.distinct_id;
}
}
var functions = /*#__PURE__*/Object.freeze({
__proto__: null,
trackSignup: trackSignup,
bindWithoutCheck: bindWithoutCheck,
bind: bind$1,
unbindWithoutCheck: unbindWithoutCheck,
unbind: unbind,
loginWithKey: loginWithKey,
login: login,
logout: logout,
getIdentities: getIdentities,
resetAnonymousIdentity: resetAnonymousIdentity,
getPresetProperties: getPresetProperties$1,
getAnonymousID: getAnonymousID
});
/*
* @Date: 2022-12-13 18:50:04
* @File:
*/
//对外 API 设置
for (var f in functions) {
sa[f] = functions[f];
}
function isValidListener(listener) {
if (typeof listener === 'function') {
return true;
} else if (listener && typeof listener === 'object') {
return isValidListener(listener.listener);
} else {
return false;
}
}
/**
* @class EventEmitter
* @category Event
* @example
* var e = new EventEmitter()
* e.on('HelloEvent',function(data){
* console.log('Hello Event happens',data);
* })
*
* e.emit('HelloEvent',123);
* // Hello Event happens , 123
*/
class EventEmitterBase {
constructor() {
this._events = {};
}
/**
* 添加事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
on(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].push(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prepend(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].unshift(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头,回调只执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prependOnce(eventName, listener) {
return this.prepend(eventName, {
listener: listener,
once: true
});
}
/**
* 添加事件,该事件只能被执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
once(eventName, listener) {
return this.on(eventName, {
listener: listener,
once: true
});
}
/**
* 删除事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
off(eventName, listener) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
if (typeof listener === 'number') {
listeners.splice(listener, 1);
} else if (typeof listener === 'function') {
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i] && listeners[i].listener === listener) {
listeners.splice(i, 1);
}
}
}
return this;
}
/**
* 触发事件
* @param {String} eventName 事件名称
* @param {Array} args 传入监听器函数的参数,使用数组形式传入
* @return {Object} 可链式调用
*/
emit(eventName, args) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
if (listener) {
listener.listener.call(this, args || {});
if (listener.once) {
this.off(eventName, i);
}
}
}
return this;
}
/**
* 删除某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
removeAllListeners(eventName) {
if (eventName && this._events[eventName]) {
this._events[eventName] = [];
} else {
this._events = {};
}
}
/**
* 返回某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
listeners(eventName) {
if (eventName && typeof eventName === 'string') {
return this._events[eventName];
} else {
return this._events;
}
}
}
/**
* ex 扩展
*/
class EventEmitterEx extends EventEmitterBase {
constructor() {
super();
this.cacheEvents = [];
this.maxLen = 20;
}
replay(eventName, listener) {
this.on(eventName, listener);
if (this.cacheEvents.length > 0) {
this.cacheEvents.forEach(function (val) {
if (val.type === eventName) {
listener.call(null, val.data);
}
});
}
}
emit(eventName, args) {
super.emit.apply(this, arguments);
this.cacheEvents.push({ type: eventName, data: args });
this.cacheEvents.length > this.maxLen ? this.cacheEvents.shift() : null;
}
}
/*
* @Date: 2022-07-07 14:20:38
* @File:
*/
var ee = {};
ee.sdk = new EventEmitterEx();
ee.data = new EventEmitterEx();
/*
* @Date: 2022-06-08 18:59:23
* @File: 老版的事件订阅发布
*/
var eventEmitter = function () {
this.sub = [];
};
eventEmitter.prototype = {
add: function (item) {
this.sub.push(item);
},
emit: function (event, data) {
this.sub.forEach(function (temp) {
temp.on(event, data);
});
}
};
var eventSub = function (handle) {
sa.events.add(this);
this._events = [];
this.handle = handle;
this.ready = false;
};
eventSub.prototype = {
on: function (event, data) {
if (this.ready) {
if (isFunction(this.handle)) {
try {
this.handle(event, data);
} catch (error) {
sa.log(error);
}
}
} else {
this._events.push({
event,
data
});
}
},
isReady: function () {
var that = this;
that.ready = true;
that._events.forEach(function (item) {
if (isFunction(that.handle)) {
try {
that.handle(item.event, item.data);
} catch (error) {
sa.log(error);
}
}
});
}
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
//事件发布订阅监听
sa.ee = ee;
//内部全局变量
sa.meta = meta;
sa.kit = kit;
// use 插件存储
sa.modules = {};
//兼容老版的事件发布订阅
sa.eventSub = eventSub;
sa.events = new eventEmitter();
sa.init = function (obj) {
// 是否执行过init,防止重复执行
if (meta.hasExeInit === true) {
return false;
}
if (obj && isObject(obj)) {
sa.setPara(obj);
}
meta.hasExeInit = true;
if (obj && isObject(obj)) {
sa.setPara(obj);
}
// ------------- 全局参数准备完毕
// 可以使用 param
ee.sdk.emit('afterInitPara');
sa.store.init();
sa.system.init();
if (sa.para.batch_send) {
sa.system_api.getStorage('sensors_prepare_data', function (res) {
var queue = [];
if (res && res.data && isArray(res.data)) {
queue = res.data;
sa.batch_state.mem = queue.concat(sa.batch_state.mem);
}
sa.batch_state.syncStorage = true;
});
batchInterval();
}
};
sa.setPara = function (para) {
sa.para = extend2Lev(sa.para, para);
var channel = [];
if (isArray(sa.para.source_channel)) {
var len = sa.para.source_channel.length;
for (var c = 0; c < len; c++) {
if (RESERVE_CHANNEL.indexOf(' ' + sa.para.source_channel[c] + ' ') === -1) {
channel.push(sa.para.source_channel[c]);
}
}
}
sa.para.source_channel = channel;
if (typeof sa.para.send_timeout !== 'number') {
sa.para.send_timeout = 1000;
}
var batch_send_default = {
send_timeout: 6000,
max_length: 6
};
// 如果已经配置为批量发送,且未定义请求撤销时间的情况下,设置请求撤销时间为 10s
if (para && para.datasend_timeout); else if (sa.para.batch_send) {
sa.para.datasend_timeout = 10000;
}
// 如果是true,转换成对象
if (sa.para.batch_send === true) {
sa.para.batch_send = extend({}, batch_send_default);
} else if (isObject(sa.para.batch_send)) {
sa.para.batch_send = extend({}, batch_send_default, sa.para.batch_send);
}
if (!sa.para.server_url) {
sa.log('请使用 setPara() 方法设置 server_url 数据接收地址,详情可查看https://www.sensorsdata.cn/manual/mp_sdk_new.html#112-%E5%BC%95%E5%85%A5%E5%B9%B6%E9%85%8D%E7%BD%AE%E5%8F%82%E6%95%B0');
return;
}
sa.para.preset_properties = isObject(sa.para.preset_properties) ? sa.para.preset_properties : {};
};
sa.checkInit = function () {
if (sa.system.inited === true && sa.store.inited === true) {
sa.inited = true;
if (sa._queue.length > 0) {
each(sa._queue, function (content) {
sa[content[0]].apply(sa, slice.call(content[1]));
});
sa._queue = [];
}
}
};
each(['setProfile', 'setOnceProfile', 'track', 'identify', 'bind', 'unbind', 'login', 'logout', 'registerApp', 'clearAppRegister'], function (method) {
var temp = sa[method];
sa[method] = function () {
if (sa.inited) {
temp.apply(sa, arguments);
} else {
sa._queue.push([method, arguments]);
//sa.log(`[sensorsdata]: 请先调用 sensors.init,再调用 ${method} api`);
}
};
});
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getNetwork() {
return new Promise(function (resolve) {
sa.system_api.getNetworkType({
success(t) {
sa.properties.$network_type = setUpperCase(t['networkType']);
},
fail(e) {
sa.log('获取网络状态信息失败: ', e);
},
complete() {
resolve();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getSystemInfo() {
return new Promise((reslove) => {
sa.system_api.getSystemInfo({
success(res) {
var p = sa.properties;
if (isObject(res)) {
p.$manufacturer = res['brand'];
p.$model = res['model'];
p.$brand = setUpperCase(res['brand']) || '';
p.$screen_width = Number(res['screenWidth']);
p.$screen_height = Number(res['screenHeight']);
p.$os = formatSystem(res['platform']);
p.$os_version = res['system'].indexOf(' ') > -1 ? res['system'].split(' ')[1] : res['system'];
p.$mp_client_app_version = res['version'] || '';
var sdk_version = res['SDKVersion'] || '';
if (sdk_version) {
p.$mp_client_basic_library_version = sdk_version;
}
}
},
fail(e) {
sa.log('获取系统信息失败: ', e);
},
complete() {
reslove();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
var system = {
inited: false,
init: function () {
var timeZoneOffset = new Date().getTimezoneOffset();
if (isNumber(timeZoneOffset)) {
sa.properties.$timezone_offset = timeZoneOffset;
}
var app_id = getAppId() || sa.para.app_id || sa.para.appid;
if (app_id) {
sa.properties.$app_id = app_id;
}
var network = getNetwork();
var sysytemInfo = getSystemInfo();
Promise.all([network, sysytemInfo]).then(function () {
sa.system.inited = true;
sa.checkInit();
});
}
};
function request(para) {
var timeout;
if (para.timeout) {
timeout = para.timeout;
delete para.timeout;
}
var rq = sa.platform_obj.request(para);
setTimeout(function () {
try {
if (isObject(rq) && isFunction(rq.abort)) {
rq.abort();
}
} catch (error) {
sa.log(error);
}
}, timeout);
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getStorage(key, complete) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (e) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (err) {
sa.log('获取 storage 失败!', err);
}
}
function parseRes(res) {
if (res && res.data && isJSONString(res.data)) {
try {
var data = JSON.parse(res.data);
res.data = data;
} catch (err) {
sa.log('parse res.data 失败!', err);
}
}
complete(res);
}
}
function setStorage(item, val) {
var value;
try {
value = JSON.stringify(val);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
sa.log('设置 storage 失败: ', err);
}
}
}
function getStorageSync(key) {
var store = '';
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e) {
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e2) {
sa.log('获取 storage 失败!');
}
}
if (isJSONString(store)) {
store = JSON.parse(store);
}
return store;
}
function setStorageSync(key, value) {
var item;
try {
item = JSON.stringify(value);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
var fn = function () {
sa.platform_obj.setStorageSync(key, item);
};
try {
fn();
} catch (e) {
sa.log('set Storage fail --', e);
try {
fn();
} catch (e2) {
sa.log('set Storage fail again --', e2);
}
}
}
/*
* @Date: 2021-10-13 15:29:49
* @File: 内部 API 统一
*/
function getNetworkType() {
return sa.platform_obj.getNetworkType.apply(null, arguments);
}
function getSystemInfo$1() {
return sa.platform_obj.getSystemInfo.apply(null, arguments);
}
function getAppId$1() {
var info;
if (sa.platform_obj.getAccountInfoSync) {
info = sa.platform_obj.getAccountInfoSync();
}
if (isObject(info) && isObject(info.miniProgram)) {
return info.miniProgram;
}
}
var compose = {
request: request,
getStorage: getStorage,
setStorage: setStorage,
getStorageSync: getStorageSync,
setStorageSync: setStorageSync,
getAppInfoSync: getAppId$1,
getNetworkType: getNetworkType,
getSystemInfo: getSystemInfo$1
};
const forEach$1 = Array.prototype.forEach,
slice$1 = Array.prototype.slice,
_hasOwnProperty$1 = Object.prototype.hasOwnProperty,
_toString$1 = Object.prototype.toString;
function extend$1(obj) {
each$1(slice$1.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
function isObject$1(obj) {
return obj !== null && typeof obj === 'object';
}
function isFunction$1(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
function isString$1(obj) {
return _toString$1.call(obj) == '[object String]';
}
function each$1(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach$1 && obj.forEach === forEach$1) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty$1.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-03 08:05:52
* @File: SDK 内部 生命周期钩子统一接口
*/
var lifeCycleHook = ['appOnLaunch', 'appOnShow', 'appOnHide', 'pageOnShow', 'pageOnLoad'];
// 内部统一生命周期 API
var miniLifeCycleAPI = {};
lifeCycleHook.forEach(function (key) {
miniLifeCycleAPI[key] = function () {
throw new Error(`需要先定义 '${key}' 才能使用`);
};
});
/**
* 按照不同平台混入内部调用的 API (初始化时调用)
*
* @public
* @param {Object} mixinAPI 需混入的 API
* @returns {void}
*/
function registerLifeCycleHook(mixinAPI) {
Object.assign(miniLifeCycleAPI, mixinAPI);
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:56
* @File:
*/
function getScene(scene_value, sa) {
if (!isObject$1(sa)) {
return false;
}
var scene_prefix = sa.meta.scene_prefix;
// 判断是否存在 scene_prefix 来确定当前小程序是否采集 scene 场景值
if (!scene_prefix || !isString$1(scene_prefix)) {
return false;
}
if (typeof scene_value === 'number' || (typeof scene_value === 'string' && scene_value !== '')) {
scene_value = scene_prefix + String(scene_value);
return scene_value;
} else {
return '未取到值';
}
}
/**
* hook function
*
* @public
* @param {Object} obj 待 hook 对象
* @param {name} method 方法名
* @param {Function} hook hook 方法
* @returns {void}
* */
function hookFunc(obj, method, hook) {
var oldMethod = obj[method];
obj[method] = function (args) {
if (isFunction$1(hook)) {
hook.call(this, args);
}
oldMethod && isFunction$1(oldMethod) && oldMethod.call(this, args);
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: app 重写逻辑
*/
function hookAppFunc(option) {
hookFunc(option, 'onLaunch', miniLifeCycleAPI['appOnLaunch']);
hookFunc(option, 'onShow', miniLifeCycleAPI['appOnShow']);
hookFunc(option, 'onHide', miniLifeCycleAPI['appOnHide']);
}
/**
* hook app
* sa 引入主 SDK
* hookAppFunc 需要监听的生命周期
*/
function proxyApp(hookAppFunc, sa) {
function initAppGlobalName(callback) {
var oldApp = App;
App = function (option) {
try {
callback && callback(option);
option[sa.para.name] = sa;
oldApp.apply(this, arguments);
} catch (error) {
oldApp.apply(this, arguments);
global.sensors.log('App:' + error);
}
};
}
//有部分小程序提供如下 API,可以在app.js 没有生命 onshow,onHide 的情况下能监听到如下生命周期
if (isObject$1(sa) && isFunction$1(sa.platform_obj.onAppShow) && isFunction$1(sa.platform_obj.onAppHide)) {
initAppGlobalName();
sa.platform_obj.onAppShow(function (para) {
if (!sa.para.launched) {
var option = para || (isFunction$1(sa.platform_obj.getLaunchOptionsSync) && sa.platform_obj.getLaunchOptionsSync()) || {};
miniLifeCycleAPI.appOnLaunch(option);
sa.para.launched = true;
}
miniLifeCycleAPI.appOnShow(para);
});
sa.platform_obj.onAppHide(function () {
miniLifeCycleAPI.appOnHide();
});
} else {
initAppGlobalName(hookAppFunc);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:55:28
* @File: app 生命周期数据上报模块
*/
function appOnLaunch(option, prop) {
if (!isObject$1(option)) {
global.sensors.log('appOnLaunch:请传入正确的参数');
return;
}
var obj = {};
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.meta.current_scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
} else {
obj.$scene = '未取到值';
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (global.sensors.meta.is_first_launch) {
obj.$is_first_time = true;
if (!global.sensors._.isEmptyObject(utms.pre1)) {
global.sensors.setOnceProfile(utms.pre1);
}
} else {
obj.$is_first_time = false;
}
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appLaunch) {
global.sensors.track('$MPLaunch', obj);
}
}
function appOnShow(option, prop) {
var obj = {};
global.sensors.meta.mp_show_time = new Date().getTime();
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appShow) {
global.sensors.track('$MPShow', obj);
}
}
function appOnHide(prop) {
var current_time = new Date().getTime();
var obj = {};
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
extend$1(obj, global.sensors._.getPageProps());
var mpShowTime = global.sensors.meta.mp_show_time;
if (mpShowTime && current_time - mpShowTime > 0 && (current_time - mpShowTime) / 3600000 < 24) {
obj.event_duration = (current_time - mpShowTime) / 1000;
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appHide) {
global.sensors.track('$MPHide', obj);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 全埋点 appOnHide, appOnShow, appOnLaunch 通用版本使用
*/
var presetEvents = {
appLaunch: true,
appShow: true,
appHide: true
};
var AutoTrackApp = {
name: 'AutoTrackApp'
};
AutoTrackApp.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global.sensors = sensorsdata;
global.sensors.para.autoTrack = extend$1(presetEvents, para);
//初始化全埋点埋点方法
AutoTrackApp.lifeCycleAPI();
AutoTrackApp.proxyFrameworkInterface();
};
AutoTrackApp.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.appOnLaunch = appOnLaunch;
lifeCycleAPI.appOnShow = appOnShow;
lifeCycleAPI.appOnHide = appOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackApp.proxyFrameworkInterface = function () {
proxyApp(hookAppFunc, global.sensors);
};
/*
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global$1 = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:43
* @File:
*/
/**
* sa 引入主 SDK
*/
function getCurrentPath$1(sa) {
var url = '未取到';
var current_page = getCurrentPage$1(sa);
if (current_page && current_page.route) {
url = current_page.route;
}
return url;
}
/**
* sa 引入主 SDK
*/
function getCurrentPage$1(sa) {
var currentPage = {};
var pages;
if (sa) {
try {
pages = isFunction$1(sa.platform_obj.getCurrentPages) ? sa.platform_obj.getCurrentPages() : getCurrentPages();
currentPage = pages[pages.length - 1];
} catch (e) {
sa.log(e);
}
} else {
console.log('getCurrentPage:请传入 sa 对象');
}
return currentPage;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:35:22
* @File: 全埋点点击事件,数据处理模块
*/
function isClick(type) {
const TYPES = {
tap: 1,
longtap: 1,
longpress: 1
};
return !!TYPES[type];
}
function createClickData(events) {
var prop = {},
event_prop = {};
var current_target = events.currentTarget || {};
var dataset = current_target.dataset || {};
prop['$element_id'] = current_target.id;
prop['$element_type'] = dataset['type'];
prop['$element_content'] = dataset['content'];
prop['$element_name'] = dataset['name'];
if (isObject$1(events.event_prop)) {
event_prop = events.event_prop;
}
prop['$url_path'] = getCurrentPath$1(global$1.sensors);
prop['$url'] = global$1.sensors._.getPageProps().$url;
prop = extend$1(prop, event_prop);
return prop;
}
var ClickTrack = {};
ClickTrack.track = function (events) {
var prop = createClickData(events);
var current_target = events.currentTarget || {};
var target = events.target || {};
var type = events['type'];
var saPara = global$1.sensors.para;
if (isObject$1(saPara.framework) && isObject$1(saPara.framework.taro) && !saPara.framework.taro.createApp) {
if (target.id && current_target.id && target.id !== current_target.id) {
return false;
}
}
if (isObject$1(prop) && type && isClick(type)) {
if (saPara.preset_events && saPara.preset_events.collect_element && saPara.preset_events.collect_element(arguments[0]) === false) {
return false;
}
global$1.sensors.track('$MPClick', prop);
}
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:20:42
* @File: 全埋点点击事件核心逻辑模块
*/
var MP_HOOKS = {
data: 1,
onLoad: 1,
onShow: 1,
onReady: 1,
onPullDownRefresh: 1,
onReachBottom: 1,
onShareAppMessage: 1,
onPageScroll: 1,
onResize: 1,
onTabItemTap: 1,
onHide: 1,
onUnload: 1
};
// 重点注意 clickProxy 不能使用 return false
function clickProxy(option, method) {
var oldFunc = option[method];
option[method] = function () {
// 在重写 oldFunc 之前就已经判断是一个方法类型,此处是做一次重复的校验
var res = oldFunc.apply(this, arguments);
var args = arguments[0];
if (isObject$1(args)) {
ClickTrack.track(args);
}
return res;
};
}
function monitorClick(option) {
var methods = [];
var autoTrack = global$1.sensors.para.autoTrack;
if (autoTrack && autoTrack.mpClick) {
methods = getMethods(option);
tabProxy(option);
var len = methods.length;
for (var i = 0; i < len; i++) {
clickProxy(option, methods[i]);
}
}
}
// 监听重写 tabBar
function tabProxy(option) {
var oldTab = option['onTabItemTap'];
option['onTabItemTap'] = function (item) {
if (oldTab) {
oldTab.apply(this, arguments);
}
var prop = {};
if (item) {
prop['$element_content'] = item.text || '';
}
prop['$element_type'] = 'tabBar';
prop['$url_path'] = item.pagePath ? item.pagePath : global$1.sensors._.getCurrentPath();
global$1.sensors.track('$MPClick', prop);
};
}
// 对 page 所有事件进行清理
function getMethods(option) {
var methods = [];
for (var m in option) {
if (typeof option[m] === 'function' && !MP_HOOKS[m]) {
methods.push(m);
}
}
return methods;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: Page Component 重写逻辑模块
*/
// option是 Page(option) option={onLoad(){},onShow(){}}
function hookPageFunc(option) {
hookFunc(option, 'onShow', miniLifeCycleAPI['pageOnShow']);
hookFunc(option, 'onLoad', miniLifeCycleAPI['pageOnLoad']);
hookFunc(option, 'onUnload', miniLifeCycleAPI['pageOnUnload']);
hookFunc(option, 'onHide', miniLifeCycleAPI['pageOnHide']);
}
/**
* hook Page
*/
function proxyPage(hookPageFunc, monitorClick) {
var oldPage = Page;
Page = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
isFunction$1(hookPageFunc) && hookPageFunc(option);
isFunction$1(monitorClick) && monitorClick(option);
oldPage.apply(this, arguments);
} catch (error) {
oldPage.apply(this, arguments);
console.log('Page:' + error);
}
};
var oldComponent = Component;
Component = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
if (!option.methods) {
option.methods = {};
}
isFunction$1(hookPageFunc) && hookPageFunc(option.methods);
isFunction$1(monitorClick) && monitorClick(option.methods);
oldComponent.apply(this, arguments);
} catch (e) {
oldComponent.apply(this, arguments);
console.log('Component:' + e);
}
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:21:53
* @File:
*/
var pageLeave = function () {
if (global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageLeave) {
var currentPage = {};
var router = '';
try {
currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log(error);
}
if (global$1.sensors.meta.page_show_time >= 0 && router !== '') {
var prop = {};
var page_stay_time = (Date.now() - global$1.sensors.meta.page_show_time) / 1000;
if (isNaN(page_stay_time) || page_stay_time < 0) {
page_stay_time = 0;
}
extend$1(prop, global$1.sensors._.getPageProps());
prop.event_duration = page_stay_time;
// 数据上报前,判断当前页面是否采集
global$1.sensors.track('$MPPageLeave', prop);
global$1.sensors.meta.page_show_time = -1;
}
}
};
function pageOnLoad(option) {
var currentPage = this;
if (global$1.sensors._.isObject(option)) {
try {
currentPage = getCurrentPage$1(global$1.sensors);
} catch (error) {
global$1.sensors.log('pageOnLoad:' + error);
}
currentPage.sensors_mp_url_query = global$1.sensors._.setQuery(option);
currentPage.sensors_mp_encode_url_query = global$1.sensors._.setQuery(option, true);
}
}
function pageOnShow() {
global$1.sensors.meta.page_show_time = Date.now();
var obj = {};
var router = '';
try {
var currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log('pageOnShow:' + error);
}
extend$1(obj, global$1.sensors._.getPageProps());
obj.$referrer = global$1.sensors.meta.sa_referrer;
if (global$1.sensors.para && global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageShow) {
global$1.sensors.track('$MPViewScreen', obj);
}
global$1.sensors.meta.sa_referrer = router;
}
function pageOnUnload() {
pageLeave();
}
function pageOnHide() {
pageLeave();
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 通用全埋点事件入口,如果需要定制化,在对应平台入口进行定制化初始化
*/
var presetEvents$1 = {
pageShow: true,
mpClick: true,
pageLeave: false
};
var AutoTrackPage = {
name: 'AutoTrackPage'
};
AutoTrackPage.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global$1.sensors = sensorsdata;
global$1.sensors.para.autoTrack = extend$1(presetEvents$1, para);
//初始化全埋点埋点方法
AutoTrackPage.lifeCycleAPI();
AutoTrackPage.proxyFrameworkInterface();
};
AutoTrackPage.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.pageOnShow = pageOnShow;
lifeCycleAPI.pageOnLoad = pageOnLoad;
lifeCycleAPI.pageOnUnload = pageOnUnload;
lifeCycleAPI.pageOnHide = pageOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackPage.proxyFrameworkInterface = function () {
proxyPage(hookPageFunc, monitorClick);
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File:平台入口
*/
var presetEvents$2 = {
appLaunch: true,
appShow: true,
appHide: true,
pageShow: true,
mpClick: true
};
var AutoTrack = {};
AutoTrack.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
var autoTrack = extend$1(presetEvents$2, para);
sensorsdata.use(AutoTrackApp, autoTrack);
sensorsdata.use(AutoTrackPage, autoTrack);
};
sa.lib.name = 'BytedanceMini';
sa.properties.$lib = 'BytedanceMini';
sa.system = system;
sa.system_api = compose;
sa._ = _;
sa.storageName = 'sensorsdata2015_tt';
sa.meta.scene_prefix = 'byte-';
REQUEST.header = { 'Content-Type': 'text/plain' };
sa.platform_obj = tt;
sa.use(AutoTrack);
export default sa;
!function(){var e=null,t=null,n={getVisibility:function(e){function t(e){var i=e.parentNode;if(9===i.nodeType)return!0;if("0"===n(e,"opacity")||"none"===n(e,"display")||"hidden"===n(e,"visibility"))return!1;if(i){var r=i.getBoundingClientRect();if("hidden"===n(i,"overflow")||"scroll"===n(i,"overflow")){if(o.bottom<=r.top||o.top>=r.bottom||o.right<=r.left||o.left>=r.right)return!1}else if("hidden"===n(i,"overflow-y")||"scroll"===n(i,"overflow-y")){if(o.bottom<=r.top||o.top>=r.bottom)return!1}else if(("hidden"===n(i,"overflow-x")||"scroll"===n(i,"overflow-x"))&&(o.right<=r.left||o.left>=r.right))return!1;return t(i)}return!0}function n(e,t){return window.getComputedStyle?document.defaultView.getComputedStyle(e,null)[t]:e.currentStyle?e.currentStyle[t]:void 0}function i(){var e=document.body.getBoundingClientRect();return!(o.top>=e.bottom||o.bottom<=e.top||o.left>=e.right||o.right<=e.left)}var o=e.getBoundingClientRect();return t(e)&&i(e)},getSubElements:function(t){var n=[];if(t.children.length)for(var i=0;i<t.children.length;i++)e.isElement(t.children[i])&&e.isObject(t.children[i].sensorsDefineStore)&&n.push(t.children[i].sensorsDefineStore.id);return n},getInfo:function(n){if(!e.isElement(n)||!e.isObject(n.sensorsDefineStore))return null;var i=n.getBoundingClientRect(),o=n.tagName,r={id:n.sensorsDefineStore.id,$element_content:e.getEleInfo({target:n}).$element_content,$element_selector:t.heatmap.getDomSelector(n),tagName:o,top:i.top,left:i.left,scrollX:window.pageXOffset,scrollY:window.pageYOffset,width:i.width,height:i.height,scale:window.devicePixelRatio,visibility:this.getVisibility(n),$url:location.href,$title:document.title,lib_version:t.lib_version,subelements:this.getSubElements(n),level:n.sensorsDefineStore.level,is_list_view:"li"===o.toLowerCase(),$element_path:t.heatmap.getElementPath(n,t.para.heatmap&&"not_use_id"===t.para.heatmap.element_selector)},l=t.heatmap.getElementPosition(n,r.$element_path,t.para.heatmap&&"not_use_id"===t.para.heatmap.element_selector);return e.isNumber(l)&&(r.$element_position=l),t.heatmap.getClosestLi(n)&&(r.list_selector=this.getListSelector(n)),e.isString(n.sensorsDefineStore.list_selector)&&(r.list_selector=n.sensorsDefineStore.list_selector),r},getZIndex:function(e){var t=window.getComputedStyle(e,null).getPropertyValue("z-index");return t&&!isNaN(+t)?t:0},getlevel:function(e,t){var n=Number(this.getZIndex(e)),i=0,o=window.getComputedStyle(e,null).getPropertyValue("position");return!o||"absolute"!==o&&"fixed"!==o||(i=1e5),t+n+i},getListSelector:function(e){var n="",i=t.heatmap.getClosestLi(e);if(i){var o=t.heatmap.getDomSelector(i,[],!0),r=t.heatmap.getDomSelector(e,[],!0);n=r.replace(o,"")}return n},initElements:function(){function n(e,n){var i={level:n,id:"h"+r};r++,e.sensorsDefineStore=i;var o=t.heatmap.getTargetElement(e);if(o){o.sensorsdata_enable_click=!0;var l=window.getComputedStyle(o,null).getPropertyValue("display");"inline"===l&&(o.style.display="inline-block")}}function i(t,r){for(var s=0;s<t.length;s++)if(e.isElement(t[s])){var a=t[s],f=o.getlevel(a,r);n(a,f),l.push(a),a.children&&i(a.children,f+1)}}var o=this,r=0,l=[];return i(document.body.children,1),l},getElementsInfo:function(){var t=this,n=[],i=[],o=this.initElements();return e.isArray(o)&&e.each(o,function(o){if(e.isElement(o)){var r=o,l=t.getInfo(r);e.isObject(l)&&l.visibility&&(r.sensorsdata_enable_click===!0?(l.enable_click=!0,n.push(l)):(l.enable_click=!1,i.push(l)))}}),{data:this.sortLevel(n),extra_elements:this.sortLevel(i)}},sortLevel:function(e){return e.sort(function(e,t){return e.level-t.level}),e},postDefineInfo:function(){var e=n.getElementsInfo(),i={data:e.data,extra_elements:e.extra_elements};new t.SDKJSBridge("visualized_track").notifyApp(i)},addDefineListener:function(n){function i(e,t,n){var i=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver,o=new i(n);o.observe(e,t)}var o=this,r={childList:!0,subtree:!0,attributes:!0},l=function(){return e.throttle(n,1e3)}();i(document.body,r,l),e.addEvent(window,"scroll",l),e.addEvent(window,"resize",l),e.addEvent(window,"load",l),t.ee&&t.ee.spa&&t.ee.spa.on("switch",function(e){e!==location.href&&o.postPageInfo()})},postPageInfo:function(){var e={data:{$title:document.title,$url:location.href,lib_version:t.lib_version}};new t.SDKJSBridge("page_info").notifyApp(e)},init:function(){var n=this;window.sa_jssdk_app_define_mode=function(i,o){o?(n.postPageInfo(),n.postDefineInfo()):(t=i,e=t._,n.postPageInfo(),e.bindReady(function(){n.postDefineInfo(),n.addDefineListener(n.postDefineInfo)}))}}};n.init()}();
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
var sa={},saPara={name:"sensors",server_url:"",send_timeout:1e3,show_log:!1,login_id_key:"$identity_login_id",allow_amend_share_path:!0,max_string_length:5e3,datasend_timeout:3e3,source_channel:[],autoTrack:{appLaunch:!0,appShow:!0,appHide:!0,pageShow:!0,pageShare:!0,mpClick:!1,mpFavorite:!0,pageLeave:!1},autotrack_exclude_page:{pageShow:[],pageLeave:[]},is_persistent_save:{share:!1,utm:!1},preset_properties:{url_path:!0},preset_events:{moments_page:!1,defer_track:!1,share_info_use_string:!1},batch_send:!0,sdk_id:"",storage_store_key:"sensorsdata2015_wechat",storage_prepare_data_key:"sensors_mp_prepare_data"};function log(){if(saPara.show_log&&"object"==typeof console&&console.log)try{return console.log.apply(console,arguments)}catch(e){console.log(arguments[0])}}var nativeIsArray=Array.isArray,ObjProto=Object.prototype,ArrayProto=Array.prototype,nativeForEach=ArrayProto.forEach,nativeIndexOf=ArrayProto.indexOf,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty,slice=ArrayProto.slice;function each(e,t,a){if(null==e)return!1;var i={};if(nativeForEach&&e.forEach===nativeForEach)e.forEach(t,a);else if(e.length===+e.length){for(var r=0,n=e.length;r<n;r++)if(r in e&&t.call(a,e[r],r,e)===i)return!1}else for(var s in e)if(hasOwnProperty.call(e,s)&&t.call(a,e[s],s,e)===i)return!1}function isObject(e){return null!=e&&"[object Object]"==toString.call(e)}function isAsyncFunction(e){return"[object AsyncFunction]"===Object.prototype.toString.call(e)}var getRandomBasic=function(){var e=(new Date).getTime();return function(t){return Math.ceil((e=(9301*e+49297)%233280)/233280*t)}}();function getRandom(){if("function"==typeof Uint32Array){var e="";if("undefined"!=typeof crypto?e=crypto:"undefined"!=typeof msCrypto&&(e=msCrypto),isObject(e)&&e.getRandomValues){var t=new Uint32Array(1);return e.getRandomValues(t)[0]/Math.pow(2,32)}}return getRandomBasic(1e19)/1e19}function extend(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];if("[object Object]"===Object.prototype.toString.call(a))for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&void 0!==a[i]&&(e[i]=a[i])}return e}function extend2Lev(e){return each(slice.call(arguments,1),function(t){for(var a in t)void 0!==t[a]&&null!==t[a]&&(isObject(t[a])&&isObject(e[a])?extend(e[a],t[a]):e[a]=t[a])}),e}function coverExtend(e){return each(slice.call(arguments,1),function(t){for(var a in t)void 0!==t[a]&&void 0===e[a]&&(e[a]=t[a])}),e}var isArray=nativeIsArray||function(e){return"[object Array]"===toString.call(e)};function isFunction(e){if(!e)return!1;var t=Object.prototype.toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t}function isArguments(e){return!(!e||!hasOwnProperty.call(e,"callee"))}function toArray(e){return e?e.toArray?e.toArray():isArray(e)?slice.call(e):isArguments(e)?slice.call(e):values(e):[]}function values(e){var t=[];return null==e?t:(each(e,function(e){t[t.length]=e}),t)}function include(e,t){var a=!1;return null==e?a:nativeIndexOf&&e.indexOf===nativeIndexOf?-1!=e.indexOf(t):(each(e,function(e){if(a||(a=e===t))return{}}),a)}function trim(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function isEmptyObject(e){if(isObject(e)){for(var t in e)if(hasOwnProperty.call(e,t))return!1;return!0}return!1}function deepCopy(e){var t={};return function e(t,a){for(var i in a){var r=a[i];isArray(r)?(t[i]=[],e(t[i],r)):isObject(r)?(t[i]={},e(t[i],r)):t[i]=r}}(t,e),t}function isUndefined(e){return void 0===e}function isString(e){return"[object String]"==toString.call(e)}function isDate(e){return"[object Date]"==toString.call(e)}function isBoolean(e){return"[object Boolean]"==toString.call(e)}function isNumber(e){return"[object Number]"==toString.call(e)&&/[\d\\.]+/.test(String(e))}function isJSONString(e){try{JSON.parse(e)}catch(e){return!1}return!0}var isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},isSafeInteger=Number.isSafeInteger||function(e){return isInteger(e)&&Math.abs(e)<=Math.pow(2,53)-1},urlSafeBase64={ENC:{"+":"-","/":"_","=":"."},DEC:{"-":"+",_:"/",".":"="},encode:function(e){return e.replace(/[+\/=]/g,function(e){return urlSafeBase64.ENC[e]})},decode:function(e){return e.replace(/[-_.]/g,function(e){return urlSafeBase64.DEC[e]})},trim:function(e){return e.replace(/[.=]{1,2}$/,"")},isBase64:function(e){return/^[A-Za-z0-9+\/]*[=]{0,2}$/.test(e)},isUrlSafeBase64:function(e){return/^[A-Za-z0-9_-]*[.]{0,2}$/.test(e)}},SOURCE_CHANNEL_STANDARD="utm_source utm_medium utm_campaign utm_content utm_term",LATEST_SOURCE_CHANNEL=["$latest_utm_source","$latest_utm_medium","$latest_utm_campaign","$latest_utm_content","$latest_utm_term","$latest_sa_utm"],LATEST_SHARE_INFO=["$latest_share_distinct_id","$latest_share_url_path","$latest_share_depth","$latest_share_method"],SHARE_INFO_KEY=["sensors_share_d","sensors_share_p","sensors_share_i","sensors_share_m"],MP_FILTER_HOOK={data:1,onLoad:1,onShow:1,onReady:1,onPullDownRefresh:1,onShareAppMessage:1,onShareTimeline:1,onReachBottom:1,onPageScroll:1,onResize:1,onTabItemTap:1,onHide:1,onUnload:1},IDENTITY_KEY={EMAIL:"$identity_email",MOBILE:"$identity_mobile",LOGIN:"$identity_login_id"},LIB_VERSION="1.21.7",LIB_NAME="MiniProgram",meta={init_status:!1,life_state:{app_launched:!1},plugin:{init_list:[],uninitialized_list:[]},privacy:{enable_data_collect:!1},initialState:{queue:[],isComplete:!1},preset_properties:{$lib:LIB_NAME,$lib_version:LIB_VERSION},promise_list:[],query_share_depth:0,page_show_time:Date.now(),mp_show_time:null,share_distinct_id:"",share_method:"",current_scene:"",is_first_launch:!1,wx_sdk_version:"",global_title:{},page_route_map:[]};function getAppInfoSync(){if(wx.getAccountInfoSync){var e=wx.getAccountInfoSync(),t=e&&e.miniProgram?e.miniProgram:{};return{appId:t.appId,appEnv:t.envVersion,appVersion:t.version}}return{}}function getAppId(){var e=getAppInfoSync();return e&&e.appId?e.appId:""}function getOpenidNameByAppid(){var e=getAppId(),t="$identity_mp_openid";return e&&(t="$identity_mp_"+e+"_openid"),t}function rot13defs(e){return rot13obfs(e=String(e),113)}function rot13obfs(e,t){t="number"==typeof t?t:13;for(var a=(e=String(e)).split(""),i=0,r=a.length;i<r;i++){a[i].charCodeAt(0)<126&&(a[i]=String.fromCharCode((a[i].charCodeAt(0)+t)%126))}return a.join("")}var hasOwnProperty$1=Object.prototype.hasOwnProperty,store={storageInfo:null,store_queue:[],getUUID:function(){return Date.now()+"-"+Math.floor(1e7*getRandom())+"-"+getRandom().toString(16).replace(".","")+"-"+String(31242*getRandom()).replace(".","").slice(0,8)},getStorage:function(){return this.storageInfo?this.storageInfo:(this.storageInfo=sa._.getStorageSync(saPara.storage_store_key)||"",this.storageInfo)},_state:{},mem:{mdata:[],getLength:function(){return this.mdata.length},add:function(e){this.mdata.push(e)},clear:function(e){this.mdata.splice(0,e)}},toState:function(e){var t=null,a=this;function i(){t.distinct_id?a._state=t:a.set("distinct_id",a.getUUID())}isJSONString(e)?(t=JSON.parse(e),i()):isObject(e)?(t=e,i()):this.set("distinct_id",this.getUUID());var r=this._state._first_id||this._state.first_id,n=this._state._distinct_id||this._state.distinct_id,s=this._state.openid,o=(this._state.history_login_id?this._state.history_login_id:{}).name;if(this._state.identities&&isString(this._state.identities)){var u=JSON.parse(rot13defs(this._state.identities));this._state.identities=u}var c,p,d=getOpenidNameByAppid();if(this._state.identities&&isObject(this._state.identities)&&!isEmptyObject(this._state.identities)){var l=(c=getAppId(),p="$mp_openid",c&&(p="$mp_"+c+"_openid"),p);hasOwnProperty$1.call(this._state.identities,"$mp_id")&&(this._state.identities.$identity_mp_id=this._state.identities.$mp_id,delete this._state.identities.$mp_id),hasOwnProperty$1.call(this._state.identities,"$mp_unionid")&&(this._state.identities.$identity_mp_unionid=this._state.identities.$mp_unionid,delete this._state.identities.$mp_unionid),hasOwnProperty$1.call(this._state.identities,l)&&(this._state.identities[d]=this._state.identities[l],delete this._state.identities[l])}else this._state.identities={},this._state.identities.$identity_mp_id=this.getUUID();function _(e){for(var t in store._state.identities)hasOwnProperty$1.call(store._state.identities,t)&&"$identity_mp_id"!==t&&t!==e&&delete store._state.identities[t]}s&&(this._state.identities[d]=s),r?o&&hasOwnProperty$1.call(this._state.identities,o)?this._state.identities[o]!==n&&(this._state.identities[o]=n,_(o),this._state.history_login_id.value=n):(this._state.identities[IDENTITY_KEY.LOGIN]=n,_(IDENTITY_KEY.LOGIN),this._state.history_login_id={name:IDENTITY_KEY.LOGIN,value:n}):this._state.history_login_id={name:"",value:""},this.save()},getFirstId:function(){return this._state._first_id||this._state.first_id},getDistinctId:function(){var e=this.getLoginDistinctId();return e||(this._state._distinct_id||this._state.distinct_id)},getUnionId:function(){var e={},t=this._state._first_id||this._state.first_id,a=this.getDistinctId();return t&&a?(e.login_id=a,e.anonymous_id=t):e.anonymous_id=a,e},getIdentities:function(){var e=JSON.parse(JSON.stringify(this._state.identities));return e.$identity_anonymous_id=this.getAnonymousId(),e},getAnonymousId:function(){return this.getUnionId().anonymous_id},getHistoryLoginId:function(){return isObject(this._state.history_login_id)?this._state.history_login_id:null},getLoginDistinctId:function(){var e=this.getHistoryLoginId();return isObject(e)&&e.value?e.name!==IDENTITY_KEY.LOGIN?e.name+"+"+e.value:e.value:null},getProps:function(){return this._state.props||{}},setProps:function(e,t){var a=this._state.props||{};t?this.set("props",e):(extend(a,e),this.set("props",a))},set:function(e,t){var a={};for(var i in"string"==typeof e?a[e]=t:"object"==typeof e&&(a=e),this._state=this._state||{},a)this._state[i]=a[i],"first_id"===i?delete this._state._first_id:"distinct_id"===i&&(delete this._state._distinct_id,sa.events.emit("changeDistinctId"));this.save()},identitiesSet:function(e){var t={};switch(e.type){case"login":t.$identity_mp_id=this._state.identities.$identity_mp_id,t[e.id_name]=e.id;break;case"logout":t.$identity_mp_id=this._state.identities.$identity_mp_id}this.set("identities",t)},change:function(e,t){this._state["_"+e]=t},encryptStorage:function(){var e=this.getStorage(),t="data:enc;";isObject(e)?e=t+rot13obfs(JSON.stringify(e)):isString(e)&&-1===e.indexOf(t)&&(e=t+rot13obfs(e)),sa._.setStorageSync(saPara.storage_store_key,e)},save:function(){var e=deepCopy(this._state),t=rot13obfs(JSON.stringify(e.identities));if(e.identities=t,delete e._first_id,delete e._distinct_id,saPara.encrypt_storage){e="data:enc;"+rot13obfs(JSON.stringify(e))}sa._.setStorageSync(saPara.storage_store_key,e)},init:function(){var e=this.getStorage(),t=store.getUUID();if(e)isString(e)&&-1!==e.indexOf("data:enc;")&&(e=e.substring("data:enc;".length),e=JSON.parse(rot13defs(e))),this.toState(e);else{meta.is_first_launch=!0;var a=new Date,i=a.getTime();a.setHours(23),a.setMinutes(59),a.setSeconds(60),this.set({distinct_id:t,first_visit_time:i,first_visit_day_time:a.getTime(),identities:{$identity_mp_id:t},history_login_id:{name:"",value:""}})}this.checkStoreInit()},checkStoreInit:function(){meta.init_status&&(this.store_queue.length>0&&each(this.store_queue,function(e){sa[e.method].apply(sa,slice.call(e.params))}),this.store_queue=[])}};function _decodeURIComponent(e){var t="";try{t=decodeURIComponent(e)}catch(a){t=e}return t}var hasOwnProperty$2=Object.prototype.hasOwnProperty,decodeURIComponent$1=_decodeURIComponent;function initAppGlobalName(){var e=App;App=function(t){t[saPara.name]=sa,e.apply(this,arguments)}}function getPublicPresetProperties(){var e=getRefPage(),t=getCurrentPageInfo(),a={$referrer:e.route,$referrer_title:e.title,$title:t.title,$url:t.url};return!0===saPara.preset_properties.url_path&&(a.$url_path=t.path),a}function encodeDates(e){return each(e,function(t,a){isDate(t)?e[a]=formatDate(t):isObject(t)&&(e[a]=encodeDates(t))}),e}function formatDate(e){function t(e){return e<10?"0"+e:e}return e.getFullYear()+"-"+t(e.getMonth()+1)+"-"+t(e.getDate())+" "+t(e.getHours())+":"+t(e.getMinutes())+":"+t(e.getSeconds())+"."+t(e.getMilliseconds())}function searchObjDate(e){(isObject(e)||isArray(e))&&each(e,function(t,a){isObject(t)||isArray(t)?searchObjDate(e[a]):isDate(t)&&(e[a]=formatDate(t))})}function formatString(e){return e.length>saPara.max_string_length?(log("\u5b57\u7b26\u4e32\u957f\u5ea6\u8d85\u8fc7\u9650\u5236\uff0c\u5df2\u7ecf\u505a\u622a\u53d6--"+e),e.slice(0,saPara.max_string_length)):e}function searchObjString(e){isObject(e)&&each(e,function(t,a){isObject(t)?searchObjString(e[a]):isString(t)&&(e[a]=formatString(t))})}function parseSuperProperties(e){isObject(e)&&each(e,function(t,a){if(isFunction(t))try{e[a]=t(),isFunction(e[a])&&(log("\u60a8\u7684\u5c5e\u6027- "+a+" \u683c\u5f0f\u4e0d\u6ee1\u8db3\u8981\u6c42\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u5176\u5220\u9664"),delete e[a])}catch(t){delete e[a],log("\u60a8\u7684\u5c5e\u6027- "+a+" \u629b\u51fa\u4e86\u5f02\u5e38\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u5176\u5220\u9664")}})}function unique(e){for(var t,a=[],i={},r=0;r<e.length;r++)(t=e[r])in i||(i[t]=!0,a.push(t));return a}var check={checkKeyword:function(e){return/^((?!^distinct_id$|^original_id$|^device_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i.test(e)},checkIdLength:function(e){return!(String(e).length>255)||(log("id \u957f\u5ea6\u8d85\u8fc7 255 \u4e2a\u5b57\u7b26\uff01"),!1)}};function strip_sa_properties(e){return isObject(e)?(each(e,function(t,a){if(isArray(t)){var i=[];each(t,function(e){if(isString(e))i.push(e);else if(isUndefined(e))i.push("null");else try{i.push(JSON.stringify(e))}catch(e){log("\u60a8\u7684\u6570\u636e - "+a+":"+t+" - \u7684\u6570\u7ec4\u91cc\u7684\u503c\u6709\u9519\u8bef,\u5df2\u7ecf\u5c06\u5176\u5220\u9664")}}),e[a]=i}if(isObject(t))try{e[a]=JSON.stringify(t)}catch(i){delete e[a],log("\u60a8\u7684\u6570\u636e - "+a+":"+t+" - \u7684\u6570\u636e\u503c\u6709\u9519\u8bef,\u5df2\u7ecf\u5c06\u5176\u5220\u9664")}else isString(t)||isNumber(t)||isDate(t)||isBoolean(t)||isArray(t)||(log("\u60a8\u7684\u6570\u636e - "+a+":"+t+" - \u683c\u5f0f\u4e0d\u6ee1\u8db3\u8981\u6c42\uff0c\u5df2\u7ecf\u5c06\u5176\u5220\u9664"),delete e[a])}),e):e}function strip_empty_properties(e){var t={};return each(e,function(e,a){null==e&&void 0===e||(t[a]=e)}),t}function utf8Encode(e){var t,a,i,r,n="";for(t=a=0,i=(e=(e+"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")).length,r=0;r<i;r++){var s=e.charCodeAt(r),o=null;s<128?a++:o=s>127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==o&&(a>t&&(n+=e.substring(t,a)),n+=o,t=a=r+1)}return a>t&&(n+=e.substring(t,e.length)),n}function base64Encode(e){var t,a,i,r,n,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o=0,u=0,c="",p=[];if(!e)return e;e=utf8Encode(e);do{t=(n=e.charCodeAt(o++)<<16|e.charCodeAt(o++)<<8|e.charCodeAt(o++))>>18&63,a=n>>12&63,i=n>>6&63,r=63&n,p[u++]=s.charAt(t)+s.charAt(a)+s.charAt(i)+s.charAt(r)}while(o<e.length);switch(c=p.join(""),e.length%3){case 1:c=c.slice(0,-2)+"==";break;case 2:c=c.slice(0,-1)+"="}return c}function btoa(e){for(var t,a,i,r,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="",o=0,u=(e=String(e)).length%3;o<e.length;)((a=e.charCodeAt(o++))>255||(i=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255)&&log("Failed to execute 'btoa' : The string to be encoded contains characters outside of the Latin1 range."),s+=n.charAt((t=a<<16|i<<8|r)>>18&63)+n.charAt(t>>12&63)+n.charAt(t>>6&63)+n.charAt(63&t);return u?s.slice(0,u-3)+"===".substring(u):s}function urlBase64Encode(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function getCurrentPage(){var e={};try{var t=getCurrentPages();e=t[t.length-1]}catch(e){log(e)}return e}function getCurrentPath(){var e="\u672a\u53d6\u5230";try{var t=getCurrentPage();e=t?t.route:e}catch(e){log(e)}return e}function getIsFirstDay(){return!!("object"==typeof store._state&&isNumber(store._state.first_visit_day_time)&&store._state.first_visit_day_time>(new Date).getTime())}function getCurrentUrl(e){var t=getCurrentPath(),a="";return isObject(e)&&e.sensors_mp_encode_url_query&&(a=e.sensors_mp_encode_url_query),t?a?t+"?"+a:t:"\u672a\u53d6\u5230"}function getPath(e){return e=isString(e)?e.replace(/^\//,""):"\u53d6\u503c\u5f02\u5e38"}function getCustomUtmFromQuery(e,t,a,i){if(!isObject(e))return{};var r={};if(e.sa_utm)for(var n in e)"sa_utm"!==n?include(saPara.source_channel,n)&&(r[a+n]=e[n]):r[i+n]=e[n];else for(var s in e)-1===(" "+SOURCE_CHANNEL_STANDARD+" ").indexOf(" "+s+" ")?include(saPara.source_channel,s)&&(r[a+s]=e[s]):r[t+s]=e[s];return r}function getObjFromQuery(e){var t=e.split("?"),a=[],i={};return t&&t[1]?(each(t[1].split("&"),function(e){(a=e.split("="))[0]&&a[1]&&(i[a[0]]=a[1])}),i):{}}function setStorageSync(e,t){var a=function(){wx.setStorageSync(e,t)};try{a()}catch(e){log("set Storage fail --",e);try{a()}catch(e){log("set Storage fail again --",e)}}}function getStorageSync(e){var t="";try{t=wx.getStorageSync(e)}catch(e){log("getStorage fail")}return t}function getMPScene(e){return isNumber(e)||isString(e)&&""!==e?e="wx-"+String(e):"\u672a\u53d6\u5230\u503c"}function objToParam(e,t){if(!isObject(e))return log("\u8bf7\u4f20\u5165\u6709\u6548\u5bf9\u8c61"),"";var a=[];for(var i in e)if(hasOwnProperty$2.call(e,i)){var r=e[i];void 0===r?a.push(i+"="):(r=t?encodeURIComponent(r):r,a.push(i+"="+r))}return a.join("&")}function delObjectKey(e){if(isObject(e))for(var t=0;t<SHARE_INFO_KEY.length;t++)delete e[SHARE_INFO_KEY[t]];else log("\u8bf7\u4f20\u5165\u6709\u6548\u5bf9\u8c61")}function shareInfoData(e){var t={},a={};if(saPara.preset_events.share_info_use_string){a=e.query;for(var i=0;i<SHARE_INFO_KEY.length;i++){if(!hasOwnProperty$2.call(a,SHARE_INFO_KEY[i]))return{};a[SHARE_INFO_KEY[i]]=_decodeURIComponent(a[SHARE_INFO_KEY[i]])}t={depth:Number(a.sensors_share_d),path:a.sensors_share_p||"",id:a.sensors_share_i||"",method:a.sensors_share_m||""}}else{if(!e.query.sampshare)return{};if(!isJSONString(a=_decodeURIComponent(e.query.sampshare)))return{};t={depth:(a=JSON.parse(a)).d,path:a.p,id:a.i,method:a.m}}return t}function setShareInfo(e,t){var a={},i={},r=store.getDistinctId(),n=store.getFirstId();if(e&&isObject(e.query)){if(isEmptyObject(a=shareInfoData(e)))return{};var s=a.depth,o=a.path,u=a.id,c=a.method}"string"==typeof u?(t.$share_distinct_id=u,meta.share_distinct_id=u,i.$latest_share_distinct_id=u):t.$share_distinct_id="\u53d6\u503c\u5f02\u5e38","number"==typeof s?!meta.share_distinct_id||meta.share_distinct_id!==r&&meta.share_distinct_id!==n?!meta.share_distinct_id||meta.share_distinct_id===r&&meta.share_distinct_id===n?t.$share_depth="-1":(t.$share_depth=s+1,meta.query_share_depth=s+1,i.$latest_share_depth=s+1):(t.$share_depth=s,meta.query_share_depth=s,i.$latest_share_depth=s):t.$share_depth="-1","string"==typeof o?(t.$share_url_path=o,i.$latest_share_url_path=o):t.$share_url_path="\u53d6\u503c\u5f02\u5e38","string"==typeof c?(t.$share_method=c,i.$latest_share_method=c):t.$share_method="\u53d6\u503c\u5f02\u5e38",setLatestShare(i)}function getShareInfo(){if(saPara.preset_events.share_info_use_string)return objToParam({sensors_share_i:store.getDistinctId()||"\u53d6\u503c\u5f02\u5e38",sensors_share_p:getCurrentPath(),sensors_share_d:meta.query_share_depth,sensors_share_m:meta.share_method},!0);var e=JSON.stringify({i:store.getDistinctId()||"\u53d6\u503c\u5f02\u5e38",p:getCurrentPath(),d:meta.query_share_depth,m:meta.share_method});return"sampshare="+encodeURIComponent(e)}function detectOptionQuery(e){if(!e||!isObject(e.query))return{};var t,a,i,r,n={};return n.query=extend({},e.query),"string"==typeof n.query.scene&&(t=n.query,a=["utm_source","utm_content","utm_medium","utm_campaign","utm_term","sa_utm"].concat(saPara.source_channel),i=new RegExp("("+a.join("|")+")%3D","i"),1===(r=Object.keys(t)).length&&"scene"===r[0]&&i.test(t.scene))&&(n.scene=n.query.scene,delete n.query.scene),e.query.q&&e.query.scancode_time&&"101"===String(e.scene).slice(0,3)&&(n.q=String(n.query.q),delete n.query.q,delete n.query.scancode_time),n}function getMixedQuery(e){var t=detectOptionQuery(e),a=t.scene,i=t.q,r=t.query;for(var n in r)r[n]=_decodeURIComponent(r[n]);return a&&extend(r,getObjFromQuery(a=-1!==(a=_decodeURIComponent(a)).indexOf("?")?"?"+a.replace(/\?/g,""):"?"+a)),i&&extend(r,getObjFromQuery(_decodeURIComponent(i))),r}function setUtm(e,t){var a={},i=getMixedQuery(e),r=getCustomUtmFromQuery(i,"$","_","$"),n=getCustomUtmFromQuery(i,"$latest_","_latest_","$latest_");return a.pre1=r,a.pre2=n,extend(t,r),a}function setSfSource(e,t){isEmptyObject(e.query)||e.query&&e.query._sfs&&(t.$sf_source=e.query._sfs,sa.registerApp({$latest_sf_source:t.$sf_source}))}function setPageSfSource(e){try{var t=getCurrentPage(),a=deepCopy(t?t.options:"");for(var i in a)a[i]=_decodeURIComponent(a[i]);!isEmptyObject(a)&&a._sfs&&(e.$sf_source=a._sfs)}catch(e){log(e)}}function setRefPage(){var e={route:"\u76f4\u63a5\u6253\u5f00",path:"\u76f4\u63a5\u6253\u5f00",title:""};try{var t=getCurrentPage();if(t&&t.route){var a=t.sensors_mp_url_query?"?"+t.sensors_mp_url_query:"",i=t.route,r=getPageTitle(i);e.route=i+a,e.path=i,e.title=r,meta.page_route_map.length>=2?(meta.page_route_map.shift(),meta.page_route_map.push(e)):meta.page_route_map.push(e)}}catch(e){log(e)}}function getRefPage(){var e={route:"\u76f4\u63a5\u6253\u5f00",path:"\u76f4\u63a5\u6253\u5f00",title:""};return meta.page_route_map.length>1&&(e.title=meta.page_route_map[0].title,e.route=meta.page_route_map[0].route,e.path=meta.page_route_map[0].path),e}function getCurrentPageInfo(){var e=getCurrentPage(),t={title:"",url:"",path:"\u672a\u53d6\u5230"};if(e&&e.route){var a=e.sensors_mp_url_query?"?"+e.sensors_mp_url_query:"";t.title=getPageTitle(e.route),t.url=e.route+a,t.path=e.route}return t}function setPageRefData(e,t,a){var i=getRefPage();isObject(e)&&(t?meta.page_route_map.length>0&&t?(a=a?"?"+a:"",e.$referrer=getPath(t)+a,e.$referrer_title=getPageTitle(t)):(e.$referrer="\u76f4\u63a5\u6253\u5f00",e.$referrer_title=""):(e.$referrer=i.route,e.$referrer_title=i.title))}function getPageTitle(e){if("\u672a\u53d6\u5230"===e||!e)return"";var t="";try{if(__wxConfig){var a=__wxConfig,i=__wxConfig.page||{},r=i[e]||i[e+".html"],n={},s={};if(a.global&&a.global.window&&a.global.window.navigationBarTitleText&&(n.titleVal=a.global.window.navigationBarTitleText),r&&r.window&&r.window.navigationBarTitleText&&(s.titleVal=r.window.navigationBarTitleText),!s.titleVal&&__wxAppCode__){var o=__wxAppCode__[e+".json"];o&&o.navigationBarTitleText&&(s.titleVal=o.navigationBarTitleText)}if(each(meta.global_title,function(a,i){if(i===e)return t=a}),0===t.length){var u=extend(n,s);t=u.titleVal||""}}}catch(e){log(e)}return t}function wxrequest(e){if(compareSDKVersion(meta.wx_sdk_version,"2.10.0")>=0)e.timeout=saPara.datasend_timeout,wx.request(e);else{var t=wx.request(e);setTimeout(function(){isObject(t)&&isFunction(t.abort)&&t.abort()},saPara.datasend_timeout)}}function validId(e){return"string"!=typeof e&&"number"!=typeof e||""===e?(log("\u8f93\u5165 ID \u7c7b\u578b\u9519\u8bef"),!1):"number"!=typeof e||(e=String(e),/^\d+$/.test(e))?!!check.checkIdLength(e)&&e:(log("\u8f93\u5165 ID \u7c7b\u578b\u9519\u8bef"),!1)}function compareSDKVersion(e,t){e=e.split("."),t=t.split(".");for(var a=Math.max(e.length,t.length);e.length<a;)e.push("0");for(;t.length<a;)t.push("0");for(var i=0;i<a;i++){var r=parseInt(e[i]),n=parseInt(t[i]);if(r>n)return 1;if(r<n)return-1}return 0}function setUpperCase(e){return isString(e)?e.toLocaleUpperCase():e}function setLatestChannel(e){isEmptyObject(e)||(function(e,t){var a=!1;for(var i in t)e[t[i]]&&(a=!0);return a}(e,LATEST_SOURCE_CHANNEL)&&(sa.clearAppRegister(LATEST_SOURCE_CHANNEL),sa.clearAllProps(LATEST_SOURCE_CHANNEL)),saPara.is_persistent_save.utm?sa.register(e):sa.registerApp(e))}function setLatestShare(e){(e.$latest_share_depth||e.$latest_share_distinct_id||e.$latest_share_url_path||e.$latest_share_method)&&(sa.clearAppRegister(LATEST_SHARE_INFO),sa.clearAllProps(LATEST_SHARE_INFO),saPara.is_persistent_save.share?sa.register(e):sa.registerApp(e))}function setQuery(e,t){if(e&&isObject(e)&&!isEmptyObject(e)){var a=[];return each(e,function(e,i){"q"===i&&isString(e)&&0===e.indexOf("http")||(t?a.push(i+"="+e):a.push(i+"="+_decodeURIComponent(e)))}),a.join("&")}return""}function setNavigationBarTitle(){try{var e=wx.setNavigationBarTitle;Object.defineProperty(wx,"setNavigationBarTitle",{get:function(){return function(t){var a=getCurrentPath();t=isObject(t)?t:{},meta.global_title[a]=t.title,e.call(this,t)}}})}catch(e){log(e)}}function getUtmFromPage(){var e={};try{var t=deepCopy(getCurrentPage().options);for(var a in t)t[a]=_decodeURIComponent(t[a]);e=getCustomUtmFromQuery(t,"$","_","$")}catch(e){log(e)}return e}function isNewLoginId(e,t){return e!==store._state.history_login_id.name||store._state.history_login_id.value!==t}function isSameAndAnonymousID(e){var t=store.getFirstId(),a=store.getDistinctId();return t?e===t:e===a}function isPresetIdKeys(e,t){var a=["$identity_anonymous_id"];for(var i of(isArray(t)&&(a=a.concat(t)),a))if(i===e)return!0;return!1}function encodeTrackData(e){var t=base64Encode(e=JSON.stringify(e));return encodeURIComponent(t)}function setPublicProperties(e){if(e&&e.properties){var t=getRefPage(),a=getCurrentPageInfo(),i={$referrer:t.route,$referrer_title:t.title,$title:a.title,$url:a.url};for(var r in!0===saPara.preset_properties.url_path&&(i.$url_path=a.path),i)hasOwnProperty$2.call(e.properties,r)||(e.properties[r]=i[r])}}function networkStatusChange(){wx.onNetworkStatusChange(function(e){sa.registerApp({$network_type:e.networkType||""})})}function getNetworkType(){return new Promise((e,t)=>{wx.getNetworkType({success:function(t){meta.preset_properties.$network_type=setUpperCase(t.networkType),e()},fail:function(e){log("\u83b7\u53d6\u7f51\u7edc\u4fe1\u606f\u5931\u8d25",e),t()}})})}function getSystemInfo(){var e=meta.preset_properties;return new Promise(t=>{wx.getSystemInfo({success:function(a){var i,r;e.$brand=setUpperCase(a.brand),e.$manufacturer=a.brand,e.$model=a.model,e.$screen_width=Number(a.screenWidth),e.$screen_height=Number(a.screenHeight),e.$os=(i=a.platform,"ios"===(r=i.toLowerCase())?"iOS":"android"===r?"Android":i),e.$os_version=a.system.indexOf(" ")>-1?a.system.split(" ")[1]:a.system,meta.wx_sdk_version=a.SDKVersion,e.$mp_client_app_version=a.version,e.$mp_client_basic_library_version=meta.wx_sdk_version;var n=(new Date).getTimezoneOffset(),s=getAppInfoSync();isNumber(n)&&(e.$timezone_offset=n),s.appId&&(e.$app_id=s.appId),s.appVersion&&(e.$app_version=s.appVersion),t()}})})}var info={currentProps:meta.preset_properties},logger={info:function(){if(saPara.show_log&&"object"==typeof console&&console.log)try{if(3===arguments.length)return console.log(arguments[0],arguments[1],arguments[2]);if(2===arguments.length)return console.log(arguments[0],arguments[1]);if(1===arguments.length)return console.log(arguments[0])}catch(e){console.log(arguments[0])}}};function isValidListener(e){return"function"==typeof e||!(!e||"object"!=typeof e)&&isValidListener(e.listener)}class EventEmitterBase{constructor(){this._events={}}on(e,t){if(!e||!t)return!1;if(!isValidListener(t))throw new Error("listener must be a function");this._events[e]=this._events[e]||[];var a="object"==typeof t;return this._events[e].push(a?t:{listener:t,once:!1}),this}prepend(e,t){if(!e||!t)return!1;if(!isValidListener(t))throw new Error("listener must be a function");this._events[e]=this._events[e]||[];var a="object"==typeof t;return this._events[e].unshift(a?t:{listener:t,once:!1}),this}prependOnce(e,t){return this.prepend(e,{listener:t,once:!0})}once(e,t){return this.on(e,{listener:t,once:!0})}off(e,t){var a=this._events[e];if(!a)return!1;if("number"==typeof t)a.splice(t,1);else if("function"==typeof t)for(var i=0,r=a.length;i<r;i++)a[i]&&a[i].listener===t&&a.splice(i,1);return this}emit(e,t){var a=this._events[e];if(!a)return!1;for(var i=0;i<a.length;i++){var r=a[i];r&&(r.listener.call(this,t||{}),r.once&&this.off(e,i))}return this}removeAllListeners(e){e&&this._events[e]?this._events[e]=[]:this._events={}}listeners(e){return e&&"string"==typeof e?this._events[e]:this._events}}class EventEmitterEx extends EventEmitterBase{constructor(){super(),this.cacheEvents=[],this.maxLen=20}replay(e,t){this.on(e,t),this.cacheEvents.length>0&&this.cacheEvents.forEach(function(a){a.type===e&&t.call(null,a.data)})}emit(e,t){super.emit.apply(this,arguments),this.cacheEvents.push({type:e,data:t}),this.cacheEvents.length>this.maxLen&&this.cacheEvents.shift()}}var _=Object.freeze({__proto__:null,decodeURIComponent:decodeURIComponent$1,encodeDates:encodeDates,formatDate:formatDate,searchObjDate:searchObjDate,formatString:formatString,searchObjString:searchObjString,parseSuperProperties:parseSuperProperties,unique:unique,check:check,getUtmFromPage:getUtmFromPage,setQuery:setQuery,setLatestShare:setLatestShare,setLatestChannel:setLatestChannel,setUpperCase:setUpperCase,compareSDKVersion:compareSDKVersion,validId:validId,wxrequest:wxrequest,getPageTitle:getPageTitle,setPageRefData:setPageRefData,getCurrentPageInfo:getCurrentPageInfo,getRefPage:getRefPage,setRefPage:setRefPage,setPageSfSource:setPageSfSource,setSfSource:setSfSource,setUtm:setUtm,getMixedQuery:getMixedQuery,detectOptionQuery:detectOptionQuery,getShareInfo:getShareInfo,setShareInfo:setShareInfo,shareInfoData:shareInfoData,delObjectKey:delObjectKey,objToParam:objToParam,getMPScene:getMPScene,getStorageSync:getStorageSync,setStorageSync:setStorageSync,getObjFromQuery:getObjFromQuery,getCustomUtmFromQuery:getCustomUtmFromQuery,getPath:getPath,getCurrentUrl:getCurrentUrl,getIsFirstDay:getIsFirstDay,getCurrentPath:getCurrentPath,getCurrentPage:getCurrentPage,urlBase64Encode:urlBase64Encode,btoa:btoa,base64Encode:base64Encode,strip_empty_properties:strip_empty_properties,strip_sa_properties:strip_sa_properties,setNavigationBarTitle:setNavigationBarTitle,networkStatusChange:networkStatusChange,getNetworkType:getNetworkType,getSystemInfo:getSystemInfo,encodeTrackData:encodeTrackData,initAppGlobalName:initAppGlobalName,getPublicPresetProperties:getPublicPresetProperties,setPublicProperties:setPublicProperties,isPresetIdKeys:isPresetIdKeys,isNewLoginId:isNewLoginId,isSameAndAnonymousID:isSameAndAnonymousID,info:info,logger:logger,getAppId:getAppId,getAppInfoSync:getAppInfoSync,getOpenidNameByAppid:getOpenidNameByAppid,rot13defs:rot13defs,rot13obfs:rot13obfs,each:each,isObject:isObject,getRandom:getRandom,extend:extend,extend2Lev:extend2Lev,coverExtend:coverExtend,isArray:isArray,isFunction:isFunction,isAsyncFunction:isAsyncFunction,isArguments:isArguments,toArray:toArray,values:values,include:include,trim:trim,isEmptyObject:isEmptyObject,deepCopy:deepCopy,isUndefined:isUndefined,isString:isString,isDate:isDate,isBoolean:isBoolean,isNumber:isNumber,isJSONString:isJSONString,isInteger:isInteger,isSafeInteger:isSafeInteger,slice:slice,urlSafeBase64:urlSafeBase64,EventEmitterBase:EventEmitterBase,EventEmitterEx:EventEmitterEx,log:log});function onEventSend(){return{}}function processData(e){return e}function batchTrackData(e){var t=Date.now();return e.forEach(function(e){e._flush_time=t}),"data_list="+encodeTrackData(e)}var mergeStorageData={getData:function(e){wx.getStorage({key:saPara.storage_prepare_data_key,complete:function(t){var a=t.data&&isArray(t.data)?t.data:[];mergeStorageData.deleteAesData(a),e&&e()}})},deleteAesData:function(e){var t=[],a=e.length;if(a>0){for(var i=0;i<a;i++)isObject(e[i])&&t.push(e[i]);store.mem.mdata=t.concat(store.mem.mdata)}}};function onceTrackData(e){return"data="+encodeTrackData(e)}var kit={};function setKitTitle(e){if(!isString(e))return!1;var t=meta.page_route_map.length-1;t>=0&&(meta.page_route_map[t].title=e)}kit.setData=function(e){if(!isObject(e))return!1;e.current_title&&setKitTitle(e.current_title)},kit.processData=processData,kit.onceTrackData=onceTrackData,kit.batchTrackData=batchTrackData,kit.onEventSend=onEventSend,kit.onceSend=function(){};var sendStrategy={dataHasSend:!0,dataHasChange:!1,syncStorage:!1,failTime:0,init:function(){this.sendHasInit=!0,mergeStorageData.getData(sendStrategy.syncStorageState.bind(sendStrategy)),this.batchInterval(),this.onAppHide()},syncStorageState:function(){this.syncStorage=!0},onAppHide:function(){var e=this;wx.onAppHide(function(){saPara.batch_send&&e.batchSend()})},send:function(e){this.dataHasChange=!0,store.mem.getLength()>=500&&(log("storage data is too large"),store.mem.mdata.shift()),(e=kit.processData(e))&&store.mem.add(e),this.sendAsOver()},sendAsOver:function(){this.sendHasInit&&store.mem.getLength()>=saPara.batch_send.max_length&&this.batchSend()},wxrequest:function(e){if(isArray(e.data)&&e.data.length>0){var t=kit.batchTrackData(e.data);sa._.wxrequest({url:saPara.server_url,method:"POST",dataType:"text",data:t,header:{"content-type":"text/plain"},success:function(){e.success(e.len)},fail:function(){e.fail()}})}else e.success(e.len)},batchSend:function(){if(this.dataHasSend){var e,t,a=store.mem.mdata;(t=(e=a.length>=100?a.slice(0,100):a).length)>0&&(this.dataHasSend=!1,this.wxrequest({data:e,len:t,success:this.batchRemove.bind(this),fail:this.sendFail.bind(this)}))}},sendFail:function(){this.dataHasSend=!0,this.failTime++},batchRemove:function(e){store.mem.clear(e),this.dataHasSend=!0,this.dataHasChange=!0,this.batchWrite(),this.failTime=0},is_first_batch_write:!0,batchWrite:function(){this.dataHasChange&&(this.dataHasChange=!1,this.syncStorage&&sa._.setStorageSync(saPara.storage_prepare_data_key,store.mem.mdata))},batchInterval:function(){var e=this;!function t(){setTimeout(function(){e.batchWrite(),t()},500)}(),function t(){setTimeout(function(){e.batchSend(),t()},saPara.batch_send.send_timeout*Math.pow(2,e.failTime))}()}};function buildData(e,t){var a={distinct_id:sa.store.getDistinctId(),identities:extend({},sa.store.getIdentities()),lib:{$lib:LIB_NAME,$lib_method:"code",$lib_version:LIB_VERSION},properties:{}};return isObject(t)||(t={}),"track_id_unbind"===e.type&&"$UnbindID"===e.event&&(a.identities=deepCopy(e.unbind_value),delete e.unbind_value),extend(a,sa.store.getUnionId(),e),isObject(e.properties)&&!isEmptyObject(e.properties)&&extend(a.properties,e.properties),"track_id_unbind"===e.type&&"$UnbindID"===e.event&&(a.login_id&&delete a.login_id,a.anonymous_id&&delete a.anonymous_id),e.type&&"profile"===e.type.slice(0,7)||(a._track_id=Number(String(getRandom()).slice(2,5)+String(getRandom()).slice(2,4)+String(Date.now()).slice(-4)),a.properties=extend({},getPublicPresetProperties(),meta.preset_properties,sa.store.getProps(),t,a.properties),"track"===e.type&&(a.properties.$is_first_day=getIsFirstDay())),a.properties.$time&&isDate(a.properties.$time)?(a.time=1*a.properties.$time,delete a.properties.$time):a.time=1*new Date,sa.ee.sdk.emit("createData",a),sa.ee.sdk.emit("beforeBuildCheck",a),sa.ee.data.emit("beforeBuildCheck",a),parseSuperProperties(a.properties),searchObjDate(a),strip_sa_properties(a.properties),searchObjString(a),sa.ee.data.emit("finalAdjustData",a),a}function dataStage(e){if(!saPara.server_url)return!1;if(meta.current_scene&&1154===meta.current_scene&&!sa.para.preset_events.moments_page)return!1;var t=sa._.deepCopy(e),a=buildData(e,kit.onEventSend(t));a?(log(a),sa.events.emit("send",a),sa.para.batch_send?sendStrategy.send(a):sa.kit.onceSend(a)):log("error: \u6570\u636e\u5f02\u5e38 "+a)}sa.popupEmitter={attached:function(){return!1}};var usePlugin=function(e,t){if(!isObject(e)&&!isFunction(e))return log("plugin must be an object",e),!1;if(isFunction(e.init)||log("plugin maybe missing init method",e.plugin_name||e),isString(e.plugin_name)&&e.plugin_name?sa.modules[e.plugin_name]?e=sa.modules[e.plugin_name]:sa.modules[e.plugin_name]=e:log("plugin_name is not defined - ",e.plugin_name||e),isObject(e)&&!0===e.plugin_is_init)return e;if(isObject(e)&&e.plugin_name&&(isString(e.plugin_version)&&e.plugin_version===LIB_VERSION||log("warning!"+e.plugin_name+" plugin version do not match SDK version \uff01\uff01\uff01")),meta.init_status)"function"==typeof e.init&&(e.init(sa,t),e.plugin_is_init=!0,log(e.plugin_name+" plugin is initialized"));else{var a={target:e,para:t};meta.plugin.uninitialized_list.push(a)}return e},use=function(e,t){return isObject(e)||isFunction(e)?(isFunction(e.init)||log("plugin maybe missing init method",e.plugin_name||e),isString(e.plugin_name)&&e.plugin_name?sa.modules[e.plugin_name]?e=sa.modules[e.plugin_name]:sa.modules[e.plugin_name]=e:log("plugin_name is not defined - ",e.plugin_name||e),isObject(e)&&!0===e.plugin_is_init?e:(isObject(e)&&e.plugin_name&&(isString(e.plugin_version)&&e.plugin_version===LIB_VERSION||log("warning!"+e.plugin_name+" plugin version do not match SDK version \uff01\uff01\uff01")),"function"==typeof e.init&&(e.init(sa,t),e.plugin_is_init=!0,log(e.plugin_name+" plugin is initialized")),e)):(log("plugin must be an object",e),!1)},checkPluginInitStatus=function(){if(meta.plugin.uninitialized_list.length>0){for(var e in meta.plugin.uninitialized_list){var t=meta.plugin.uninitialized_list[e];t&&t.target&&"function"==typeof t.target.init&&!t.target.plugin_is_init&&(t.target.init(sa,t.para),isObject(t.target)&&(t.target.plugin_is_init=!0,isString(t.target.plugin_name)&&t.target.plugin_name&&log(t.target.plugin_name+" plugin is initialized")))}meta.plugin.uninitialized_list=[]}};function initAppShowHide(){wx.onAppShow(function(e){if(!meta.life_state.app_launched){var t=wx.getLaunchOptionsSync()||{};sa.autoTrackCustom.appLaunch(t)}sa.autoTrackCustom.appShow(e)}),wx.onAppHide(function(){sa.autoTrackCustom.appHide()})}function checkAppLaunch(){if(!meta.life_state.app_launched){var e=wx.getLaunchOptionsSync()||{};sa.autoTrackCustom.appLaunch(e)}}function mpProxy(e,t,a){var i=sa.autoTrackCustom[a];if(e[t]){var r=e[t];e[t]=function(){!sa.para.autoTrackIsFirst||isObject(sa.para.autoTrackIsFirst)&&!sa.para.autoTrackIsFirst[a]?(r.apply(this,arguments),i.apply(this,arguments)):(!0===sa.para.autoTrackIsFirst||isObject(sa.para.autoTrackIsFirst)&&sa.para.autoTrackIsFirst[a])&&(i.apply(this,arguments),r.apply(this,arguments)),sa.ee.page.emit(a)}}else e[t]=function(){i.apply(this,arguments),sa.ee.page.emit(a)}}function clickTrack(e){var t,a={},i={},r=e.currentTarget||{},n=e.target||{};if(isObject(sa.para.framework)&&isObject(sa.para.framework.taro)&&!sa.para.framework.taro.createApp&&n.id&&r.id&&n.id!==r.id)return!1;var s=r.dataset||{};if(t=e.type,a.$element_id=r.id,a.$element_type=s.type,a.$element_content=s.content,a.$element_name=s.name,isObject(e.event_prop)&&(i=e.event_prop),t&&isClick(t)){if(sa.para.preset_events&&sa.para.preset_events.collect_element&&!1===sa.para.preset_events.collect_element(arguments[0]))return!1;a.$url_path=sa._.getCurrentPath(),sa._.setPageRefData(a),a=sa._.extend(a,i),sa.track("$MPClick",a)}}function clickProxy(e,t){var a=e[t];e[t]=function(){var e=a.apply(this,arguments),t=arguments[0];return isObject(t)&&(sa.para.preset_events.defer_track?setTimeout(function(){clickTrack(t)},0):clickTrack(t)),e}}function isClick(e){return!!{tap:1,longpress:1,longtap:1}[e]}function tabProxy(e){var t=e.onTabItemTap;e.onTabItemTap=function(e){t&&t.apply(this,arguments);var a={};e&&(a.$element_content=e.text),a.$element_type="tabBar",a.$url_path=sa._.getCurrentPath(),sa._.setPageRefData(a),sa.track("$MPClick",a)}}function getMethods(e){var t=MP_FILTER_HOOK,a=[];for(var i in e)"function"!=typeof e[i]||t[i]||a.push(i);return a}function initPageProxy(){var e=Page;Page=function(t){try{t||(t={}),monitorClick(t),monitorHooks(t),e.apply(this,arguments)}catch(t){e.apply(this,arguments)}};var t=Component;Component=function(e){try{e||(e={}),e.methods||(e.methods={}),monitorClick(e.methods),monitorHooks(e.methods),t.apply(this,arguments)}catch(e){t.apply(this,arguments)}}}function monitorClick(e){var t=[];if(sa.para.autoTrack&&sa.para.autoTrack.mpClick){t=getMethods(e),tabProxy(e);for(var a=t.length,i=0;i<a;i++)clickProxy(e,t[i])}}function monitorHooks(e){mpProxy(e,"onLoad","pageLoad"),mpProxy(e,"onShow","pageShow"),mpProxy(e,"onHide","pageHide"),mpProxy(e,"onUnload","pageHide"),mpProxy(e,"onAddToFavorites","pageAddFavorites"),"function"==typeof e.onShareAppMessage&&sa.autoTrackCustom.pageShare(e),"function"==typeof e.onShareTimeline&&sa.autoTrackCustom.pageShareTimeline(e)}var eventEmitter=function(){this.sub=[]};eventEmitter.prototype={add:function(e){this.sub.push(e)},emit:function(e,t){this.sub.forEach(function(a){a.on(e,t)})}};var eventSub=function(e){sa.events.add(this),this._events=[],this.handle=e,this.ready=!1};eventSub.prototype={on:function(e,t){if(this.ready){if(isFunction(this.handle))try{this.handle(e,t)}catch(e){log(e)}}else this._events.push({event:e,data:t})},isReady:function(){var e=this;e.ready=!0,e._events.forEach(function(t){if(isFunction(e.handle))try{e.handle(t.event,t.data)}catch(e){log(e)}})}};var ee={};function checkPrivacyStatus(){var e;return global&&global.sensors_data_pre_config&&(e=!!global.sensors_data_pre_config.is_compliance_enabled&&global.sensors_data_pre_config.is_compliance_enabled),!e||(!!meta.init_status||!!meta.privacy.enable_data_collect)}function enableDataCollect(){meta.privacy.enable_data_collect=!0}function apiStaging(){each(["resetAnonymousIdentity","setProfile","setOnceProfile","track","quick","incrementProfile","appendProfile","login","logout","registerApp","register","clearAllRegister","clearAllProps","clearAppRegister","bind","unbind","bindOpenid","unbindOpenid","bindUnionid","unbindUnionid"],function(e){var t=sa[e];sa[e]=function(){return!!checkPrivacyStatus()&&((!isFunction(sa.getDisabled)||!sa.getDisabled())&&void(meta.initialState.isComplete?t.apply(sa,arguments):meta.initialState.queue.push([e,arguments])))}})}function registerApp(e){isObject(e)&&!isEmptyObject(e)&&(meta.preset_properties=extend(meta.preset_properties,e))}function register(e){isObject(e)&&!isEmptyObject(e)&&store.setProps(e)}function clearAllRegister(){store.setProps({},!0)}function clearAppRegister(e){isArray(e)&&each(meta.preset_properties,function(t,a){include(e,a)&&delete meta.preset_properties[a]})}function clearAllProps(e){var t=store.getProps(),a={};isArray(e)&&(each(t,function(t,i){include(e,i)||(a[i]=t)}),store.setProps(a,!0))}ee.sdk=new EventEmitterEx,ee.data=new EventEmitterEx,ee.page=new EventEmitterEx;var hasOwnProperty$3=Object.prototype.hasOwnProperty;function setProfile(e,t){dataStage({type:"profile_set",properties:e})}function setOnceProfile(e,t){dataStage({type:"profile_set_once",properties:e})}function appendProfile(e,t){if(!isObject(e))return!1;each(e,function(t,a){isString(t)?e[a]=[t]:isArray(t)?e[a]=t:(delete e[a],log("appendProfile\u5c5e\u6027\u7684\u503c\u5fc5\u987b\u662f\u5b57\u7b26\u4e32\u6216\u8005\u6570\u7ec4"))}),dataStage({type:"profile_append",properties:e})}function incrementProfile(e,t){if(!isObject(e))return!1;var a=e;isString(e)&&((e={})[a]=1),dataStage({type:"profile_increment",properties:e})}function track(e,t,a){dataStage({type:"track",event:e,properties:t})}function identify(e){if(!checkPrivacyStatus())return!1;if(!meta.init_status)return store.store_queue.push({method:"identify",params:arguments}),!1;(e=validId(e))&&(store.getFirstId()?store.set("first_id",e):store.set("distinct_id",e))}function resetAnonymousIdentity(e){if(store.getFirstId())return log("resetAnonymousIdentity must be used in a logout state \uff01"),!1;if("number"==typeof e&&(e=String(e)),void 0===e){var t=store.getUUID();store._state.identities.$identity_mp_id=t,store.set("distinct_id",t)}else validId(e)&&(store._state.identities.$identity_mp_id=e,store.set("distinct_id",e))}function trackSignup(e,t,a,i){var r,n,s,o;isObject(e)?(r=e.id,n=e.event_name,s=e.id_name):(r=e,n=t),store.set("distinct_id",r),o=s&&s!==IDENTITY_KEY.LOGIN?s+"+"+r:r,dataStage({original_id:store.getFirstId()||store.getDistinctId(),distinct_id:o,login_id:o,type:"track_signup",event:n,properties:a})}function login(e){if(!(e=validId(e)))return!1;if(isSameAndAnonymousID(e))return!1;var t=store.getFirstId(),a=store.getDistinctId(),i=IDENTITY_KEY.LOGIN;isNewLoginId(i,e)&&(store._state.identities[i]=e,store.set("history_login_id",{name:i,value:e}),t||store.set("first_id",a),sa.trackSignup({id:e,event_name:"$SignUp"}),store.identitiesSet({type:"login",id:e,id_name:i}))}function loginWithKey(e,t){if(log("loginWithKey is deprecated !!!"),!isString(e))return log("Key must be String"),!1;if(!check.checkKeyword(e)&&e.length>100)log("Key ["+e+"] is invalid");else if(!check.checkKeyword(e))return log("Key ["+e+"] is invalid"),!1;if(isPresetIdKeys(e,["$mp_openid","$identity_mp_openid","$identity_mp_unionid","$mp_unionid","$mp_id","$identity_mp_id"]))return log("Key ["+e+"] is invalid"),!1;if(!(t=validId(t)))return!1;if(isSameAndAnonymousID(t))return!1;var a=store.getFirstId(),i=store.getDistinctId();isNewLoginId(e,t)&&(store._state.identities[e]=t,store.set("history_login_id",{name:e,value:t}),a||store.set("first_id",i),sa.trackSignup({id:t,event_name:"$SignUp",id_name:e}),store.identitiesSet({type:"login",id:t,id_name:e}))}function getAnonymousID(){if(!isEmptyObject(store._state))return store._state._first_id||store._state.first_id||store._state._distinct_id||store._state.distinct_id;log("\u8bf7\u5148\u521d\u59cb\u5316SDK")}function getIdentities(){return isEmptyObject(store._state)?(log("\u8bf7\u5148\u521d\u59cb\u5316SDK"),null):store.getIdentities()||null}function logout(e){var t=store.getFirstId();store.identitiesSet({type:"logout"}),store.set("history_login_id",{name:"",value:""}),t?(store.set("first_id",""),!0===e?store.set("distinct_id",store.getUUID()):store.set("distinct_id",t)):log("\u6ca1\u6709first_id\uff0clogout\u5931\u8d25")}function getPresetProperties(){if(meta.preset_properties&&meta.preset_properties.$lib){var e={};each(meta.preset_properties,function(t,a){0===a.indexOf("$")&&(e[a]=t)});var t={$url_path:getCurrentPath(),$is_first_day:getIsFirstDay(),$is_first_time:meta.is_first_launch},a=extend(e,t,meta.preset_properties,store.getProps());return delete a.$lib,a}return{}}function bindOpenid(e){if(!(e=validId(e)))return!1;var t=getOpenidNameByAppid();this.bind(t,e)}function unbindOpenid(e){if(!validId(e))return!1;var t=getOpenidNameByAppid();this.unbind(t,e)}function setUnionid(e){log("setUnionid is deprecated !!!");var t=validId(e);t&&bind("$identity_mp_unionid",t)}function unsetUnionid(e){log("unsetUnionid is deprecated !!!");var t=validId(e);if(t){if(hasOwnProperty$3.call(store._state.identities,"$identity_mp_unionid")&&t===store._state.identities.$identity_mp_unionid){var a=getOpenidNameByAppid();hasOwnProperty$3.call(store._state.identities,a)&&(delete store._state.identities[a],delete store._state.openid,store.save())}unbind("$identity_mp_unionid",t)}}function bind(e,t){if(isNumber(t)){if(isInteger(t)&&!1===isSafeInteger(t))return log("Value must be String"),!1;t=String(t)}if(!isString(e))return log("Key must be String"),!1;var a=store.getHistoryLoginId(),i=a?a.name:"";return!check.checkKeyword(e)||isPresetIdKeys(e,[IDENTITY_KEY.LOGIN,i,"$mp_id","$identity_mp_id"])?(log("Key ["+e+"] is invalid"),!1):t&&""!==t?isString(t)?!!check.checkIdLength(t)&&(store._state.identities[e]=t,store.save(),void dataStage({type:"track_id_bind",event:"$BindID"})):(log("Value must be String"),!1):(log("Value is empty or null"),!1)}function unbind(e,t){if(isNumber(t)){if(isInteger(t)&&!1===isSafeInteger(t))return log("Value must be String"),!1;t=String(t)}if(!isString(e))return log("Key must be String"),!1;if(!sa._.check.checkKeyword(e)||isPresetIdKeys(e,[IDENTITY_KEY.LOGIN]))return log("Key ["+e+"] is invalid"),!1;if(!t||""===t)return log("Value is empty or null"),!1;if(!isString(t))return log("Value must be String"),!1;if(!sa._.check.checkIdLength(t))return!1;hasOwnProperty$3.call(store._state.identities,e)&&t===store._state.identities[e]&&("$mp_id"!==e&&"$identity_mp_id"!==e&&delete store._state.identities[e],store.save());var a=store.getDistinctId(),i=store.getFirstId();a===e+"+"+t&&(store.set("first_id",""),store.set("distinct_id",i),store.set("history_login_id",{name:"",value:""}));var r={};r[e]=t,dataStage({type:"track_id_unbind",event:"$UnbindID",unbind_value:r})}function setWebViewUrl(e,t){if(log("setWebViewUrl \u65b9\u6cd5\u5df2\u4ece 2022-9-23 \u5f00\u59cb\u5e9f\u5f03\uff0c\u8bf7\u5c3d\u5feb\u53bb\u9664\u8be5 API \u7684\u8c03\u7528\uff0c\u5e76\u4f7f\u7528 use \u63d2\u4ef6 \u4ee3\u66ff"),!isString(e)||""===e)return log("error:\u8bf7\u4f20\u5165\u6b63\u786e\u7684 URL \u683c\u5f0f"),!1;if(!/^http(s)?:\/\//.test(e))return log("warning: \u8bf7\u4f20\u5165\u6b63\u786e\u7684 URL \u683c\u5f0f"),!1;var a=/([^?#]+)(\?[^#]*)?(#.*)?/.exec(e);if(!a)return!1;var i,r=a[1]||"",n=a[2]||"",s=a[3]||"",o="",u=store.getDistinctId()||"",c=store.getFirstId()||"";urlSafeBase64&&urlSafeBase64.encode?u=u?urlSafeBase64.trim(urlSafeBase64.encode(urlBase64Encode(u))):"":rot13obfs&&(u=u?rot13obfs(u):""),u=encodeURIComponent(u);var p=c?"f"+u:"d"+u;t?(i=s.indexOf("_sasdk"),o=s.indexOf("?")>-1?i>-1?r+n+"#"+s.substring(1,i)+"_sasdk="+p:r+n+"#"+s.substring(1)+"&_sasdk="+p:r+n+"#"+s.substring(1)+"?_sasdk="+p):(i=n.indexOf("_sasdk"),o=/^\?(\w)+/.test(n)?i>-1?r+n.replace(/(_sasdk=)([^&]*)/gi,"_sasdk="+p)+s:r+"?"+n.substring(1)+"&_sasdk="+p+s:r+"?"+n.substring(1)+"_sasdk="+p+s);return o}function quick(){var e=arguments[0],t=arguments[1],a=arguments[2],i=isObject(a)?a:{};if("getAnonymousID"===e){if(!isEmptyObject(store._state))return store._state._first_id||store._state.first_id||store._state._distinct_id||store._state.distinct_id;log("\u8bf7\u5148\u521d\u59cb\u5316SDK")}else"appLaunch"===e||"appShow"===e?t?sa.autoTrackCustom[e](t,i):log("App\u7684launch\u548cshow\uff0c\u5728sensors.quick\u7b2c\u4e8c\u4e2a\u53c2\u6570\u5fc5\u987b\u4f20\u5165App\u7684options\u53c2\u6570"):"appHide"===e&&(i=isObject(t)?t:{},sa.autoTrackCustom[e](i))}function appLaunch(e,t){var a={};e&&e.scene?(meta.current_scene=e.scene,a.$scene=getMPScene(e.scene)):a.$scene="\u672a\u53d6\u5230\u503c",e&&e.scene&&1010===e.scene&&e.query&&(e.query.sampshare&&delete e.query.sampshare,delObjectKey(e.query)),e&&e.path&&(a.$url_path=getPath(e.path),a.$title=getPageTitle(e.path)),setShareInfo(e,a);var i=setUtm(e,a);meta.is_first_launch?(a.$is_first_time=!0,isEmptyObject(i.pre1)||sa.setOnceProfile(i.pre1)):a.$is_first_time=!1,setLatestChannel(i.pre2),setSfSource(e,a),sa.registerApp({$latest_scene:a.$scene}),a.$url_query=setQuery(e.query),a.$url=e.path+(a.$url_query?"?"+a.$url_query:""),setPageRefData(t),isObject(t)&&(a=extend(a,t)),sa.track("$MPLaunch",a)}function appShow(e,t){var a={};meta.mp_show_time=(new Date).getTime(),e&&e.scene?(meta.current_scene=e.scene,a.$scene=getMPScene(e.scene)):a.$scene="\u672a\u53d6\u5230\u503c",e&&e.scene&&1010===e.scene&&e.query&&(e.query.sampshare&&delete e.query.sampshare,delObjectKey(e.query)),e&&e.path&&(a.$url_path=getPath(e.path),a.$title=getPageTitle(e.path)),setShareInfo(e,a),setLatestChannel(setUtm(e,a).pre2),setSfSource(e,a),sa.registerApp({$latest_scene:a.$scene}),a.$url_query=setQuery(e.query),e&&e.path&&(a.$url=e.path+(a.$url_query?"?"+a.$url_query:"")),setPageRefData(a,e.path,a.$url_query),isObject(t)&&(a=extend(a,t)),sa.track("$MPShow",a)}function appHide(e){var t=(new Date).getTime(),a={};a.$url_path=getCurrentPath(),meta.mp_show_time&&t-meta.mp_show_time>0&&(t-meta.mp_show_time)/36e5<24&&(a.event_duration=(t-meta.mp_show_time)/1e3),setPageRefData(a),isObject(e)&&(a=extend(a,e)),sa.track("$MPHide",a),sa.sendStrategy.onAppHide()}function pageShow(e){var t={},a=getCurrentPath(),i=getPageTitle(a),r=getCurrentPage();i&&(t.$title=i),t.$url_path=a,t.$url_query=r.sensors_mp_url_query?r.sensors_mp_url_query:"",setPageSfSource(t=extend(t,getUtmFromPage())),setPageRefData(t),isObject(e)&&(t=extend(t,e)),sa.track("$MPViewScreen",t)}function setPara(e){sa.para=extend2Lev(saPara,e);var t=[];if(isArray(saPara.source_channel))for(var a=saPara.source_channel.length,i=0;i<a;i++)-1===" utm_source utm_medium utm_campaign utm_content utm_term sa_utm ".indexOf(" "+saPara.source_channel[i]+" ")&&t.push(saPara.source_channel[i]);saPara.source_channel=t,isObject(saPara.register)&&extend(meta.preset_properties,saPara.register),saPara.openid_url||(saPara.openid_url=saPara.server_url.replace(/([^\\\/])\/(sa)(\.gif){0,1}/,"$1/mp_login")),"number"!=typeof saPara.send_timeout&&(saPara.send_timeout=1e3);var r={send_timeout:6e3,max_length:6};e&&e.datasend_timeout||saPara.batch_send&&(saPara.datasend_timeout=1e4),!0===saPara.batch_send?saPara.batch_send=extend({},r):isObject(saPara.batch_send)&&(saPara.batch_send=extend({},r,saPara.batch_send));var n={share:!1,utm:!1};!0===saPara.is_persistent_save?(saPara.is_persistent_save=extend({},n),saPara.is_persistent_save.utm=!0):isObject(saPara.is_persistent_save)&&(saPara.is_persistent_save=extend({},n,saPara.is_persistent_save)),saPara.server_url?(saPara.preset_properties=isObject(saPara.preset_properties)?saPara.preset_properties:{},isObject(saPara.autotrack_exclude_page)||(saPara.autotrack_exclude_page={pageShow:[],pageLeave:[]}),isArray(saPara.autotrack_exclude_page.pageShow)||(saPara.autotrack_exclude_page.pageShow=[]),isArray(saPara.autotrack_exclude_page.pageLeave)||(saPara.autotrack_exclude_page.pageLeave=[]),saPara.sdk_id&&(saPara.storage_store_key+=saPara.sdk_id,saPara.storage_prepare_data_key+=saPara.sdk_id)):log("\u8bf7\u4f7f\u7528 setPara() \u65b9\u6cd5\u8bbe\u7f6e server_url \u6570\u636e\u63a5\u6536\u5730\u5740,\u8be6\u60c5\u53ef\u67e5\u770bhttps://www.sensorsdata.cn/manual/mp_sdk_new.html#112-%E5%BC%95%E5%85%A5%E5%B9%B6%E9%85%8D%E7%BD%AE%E5%8F%82%E6%95%B0")}function getServerUrl(){return saPara.server_url}var autoTrackCustom={trackCustom:function(e,t,a){var i=saPara.autoTrack[e],r="";saPara.autoTrack&&i&&("function"==typeof i?isObject(r=i())&&extend(t,r):isObject(i)&&(extend(t,i),saPara.autoTrack[e]=!0),sa.track(a,t))},appLaunch:function(e,t){if(!checkPrivacyStatus())return!1;if(!meta.initialState.isComplete)return meta.initialState.queue.push(["appLaunch",arguments]),meta.life_state.app_launched=!0,!1;meta.life_state.app_launched=!0;var a={};if(e&&e.scene?(meta.current_scene=e.scene,a.$scene=getMPScene(e.scene)):a.$scene="\u672a\u53d6\u5230\u503c",e&&e.scene&&1010===e.scene&&e.query&&(e.query.sampshare&&delete e.query.sampshare,delObjectKey(e.query)),e&&e.path&&(a.$url_path=getPath(e.path),a.$title=getPageTitle(e.path),e.query&&isObject(e.query))){var i=setQuery(e.query);i=i?"?"+i:"",a.$url=a.$url_path+i}setShareInfo(e,a);var r=setUtm(e,a);meta.is_first_launch?(a.$is_first_time=!0,isEmptyObject(r.pre1)||sa.setOnceProfile(r.pre1)):a.$is_first_time=!1,setLatestChannel(r.pre2),setSfSource(e,a),sa.registerApp({$latest_scene:a.$scene}),a.$url_query=setQuery(e.query),setPageRefData(a),t?(a=extend(a,t),sa.track("$MPLaunch",a)):saPara.autoTrack&&saPara.autoTrack.appLaunch&&sa.autoTrackCustom.trackCustom("appLaunch",a,"$MPLaunch")},appShow:function(e,t){var a={};meta.mp_show_time=(new Date).getTime(),e&&e.scene?(meta.current_scene=e.scene,a.$scene=getMPScene(e.scene)):a.$scene="\u672a\u53d6\u5230\u503c",e&&e.scene&&1010===e.scene&&e.query&&(e.query.sampshare&&delete e.query.sampshare,delObjectKey(e.query)),e&&e.path&&(a.$url_path=getPath(e.path),a.$title=getPageTitle(e.path)),setShareInfo(e,a),setLatestChannel(setUtm(e,a).pre2),setSfSource(e,a),sa.registerApp({$latest_scene:a.$scene}),a.$url_query=setQuery(e.query),setPageRefData(a,e.path,a.$url_query),e&&e.path&&(a.$url=e.path+(a.$url_query?"?"+a.$url_query:"")),t?(a=extend(a,t),sa.track("$MPShow",a)):saPara.autoTrack&&saPara.autoTrack.appShow&&sa.autoTrackCustom.trackCustom("appShow",a,"$MPShow")},appHide:function(e){var t=(new Date).getTime(),a={};a.$url_path=getCurrentPath(),meta.mp_show_time&&t-meta.mp_show_time>0&&(t-meta.mp_show_time)/36e5<24&&(a.event_duration=(t-meta.mp_show_time)/1e3),setPageRefData(a),e?(a=extend(a,e),sa.track("$MPHide",a)):saPara.autoTrack&&saPara.autoTrack.appHide&&sa.autoTrackCustom.trackCustom("appHide",a,"$MPHide")},pageLoad:function(e){meta.current_scene&&1010===meta.current_scene&&e&&(e.sampshare&&delete e.sampshare,delObjectKey(e)),e&&isObject(e)&&(this.sensors_mp_url_query=setQuery(e),this.sensors_mp_encode_url_query=setQuery(e,!0))},pageShow:function(){meta.page_show_time=Date.now();var e={},t=getCurrentPath(),a=getPageTitle(t);setRefPage(),e.$url_path=t,e.$url_query=this.sensors_mp_url_query?this.sensors_mp_url_query:"",setPageRefData(e=extend(e,getUtmFromPage())),setPageSfSource(e),a&&(e.$title=a),saPara.onshow?saPara.onshow(sa,t,this):-1===saPara.autotrack_exclude_page.pageShow.indexOf(t)&&sa.autoTrackCustom.trackCustom("pageShow",e,"$MPViewScreen")},pageShare:function(e){var t=e.onShareAppMessage;function a(e,t){return isObject(e)||(e={}),(isUndefined(e.path)||""===e.path)&&(e.path=getCurrentUrl(t)),isString(e.path)&&(-1===e.path.indexOf("?")?e.path=e.path+"?":"&"!==e.path.slice(-1)&&(e.path=e.path+"&")),e.path=e.path+getShareInfo(),e}function i(){if(saPara.autoTrack&&saPara.autoTrack.pageShare){var e={$url_path:getCurrentPath(),$share_depth:meta.query_share_depth,$share_method:meta.share_method};setPageRefData(e),sa.autoTrackCustom.trackCustom("pageShare",e,"$MPShare")}}isAsyncFunction(t)?e.onShareAppMessage=new Proxy(t,{apply:async function(e,t,r){meta.share_method="\u8f6c\u53d1\u6d88\u606f\u5361\u7247",i();var n=await e.apply(t,r);return sa.para.allow_amend_share_path&&(n=a(n,t)),n}}):e.onShareAppMessage=function(){var e=this;meta.share_method="\u8f6c\u53d1\u6d88\u606f\u5361\u7247";var r,n=t.apply(this,arguments);if(i(),sa.para.allow_amend_share_path&&isObject(n=a(n,e)))for(var s in n)if((r=n[s])&&isFunction(r.then)&&isFunction(r.catch))try{n[s]=n[s].then(function(t){return a(t,e)})}catch(e){log("onShareAppMessage: "+e)}return n}},pageShareTimeline:function(e){var t=e.onShareTimeline;e.onShareTimeline=function(){meta.share_method="\u670b\u53cb\u5708\u5206\u4eab";var e=t.apply(this,arguments);if(saPara.autoTrack&&saPara.autoTrack.pageShare){var a={$url_path:getCurrentPath(),$share_depth:meta.query_share_depth,$share_method:meta.share_method};setPageRefData(a),sa.autoTrackCustom.trackCustom("pageShare",a,"$MPShare")}return saPara.allow_amend_share_path&&("object"!=typeof e&&(e={}),"object"==typeof e&&void 0===e.query&&(e.query=""),"object"==typeof e&&"string"==typeof e.query&&""!==e.query&&"&"!==e.query.slice(-1)&&(e.query=e.query+"&"),e.query=e.query+getShareInfo()),e}},pageAddFavorites:function(){var e={};e.$url_path=getCurrentPath(),saPara.autoTrack&&saPara.autoTrack.mpFavorite&&sa.autoTrackCustom.trackCustom("mpFavorite",e,"$MPAddFavorites")},pageHide:function(){sa.para.autoTrack&&sa.para.autoTrack.pageLeave&&sendPageLeave()}};function sendPageLeave(){var e={},t="";try{t=(e=getCurrentPage())?e.route:""}catch(e){log(e)}if(meta.page_show_time>=0&&""!==t){var a={},i=getPageTitle(t),r=(Date.now()-meta.page_show_time)/1e3;(isNaN(r)||r<0)&&(r=0),a.$url_query=e.sensors_mp_url_query?e.sensors_mp_url_query:"",a.$url_path=t,a.$title=i,a.event_duration=r,-1===saPara.autotrack_exclude_page.pageLeave.indexOf(t)&&sa.track("$MPPageLeave",a),meta.page_show_time=-1}}var functions=Object.freeze({__proto__:null,setProfile:setProfile,setOnceProfile:setOnceProfile,appendProfile:appendProfile,incrementProfile:incrementProfile,track:track,identify:identify,resetAnonymousIdentity:resetAnonymousIdentity,trackSignup:trackSignup,login:login,loginWithKey:loginWithKey,getAnonymousID:getAnonymousID,getIdentities:getIdentities,logout:logout,getPresetProperties:getPresetProperties,bindOpenid:bindOpenid,unbindOpenid:unbindOpenid,setUnionid:setUnionid,unsetUnionid:unsetUnionid,bindUnionid:setUnionid,unbindUnionid:unsetUnionid,bind:bind,unbind:unbind,setWebViewUrl:setWebViewUrl,quick:quick,appLaunch:appLaunch,appShow:appShow,appHide:appHide,pageShow:pageShow,setPara:setPara,getServerUrl:getServerUrl,sendPageLeave:sendPageLeave,autoTrackCustom:autoTrackCustom,registerApp:registerApp,register:register,clearAllRegister:clearAllRegister,clearAppRegister:clearAppRegister,clearAllProps:clearAllProps});function buildAPI(e){for(var t in functions)e[t]=functions[t]}function setFirstVisitTime(){meta.is_first_launch&&sa.setOnceProfile({$first_visit_time:new Date})}function checkIsComplete(){meta.initialState.isComplete=!0,meta.initialState.queue.length>0&&(each(meta.initialState.queue,function(e){"appLaunch"===e[0]?sa.autoTrackCustom.appLaunch.apply(sa.autoTrackCustom,slice.call(e[1])):sa[e[0]].apply(sa,slice.call(e[1]))}),meta.initialState.queue=[])}function init(e){if(!0===meta.init_status)return!1;function t(){checkIsComplete(),checkAppLaunch(),sa.ee.sdk.emit("ready")}meta.init_status=!0,sa.ee.sdk.emit("beforeInit"),e&&isObject(e)&&sa.setPara(e),sa.ee.sdk.emit("initPara"),sa.ee.sdk.emit("afterInitPara"),sa.store.init(),sa.checkPluginInitStatus(),setFirstVisitTime(),sa.para.batch_send&&sa.sendStrategy.init();var a=[getNetworkType(),getSystemInfo()].concat(meta.promise_list);Promise.all(a).then(()=>{t()}).catch(()=>{t()})}function registerPropertyPlugin(e){isFunction(e.properties)?!e.isMatchedWithFilter||isFunction(e.isMatchedWithFilter)?sa.ee.data.on("finalAdjustData",function(t){try{isFunction(e.isMatchedWithFilter)?e.isMatchedWithFilter(t)&&e.properties(t):e.properties(t)}catch(e){log("execute registerPropertyPlugin callback error:"+e)}}):log("registerPropertyPlugin arguments error, isMatchedWithFilter must be function"):log("registerPropertyPlugin arguments error, properties must be function")}sa._=_,sa.modules={},sa.meta=meta,sa.kit=kit,sa.mergeStorageData=mergeStorageData,sa.dataStage=dataStage,sa.sendStrategy=sendStrategy,sa.store=store,sa.usePlugin=usePlugin,sa.use=use,sa.checkPluginInitStatus=checkPluginInitStatus,sa.eventSub=eventSub,sa.events=new eventEmitter,sa.ee=ee,sa.registerPropertyPlugin=registerPropertyPlugin,sa.enableDataCollect=enableDataCollect,sa.initialState=meta.initialState,sa.IDENTITY_KEY={EMAIL:IDENTITY_KEY.EMAIL,MOBILE:IDENTITY_KEY.MOBILE},buildAPI(sa),apiStaging(),setNavigationBarTitle(),networkStatusChange(),initAppGlobalName(),initAppShowHide(),initPageProxy(),sa.init=init;var base={plugin_version:"1.21.7"};function createPlugin(e){if("object"==typeof e&&"string"==typeof e.plugin_name&&""!==e.plugin_name)return e.plugin_version=base.plugin_version,e.log=e.log||function(){"object"==typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)},e;"object"==typeof console&&"function"==typeof console.error&&console.error('plugin must contain proprerty "plugin_name"')}var disableSDK={init(e){e.disableSDK=this.disableSDK.bind(this),e.enableSDK=this.enableSDK.bind(this),e.getDisabled=this.getDisabled.bind(this)},plugin_name:"DisableSDK",disabled:!1,disableSDK(){this.disabled=!0},enableSDK(){this.disabled=!1},getDisabled(){return this.disabled}},DisableSDK=createPlugin(disableSDK),oldOpenid={init(e){var t={getRequest:function(t){wx.login({success:function(a){a.code&&e.para.appid&&e.para.openid_url?e._.wxrequest({url:e.para.openid_url+"&code="+a.code+"&appid="+e.para.appid,method:"GET",complete:function(a){e._.isObject(a)&&e._.isObject(a.data)&&a.data.openid?t(a.data.openid):t()}}):t()}})},getWXStorage:function(){var t=e.store.getStorage();if(t&&e._.isObject(t))return t.openid},getOpenid:function(t){if(!e.para.appid)return t(),!1;var a=this.getWXStorage();a?t(a):this.getRequest(t)}};e.unsetOpenid=function(t){var a=e._.validId(t);if(!a)return!1;var i=e.store._state.openid;i===a&&e.store.set("openid","");var r=e._.getOpenidNameByAppid();if(Object.prototype.hasOwnProperty.call(e.store._state.identities,r)&&a===e.store._state.identities[r]){delete e.store._state.identities[r];var n=e.store.getFirstId(),s=e.store.getDistinctId(),o=e.store._state&&e.store._state.identities&&e.store._state.identities.$identity_mp_id;n&&n===i&&o&&e.store.change("first_id",o),s&&s===i&&o&&e.store.change("distinct_id",o),e.store.save()}},e.setOpenid=function(t){if(!(t=e._.validId(t)))return!1;if(!e.meta.init_status)return e.store.store_queue.push({method:"setOpenid",params:arguments}),!1;e.store.set("openid",t),e.identify(t);var a=e._.getOpenidNameByAppid();e.store._state.identities[a]=t,e.store.save()},e.initWithOpenid=function(a,i){(a=a||{}).appid&&(e.para.appid=a.appid),t.getOpenid(function(t){t&&e.setOpenid(t,a.isCoverLogin),i&&e._.isFunction(i)&&i(t),e.init(a)})}},plugin_name:"OldOpenid"},OldOpenid=createPlugin(oldOpenid),onceSend={init(e){e.kit.onceSend=function(t){t._flush_time=Date.now();var a=e.kit.onceTrackData(t),i=e.para.server_url+"?"+a;-1!==e.para.server_url.indexOf("?")&&(i=e.para.server_url+"&"+a),e._.wxrequest({url:i,method:"GET"})}},plugin_name:"OnceSend"},OnceSend=createPlugin(onceSend);sa.use(DisableSDK),sa.use(OldOpenid),sa.use(OnceSend);export default sa;
\ No newline at end of file
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
var sa = {
is_first_launch: false,
launched: false, // 需接口中也做调整,
_queue: [],
mpshow_time: null,
sa_referrer: '直接打开',
query_share_depth: 0,
share_distinct_id: '',
share_method: '',
current_scene: '',
inited: false
};
sa.para = {
// 神策分析数据接收地址
server_url: '',
//默认使用队列发数据时候,两条数据发送间的最大间隔
send_timeout: 1000,
// 是否允许控制台打印查看埋点数据(建议开启查看)
show_log: false,
// 是否允许修改onShareMessage里return的path,用来增加(用户id,分享层级,当前的path),在app onshow中自动获取这些参数来查看具体分享来源,层级等
allow_amend_share_path: true,
max_string_length: 500,
datasend_timeout: 3000,
source_channel: [],
batch_send: {
send_timeout: 6000,
max_length: 6
},
preset_properties: {}
};
sa.platform = '';
sa.lib = {
version: '0.14.21',
name: 'MiniGame',
method: 'code'
};
sa.properties = {
$lib: 'MiniGame',
$lib_version: '0.14.21'
};
sa.currentProps = {};
/*
* @Date: 2022-06-09 11:36:17
* @File:
*/
var SOURCE_CHANNEL_STANDARD = 'utm_source utm_medium utm_campaign utm_content utm_term';
var LATEST_SOURCE_CHANNEL = ['$latest_utm_source', '$latest_utm_medium', '$latest_utm_campaign', '$latest_utm_content', '$latest_utm_term', '$latest_sa_utm'];
var LATEST_SHARE_INFO = ['$latest_share_distinct_id', '$latest_share_url_path', '$latest_share_depth', '$latest_share_method'];
var IDENTITY_KEY = {
EMAIL: '$identity_email',
MOBILE: '$identity_mobile',
LOGIN: '$identity_login_id'
};
var IDENTITIES = {}; //ID3 用户相关的配置
var RESERVE_CHANNEL = ' utm_source utm_medium utm_campaign utm_content utm_term sa_utm ';
var REQUEST = {};
var identity_id = '$identity_xhs_mp_id';
IDENTITIES.identity_unionid = '';
IDENTITIES.identity_id = identity_id; //配置平台默认匿名 ID
IDENTITIES.openid_name = 'xhs'; //配置平台 name
IDENTITIES.bind_preset_id = [identity_id]; //配置 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
IDENTITIES.unbind_without_check = [identity_id]; //unbindWithoutCheck 过滤 ID 配置
IDENTITIES.login_preset_id = [identity_id]; //loginWithKey 预设ID 校验
REQUEST.header = { 'Content-Type': 'text/plain' };
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
const _toString = Object.prototype.toString,
_hasOwnProperty = Object.prototype.hasOwnProperty,
indexOf = Array.prototype.indexOf,
slice = Array.prototype.slice,
_isArray = Array.prototype.isArray,
forEach = Array.prototype.forEach,
bind = Function.prototype.bind;
function isUndefined(obj) {
return obj === void 0;
}
function isString(obj) {
return _toString.call(obj) == '[object String]';
}
function isDate(obj) {
return _toString.call(obj) == '[object Date]';
}
function isBoolean(obj) {
return _toString.call(obj) == '[object Boolean]';
}
function isNumber(obj) {
return _toString.call(obj) == '[object Number]' && /[\d\\.]+/.test(String(obj));
}
function isJSONString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function isObject(obj) {
if (obj == null) {
return false;
} else {
return _toString.call(obj) === '[object Object]';
}
}
function isPlainObject(obj) {
return _toString.call(obj) === '[object Object]';
}
function isArray(obj) {
return _isArray || _toString.call(obj) === '[object Array]';
}
function isFuction(f) {
try {
return /^\s*\bfunction\b/.test(f);
} catch (x) {
return false;
}
}
function isArguments(obj) {
return !!(obj && _hasOwnProperty.call(obj, 'callee'));
}
function toString(val) {
return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val);
}
function each(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach && obj.forEach === forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
function toArray(iterable, start) {
if (!iterable) {
return [];
}
var ret = [];
if (iterable.toArray) {
ret = iterable.toArray();
}
if (isArray(iterable)) {
ret = slice.call(iterable);
}
if (isArguments(iterable)) {
ret = slice.call(iterable);
}
ret = values(iterable);
if (start && isNumber(start)) {
ret = ret.slice(start);
}
return ret;
}
function values(obj) {
var results = [];
if (obj == null) {
return results;
}
each(obj, function (value) {
results[results.length] = value;
});
return results;
}
// include 函数,如果对象包含属性,就返回空对象 {}
function include(obj, target) {
var found = false;
if (obj == null) {
return found;
}
if (indexOf && obj.indexOf === indexOf) {
return obj.indexOf(target) != -1;
}
each(obj, function (value) {
if (found || (found = value === target)) {
return {};
}
});
return found;
}
function unique(arr) {
var temp,
n = [],
o = {};
for (var i = 0; i < arr.length; i++) {
temp = arr[i];
if (!o[temp]) {
o[temp] = true;
n.push(temp);
}
}
return n;
}
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function formatDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds());
}
function searchObjDate(o) {
if (isObject(o) || isArray(o)) {
each(o, function (a, b) {
if (isObject(a) || isArray(a)) {
searchObjDate(o[b]);
} else {
if (isDate(a)) {
o[b] = formatDate(a);
}
}
});
}
}
function trim(str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
function isFunction(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
// 浅复制
function extend(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
// 深复制
function extend2Lev(obj) {
each(slice.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0 && source[prop] !== null) {
if (isObject(source[prop]) && isObject(obj[prop])) {
extend(obj[prop], source[prop]);
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
}
function isEmptyObject(obj) {
if (isObject(obj)) {
for (var key in obj) {
if (_hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
return false;
}
/**
* 深复制对象
* @param {object} obj
* @returns
*/
function deepCopy(obj) {
var temp = {};
function deepClone(target, source) {
for (var k in source) {
var item = source[k];
if (isArray(item)) {
target[k] = [];
deepClone(target[k], item);
} else if (isObject(item)) {
target[k] = {};
deepClone(target[k], item);
} else {
target[k] = item;
}
}
}
deepClone(temp, obj);
return temp;
}
function formatString(str) {
if (str.length > sa.para.max_string_length) {
sa.log('字符串长度超过限制,已经做截取--' + str);
return str.slice(0, sa.para.max_string_length);
} else {
return str;
}
}
function searchObjString(o) {
if (isObject(o)) {
each(o, function (a, b) {
if (isObject(a)) {
searchObjString(o[b]);
} else {
if (isString(a)) {
o[b] = formatString(a);
}
}
});
}
}
function encodeDates(obj) {
each(obj, function (v, k) {
if (isDate(v)) {
obj[k] = formatDate(v);
} else if (isObject(v)) {
obj[k] = encodeDates(v);
}
});
return obj;
}
function utf8Encode(string) {
string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var utftext = '',
start,
end;
var stringl = 0,
n;
start = end = 0;
stringl = string.length;
for (n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
}
function base64Encode(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = utf8Encode(data);
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = (o1 << 16) | (o2 << 8) | o3;
h1 = (bits >> 18) & 0x3f;
h2 = (bits >> 12) & 0x3f;
h3 = (bits >> 6) & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}
return enc;
}
/*
* @Date: 2022-11-01 19:18:40
* @File:
*/
function _decodeURIComponent(val) {
var result = '';
try {
result = decodeURIComponent(val);
} catch (e) {
result = val;
}
return result;
}
/*
* @Date: 2022-08-12 14:18:53
* @File: 内部使用全局变量
*/
var meta = {
lib_version: '',
launched: false, // 需接口中也做调整,
lib_name: '',
query_share_depth: 0,
page_show_time: Date.now(), //页面停留时长
mp_show_time: null, //小程序停留时长
promise_list: [],
current_scene: '',
is_first_launch: false,
_queue: [],
inited: false,
hasExeInit: false,
scene_prefix: '', //场景值
share_distinct_id: '',
sa_referrer: '直接打开',
source_channel_standard: SOURCE_CHANNEL_STANDARD,
latest_source_channel: LATEST_SOURCE_CHANNEL,
latest_share_info: LATEST_SHARE_INFO
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getAppId() {
var info = sa.system_api.getAppInfoSync();
if (info && info.appId) {
return info.appId;
}
return '';
}
/*
* @Date: 2022-08-19 15:15:42
* @File: 业务相关模块
*/
function getObjFromQuery(str) {
var query = str.split('?');
var arr = [];
var obj = {};
if (query && query[1]) {
each(query[1].split('&'), function (value) {
arr = value.split('=');
if (arr[0] && arr[1]) {
obj[arr[0]] = arr[1];
}
});
} else {
return {};
}
return obj;
}
// 从query,q,scene三个参数中,解析得到一个整合的query对象
function getMixedQuery(para) {
var obj = detectOptionQuery(para);
var scene = obj.scene;
var q = obj.q;
// query
var query = obj.query;
for (var i in query) {
query[i] = _decodeURIComponent(query[i]);
}
// scene
if (scene) {
scene = _decodeURIComponent(scene);
if (scene.indexOf('?') !== -1) {
scene = '?' + scene.replace(/\?/g, '');
} else {
scene = '?' + scene;
}
extend(query, getObjFromQuery(scene));
}
// 普通二维码的q
if (q) {
extend(query, getObjFromQuery(_decodeURIComponent(q)));
}
return query;
}
// 筛选检测出para里的query,q,scene
function detectOptionQuery(para) {
if (!para || !isObject(para.query)) {
return {};
}
var result = {};
// path的query
result.query = extend({}, para.query);
function isBScene(obj) {
var source = ['utm_source', 'utm_content', 'utm_medium', 'utm_campaign', 'utm_term', 'sa_utm'];
var source_keyword = source.concat(sa.para.source_channel);
var reg = new RegExp('(' + source_keyword.join('|') + ')%3D', 'i');
var keys = Object.keys(obj);
if (keys.length === 1 && keys[0] === 'scene' && reg.test(obj.scene)) {
return true;
} else {
return false;
}
}
//如果query有scene,认为scene是b接口传过来的
if (isString(result.query.scene) && isBScene(result.query)) {
result.scene = result.query.scene;
delete result.query.scene;
}
//如果query有q
if (para.query.q && para.query.scancode_time && String(para.scene).slice(0, 3) === '101') {
result.q = String(result.query.q);
delete result.query.q;
delete result.query.scancode_time;
}
return result;
}
// 解析参数中的utm,并添加
function setUtm(para, prop) {
var utms = {};
var query = getMixedQuery(para);
var pre1 = getCustomUtmFromQuery(query, '$', '_', '$');
var pre2 = getCustomUtmFromQuery(query, '$latest_', '_latest_', '$latest_');
utms.pre1 = pre1;
utms.pre2 = pre2;
extend(prop, pre1);
return utms;
}
function setLatestChannel(channel) {
if (!isEmptyObject(channel)) {
if (includeChannel(channel, LATEST_SOURCE_CHANNEL)) {
sa.clearAppRegister(LATEST_SOURCE_CHANNEL);
}
sa.registerApp(channel);
}
function includeChannel(channel, arr) {
var found = false;
for (var i in arr) {
if (channel[arr[i]]) {
found = true;
}
}
return found;
}
}
// 从参数中解析来源参数
function getCustomUtmFromQuery(query, utm_prefix, source_channel_prefix, sautm_prefix) {
if (!isObject(query)) {
return {};
}
var result = {};
if (query['sa_utm']) {
for (var i in query) {
if (i === 'sa_utm') {
result[sautm_prefix + i] = query[i];
continue;
}
if (include(sa.para.source_channel, i)) {
result[source_channel_prefix + i] = query[i];
}
}
} else {
for (var k in query) {
if ((' ' + SOURCE_CHANNEL_STANDARD + ' ').indexOf(' ' + k + ' ') !== -1) {
result[utm_prefix + k] = query[k];
continue;
}
if (include(sa.para.source_channel, k)) {
result[source_channel_prefix + k] = query[k];
}
}
}
return result;
}
// 是否已经存在 latest utm
function existLatestUtm() {
var exit = false;
each(LATEST_SOURCE_CHANNEL, function (value) {
if (sa.properties[value]) {
exit = true;
}
});
return exit;
}
// query 解析
function setQuery(params, isEncode) {
var url_query = '';
if (params && isObject(params) && !isEmptyObject(params)) {
var arr = [];
each(params, function (value, item) {
// 防止传统二维码的para.q这种异常query。另外异常的para.scene 不好判断,直接去掉。建议不要使用这个容易异意的参数
if (!(item === 'q' && isString(value) && value.indexOf('http') === 0)) {
if (isEncode) {
arr.push(item + '=' + value);
} else {
arr.push(item + '=' + _decodeURIComponent(value));
}
}
});
return arr.join('&');
} else {
return url_query;
}
}
function getCurrentPage() {
var obj = {};
try {
var pages = isFunction(sa.system_api.getCurrentPages) ? sa.system_api.getCurrentPages() : getCurrentPages();
obj = pages[pages.length - 1];
} catch (e) {
sa.log('getCurrentPage:' + e);
}
return obj;
}
function getCurrentPath() {
var url = '未取到';
try {
var currentPage = getCurrentPage();
url = currentPage ? currentPage.route : url;
} catch (e) {
sa.log('getCurrentPath:' + e);
}
return url;
}
/**
* 判断是否为预置的 ID key,可以通过 ids 传入 id key 的列表,自定义预置的 key 值
* @param {string} name
* @param {array} ids
* @returns {boolean}
*/
function isPresetIdKeys(name, ids) {
// 预置 ID key 列表
var keyList = ['$identity_anonymous_id'];
if (isArray(ids)) {
keyList = keyList.concat(ids);
}
for (var item of keyList) {
if (item === name) {
return true;
}
}
return false;
}
/**
* 判断是否为安全整数类型
*/
var isSafeInteger =
Number.isSafeInteger ||
function (value) {
return isInteger(value) && Math.abs(value) <= Math.pow(2, 53) - 1;
};
/**
* 判断是否为整数类型
*/
var isInteger =
Number.isInteger ||
function (value) {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
};
var check = {
// 检查关键字
checkKeyword: function (para) {
var reg = /^((?!^distinct_id$|^original_id$|^device_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i;
return reg.test(para);
},
// 检查 id 字符串长度
checkIdLength: function (str) {
var temp = String(str);
if (temp.length > 255) {
sa.log('id 长度超过 255 个字符!');
return false;
}
return true;
}
};
/**
*
* @param {*} app 表示不同小程序平台
* @returns 返回 ID
*/
function getOpenidNameByAppid(app) {
if (app == '' || !isString(app)) {
sa.log('error: 参数必须是有效值');
return false;
}
var appid = getAppId();
var _identity = '$identity_';
var _openid = '_openid';
var name = _identity + app + _openid;
if (appid) {
name = _identity + app + '_' + appid + _openid;
}
return name;
}
function validId(id) {
if ((!isString(id) && !isNumber(id)) || id === '') {
sa.log('输入 ID 类型错误');
return false;
}
if (isNumber(id)) {
id = String(id);
if (!/^\d+$/.test(id)) {
sa.log('输入 ID 类型错误');
return false;
}
}
if (!check.checkIdLength(id)) {
return false;
}
return id;
}
/**
* 判断是否为新的 login id
* @param {*} name
* @param {*} id
* @returns
*/
function isNewLoginId(name, id) {
// 当当前 ID 的 name 与上一个登录 ID 的 name 相同,且当前 ID 值与上一个 ID 的值相同时,则认为是同一个 ID,否则是一个新的 ID
// return !(name === store._state.history_login_id.name && store._state.history_login_id.value === id);
// 判断当前 ID 的 name 是否和上一个 ID 的 name 值相同,若不相同,则继续判断 id 值
if (name === sa.store._state.history_login_id.name) {
if (sa.store._state.history_login_id.value === id) {
return false;
}
}
return true;
}
/**
* 判断是否和匿名 id 相同
* @param {*} id
*/
function isSameAndAnonymousID(id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (firstId) {
return id === firstId;
} else {
return id === distinctId;
}
}
/**
* 字符串转换成大写
* value 必须是字符串
*/
function setUpperCase(value) {
if (isString(value)) {
return value.toLocaleUpperCase();
}
return value;
}
// 获取是否首日访问属性
function getIsFirstDay() {
if (typeof sa.store._state === 'object' && isNumber(sa.store._state.first_visit_day_time) && sa.store._state.first_visit_day_time > new Date().getTime()) {
return true;
} else {
return false;
}
}
function getPresetProperties() {
if (sa.properties && sa.properties.$lib) {
var builtinProps = {};
each(sa.properties, function (value, item) {
if (item.indexOf('$') === 0) {
builtinProps[item] = value;
}
});
var propertyObj = {
$url_path: getCurrentPath(),
$is_first_day: getIsFirstDay(),
$is_first_time: meta.is_first_launch
};
var obj = extend(builtinProps, propertyObj, sa.properties, sa.store.getProps());
delete obj.$lib;
return obj;
} else {
return {};
}
}
/**
* 拼接 URL
* @param {URL path} path
* @param {URL query} query
* @returns
*/
function joinUrl(path, query) {
if (!path) {
return false;
}
if (path === '未取到') {
return '未取到';
}
if (!query) {
return path;
} else {
return path + '?' + query;
}
}
// 统一path的格式
function getPath(path) {
if (isString(path)) {
path = path.replace(/^\//, '');
} else {
path = '取值异常';
}
return path;
}
/**
* 获取页面
* @param {app 生命周期参数} para
* @returns
*/
function getAppProps(para) {
var prop = {};
if (para && para.path) {
prop.$url_path = getPath(para.path);
prop.$url_query = setQuery(para.query);
prop.$url = joinUrl(prop.$url_path, prop.$url_query);
}
return prop;
}
/**
*
* @returns
*/
function getPageProps() {
var pages = getCurrentPage();
var path = getCurrentPath();
var query = pages.sensors_mp_url_query || '';
var url = joinUrl(path, query);
return {
$url_path: path,
$url: url,
$url_query: query
};
}
/*
* @Date: 2022-07-05 12:07:14
* @File:
*/
/**
* De-obfuscate an obfuscated string with the method above.
*/
function rot13defs(str) {
var code_len = 13,
n = 126;
str = String(str);
return rot13obfs(str, n - code_len);
}
/**
* Obfuscate a plaintext string with a simple rotation algorithm similar to
* the rot13 cipher.
*/
function rot13obfs(str, code_len) {
str = String(str);
code_len = typeof code_len === 'number' ? code_len : 13;
var n = 126;
var chars = str.split('');
for (var i = 0, len = chars.length; i < len; i++) {
var c = chars[i].charCodeAt(0);
if (c < n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + code_len) % n);
}
}
return chars.join('');
}
var decodeURIComponent$1 = _decodeURIComponent;
function formatSystem(system) {
var _system = system.toLowerCase();
if (_system === 'ios') {
return 'iOS';
} else if (_system === 'android') {
return 'Android';
} else {
return system;
}
}
/**
* 返回 rand 方法
* @param {number} 10^19 必传参数
* @return {number}
*/
var getRandomBasic = (function () {
var today = new Date();
var seed = today.getTime();
function rnd() {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280.0;
}
return function rand(number) {
return Math.ceil(rnd() * number);
};
})();
/**
* 生成一个随机数
* @return {number}
*/
function getRandom() {
if (typeof Uint32Array === 'function') {
var cry = '';
if (typeof crypto !== 'undefined') {
cry = crypto;
} else if (typeof msCrypto !== 'undefined') {
cry = msCrypto;
}
if (isObject(cry) && cry.getRandomValues) {
var typedArray = new Uint32Array(1);
var randomNumber = cry.getRandomValues(typedArray)[0];
var integerLimit = Math.pow(2, 32);
return randomNumber / integerLimit;
}
}
return getRandomBasic(10000000000000000000) / 10000000000000000000;
}
function getUUID() {
return (
'' +
Date.now() +
'-' +
Math.floor(1e7 * getRandom()) +
'-' +
getRandom().toString(16).replace('.', '') +
'-' +
String(getRandom() * 31242)
.replace('.', '')
.slice(0, 8)
);
}
const _ = {
getUUID,
formatSystem,
indexOf,
slice,
forEach,
bind,
_hasOwnProperty,
_toString,
isUndefined,
isString,
isDate,
isBoolean,
isNumber,
isJSONString,
isObject,
isPlainObject,
isArray,
isFuction,
isArguments,
toString,
unique,
include,
values,
toArray,
each,
formatDate,
searchObjDate,
utf8Encode,
decodeURIComponent: decodeURIComponent$1,
encodeDates,
base64Encode,
trim,
isFunction,
extend,
extend2Lev,
isEmptyObject,
searchObjString,
formatString,
setLatestChannel,
getObjFromQuery,
getMixedQuery,
detectOptionQuery,
setUtm,
getCustomUtmFromQuery,
existLatestUtm,
setQuery,
getCurrentPage,
getCurrentPath,
rot13defs,
rot13obfs,
isSafeInteger,
isInteger,
isPresetIdKeys,
deepCopy,
check,
getOpenidNameByAppid,
validId,
isNewLoginId,
isSameAndAnonymousID,
setUpperCase,
getIsFirstDay,
getPageProps,
getAppProps,
getPath,
joinUrl,
getPresetProperties
};
/*
* @Date: 2022-12-15 09:54:58
* @File:
*/
function stripProperties(p) {
if (!isObject(p)) {
return p;
}
each(p, function (v, k) {
// 如果是数组,把值自动转换成string
if (isArray(v)) {
var temp = [];
each(v, function (arrv) {
if (isString(arrv)) {
temp.push(arrv);
} else if (isUndefined(arrv)) {
temp.push('null');
} else {
try {
temp.push(JSON.stringify(arrv));
} catch (error) {
sa.log('您的数据 - ' + k + ':' + v + ' - 的数组里的值有错误,已经将其删除');
}
}
});
p[k] = temp;
}
//如果是多层结构对象,直接序列化为字符串
if (isObject(v)) {
try {
p[k] = JSON.stringify(v);
} catch (error) {
delete p[k];
sa.log('您的数据 - ' + k + ':' + v + ' - 的数据值有错误,已经将其删除');
}
} else if (!(isString(v) || isNumber(v) || isDate(v) || isBoolean(v) || isArray(v))) {
// 只能是字符串,数字,日期,布尔,数组
sa.log('您的数据 - ', v, '-格式不满足要求,我们已经将其删除');
delete p[k];
}
});
return p;
}
// 处理动态公共属性
function parseSuperProperties(obj) {
if (isObject(obj)) {
each(obj, function (value, item) {
if (isFunction(value)) {
try {
obj[item] = value();
if (isFunction(obj[item])) {
sa.log('您的属性 - ' + item + ' 格式不满足要求,我们已经将其删除');
delete obj[item];
}
} catch (e) {
delete obj[item];
sa.log('您的属性 - ' + item + ' 抛出了异常,我们已经将其删除');
}
}
});
}
}
/*
* @Date: 2022-10-13 18:04:01
* @File: 批量发送数据发送模块
*/
function batchRequest(option) {
if (isArray(option.data) && option.data.length > 0) {
var now = Date.now(),
timeout = sa.para.datasend_timeout;
option.data.forEach(function (v) {
v._flush_time = now;
});
option.data = JSON.stringify(option.data);
let params = {
url: sa.para.server_url,
method: 'POST',
dataType: 'text',
data: 'data_list=' + encodeURIComponent(base64Encode(option.data)),
timeout: timeout,
success: function () {
option.success(option.len);
},
fail: function () {
option.fail();
}
};
if (REQUEST.header) {
params.header = REQUEST.header;
}
sa.system_api.request(params);
} else {
option.success(option.len);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-10-12 17:36:49
* @File: 单条发送
*/
function onceSend(data) {
data._flush_time = Date.now();
var url = '';
var str_t = JSON.stringify(data);
if (sa.para.server_url.indexOf('?') !== -1) {
url = sa.para.server_url + '&data=' + encodeURIComponent(base64Encode(str_t));
} else {
url = sa.para.server_url + '?data=' + encodeURIComponent(base64Encode(str_t));
}
var timeout = sa.para.datasend_timeout;
sa.system_api.request({
url: url,
dataType: 'text',
method: 'GET',
timeout: timeout
});
}
/*
* @Date: 2022-11-01 21:18:52
* @File: 批量发送 & 单条发送 模块
*/
var kit = {
batchRequest: batchRequest,
onceSend: onceSend
};
/**
* 批量发送
*/
sa.batch_state = {
mem: [],
changed: false,
sended: true,
is_first_batch_write: true,
sync_storage: false, // 在初始化时将 storage 存的数据同步到当前暂存队列中的操作是否完成
failTime: 0, // 发送数据失败次数
getLength: function () {
return this.mem.length;
},
add: function (data) {
this.mem.push(data);
},
clear: function (len) {
this.mem.splice(0, len);
}
};
function onAppHide() {
if (isFunction(sa.platform_obj.onAppHide)) {
sa.platform_obj.onAppHide(function () {
if (sa.para.batch_send) {
batchSend();
}
});
}
}
function batchSend() {
if (sa.batch_state.sended) {
var data,
len,
mData = sa.batch_state.mem;
if (mData.length >= 100) {
data = mData.slice(0, 100);
} else {
data = mData;
}
len = data.length;
if (len > 0) {
sa.batch_state.sended = false;
kit.batchRequest({
data: data,
len: len,
success: batchRemove,
fail: sendFail
});
}
}
}
function sendFail() {
sa.batch_state.sended = true;
sa.batch_state.failTime++;
}
function batchRemove(len) {
sa.batch_state.clear(len);
sa.batch_state.sended = true;
sa.batch_state.changed = true;
batchWrite();
sa.batch_state.failTime = 0;
}
function batchWrite() {
if (sa.batch_state.changed) {
// 如果是首次写入数据,等待1s后,优先发送,优化那些来了就跑的人
if (sa.batch_state.is_first_batch_write) {
sa.batch_state.is_first_batch_write = false;
setTimeout(function () {
batchSend();
}, 1000);
}
if (sa.batch_state.syncStorage) {
sa.system_api.setStorageSync('sensors_prepare_data', sa.batch_state.mem);
sa.batch_state.changed = false;
}
}
}
sa.batchWrite = batchWrite;
function batchInterval() {
// 每隔1秒,写入数据
function loopWrite() {
setTimeout(function () {
batchWrite();
loopWrite();
}, 1000);
}
// 默认每隔6秒,发送数据
function loopSend() {
setTimeout(function () {
batchSend();
loopSend();
}, sa.para.batch_send.send_timeout * Math.pow(2, sa.batch_state.failTime));
}
loopWrite();
loopSend();
}
sa.prepareData = function (p) {
var data = {
distinct_id: sa.store.getDistinctId(),
lib: {
$lib: sa.lib.name,
$lib_method: sa.lib.method,
$lib_version: String(sa.lib.version)
},
properties: {}
};
//兼容是否有 ID3 的小程序
if (isObject(sa.store._state.identities)) {
data.identities = extend({}, sa.store.getIdentities());
}
// unbind 额外属性修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
data.identities = _.deepCopy(p.unbind_value);
delete p.unbind_value;
}
extend(data, sa.store.getUnionId(), p);
// 合并properties里的属性
if (isObject(p.properties) && !isEmptyObject(p.properties)) {
extend(data.properties, p.properties);
}
// unbind 额外id修改
if (p.type === 'track_id_unbind' && p.event === '$UnbindID') {
if (data.login_id) {
delete data.login_id;
}
if (data.anonymous_id) {
delete data.anonymous_id;
}
}
// profile时不传公用属性
if (!p.type || p.type.slice(0, 7) !== 'profile') {
data._track_id = Number(String(getRandom()).slice(2, 5) + String(getRandom()).slice(2, 4) + String(Date.now()).slice(-4));
// 传入的属性 > 当前页面的属性 > session的属性 > cookie的属性 > 预定义属性
data.properties = extend({}, sa.properties, sa.store.getProps(), sa.currentProps, data.properties);
// 当上报的是事件的数据设置 $is_first_day 属性,对于上报用户属性相关的事件均不上报 $is_first_day 属性
if (p.type === 'track') {
data.properties.$is_first_day = getIsFirstDay();
}
}
if (data.properties.$time && isDate(data.properties.$time)) {
data.time = data.properties.$time * 1;
delete data.properties.$time;
} else {
data.time = new Date() * 1;
}
sa.ee.data.emit('beforeBuildCheck', data);
parseSuperProperties(data.properties);
searchObjDate(data);
stripProperties(data.properties);
searchObjString(data);
sa.ee.data.emit('finalAdjustData', data);
if (!sa.para.server_url) {
return false;
}
sa.log(data);
sa.send(data);
};
sa.send = function (t) {
// t._nocache = (String(getRandom()) + String(getRandom()) + String(getRandom())).slice(2, 15);
if (sa.storageName === 'sensorsdata2015_binance') {
if (sa.para.data_report_type === 'native') {
reportEvent(t);
return false;
}
}
if (sa.para.batch_send) {
if (sa.batch_state.getLength() >= 500) {
sa.log('数据量存储过大,有异常');
sa.batch_state.mem.shift();
}
sa.batch_state.add(t);
sa.batch_state.changed = true;
if (sa.batch_state.getLength() >= sa.para.batch_send.max_length) {
batchSend();
}
} else {
kit.onceSend(t);
}
};
function reportEvent(data) {
var event_name_prefix = 'sensors_';
var event_name = '';
data._flush_time = Date.now();
if (data.event) {
event_name = event_name_prefix + data.event;
} else {
event_name = event_name_prefix + data.type;
}
data.dataSource = 'sensors';
sa.log('report_event, name: ', event_name, '-- key: ', data);
__mp_private_api__.reportEvent(event_name, data);
}
// request 直接调用 sa.request
sa.log = function () {
if (sa.para.show_log) {
if (typeof console === 'object' && console.log) {
try {
var arg = Array.prototype.slice.call(arguments);
return console.log.apply(console, arg);
} catch (e) {
console.log(arguments[0]);
}
}
}
};
sa.track = function (e, p, c) {
sa.prepareData(
{
type: 'track',
event: e,
properties: p
},
c
);
};
sa.setProfile = function (p) {
sa.prepareData({
type: 'profile_set',
properties: p
});
};
sa.setOnceProfile = function (p, c) {
sa.prepareData(
{
type: 'profile_set_once',
properties: p
},
c
);
};
sa.login = function (id) {
var firstId = sa.store.getFirstId();
var distinctId = sa.store.getDistinctId();
if (id !== distinctId) {
if (firstId) {
sa.trackSignup(id, '$SignUp');
} else {
sa.store.set('first_id', distinctId);
sa.trackSignup(id, '$SignUp');
}
}
};
sa.logout = function (isChangeId) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', '');
if (isChangeId === true) {
sa.store.set('distinct_id', getUUID());
} else {
sa.store.set('distinct_id', firstId);
}
} else {
sa.log('没有first_id,logout失败');
}
};
sa.identify = function (id) {
id = _.validId(id);
if (id) {
var firstId = sa.store.getFirstId();
if (firstId) {
sa.store.set('first_id', id);
} else {
sa.store.set('distinct_id', id);
}
}
};
/**
*
* @param {object} idObj 分别为 id: id 值、event_name: 事件名、id_name: 自定义 ID 的 name
* @param {*} e 事件类型
* @param {*} p 数据
* 原传参方式通过 4 个参数来实现,但使用过程中并未传入 p 和 c 参数,故不做处理
* 兼容原有 ID 处理逻辑,判断第一个参数是否为一个对象,是对象则为新 3.0 的接口,需要按 3.0 的传参逻辑进行参数获取
* 在现逻辑中为了不修改老 3.0 中调用 trackSignup 逻辑,若登录 ID key 为默认的 $identity_login_id 则不传 idName 参数
*/
sa.trackSignup = function (idObj, e, p) {
var currentId, eventName, idName, distinctId, originalId;
if (isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
sa.store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
originalId = sa.store.getFirstId() || sa.store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
};
sa.registerApp = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.currentProps = extend(sa.currentProps, obj);
}
};
sa.clearAppRegister = function (arr) {
if (isArray(arr)) {
each(sa.currentProps, function (value, key) {
if (include(arr, key)) {
delete sa.currentProps[key];
}
});
}
};
sa.register = function (obj) {
if (isObject(obj) && !isEmptyObject(obj)) {
sa.store.setProps(obj);
}
};
sa.clearAllRegister = function () {
sa.store.setProps({}, true);
};
sa.use = function (plugin) {
const args = toArray(arguments, 1);
args.unshift(this);
if (isObject(plugin) && isFunction(plugin.init)) {
plugin.init.apply(plugin, args);
}
return plugin;
};
// sa 上挂载 use & usePlugin 保持小程序插件使用 API 的统一
sa.usePlugin = sa.use;
sa.getServerUrl = function () {
return sa.para.server_url;
};
sa.registerPropertyPlugin = function (arg) {
if (!isFunction(arg.properties)) {
sa.log('registerPropertyPlugin arguments error, properties must be function');
return;
}
if (arg.isMatchedWithFilter && !isFunction(arg.isMatchedWithFilter)) {
sa.log('registerPropertyPlugin arguments error, isMatchedWithFilter must be function');
return;
}
sa.ee.data.on('finalAdjustData', function (data) {
try {
if (isFunction(arg.isMatchedWithFilter)) {
arg.isMatchedWithFilter(data) && arg.properties(data);
} else {
arg.properties(data);
}
} catch (e) {
sa.log('execute registerPropertyPlugin callback error:' + e);
}
});
};
/*
* @Date: 2022-11-01 19:03:46
* @File: 用户生态系统 通用版本
*/
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var store = {
inited: true,
// 防止重复请求
storageInfo: null,
store_queue: [],
getStorage: function () {
if (this.storageInfo) {
return this.storageInfo;
} else {
this.storageInfo = sa.system_api.getStorageSync(sa.storageName) || '';
return this.storageInfo;
}
},
_state: {},
getUUID: function () {
return getUUID();
},
toState: function (ds) {
var state = null;
var _this = this;
function isStateDistinctId() {
if (state.distinct_id) {
_this._state = state;
} else {
_this.set('distinct_id', getUUID());
}
}
if (isJSONString(ds)) {
state = JSON.parse(ds);
isStateDistinctId();
} else if (isObject(ds)) {
state = ds;
isStateDistinctId();
} else {
this.set('distinct_id', getUUID());
}
// 在初始化同步 storage ID 属性到内存中时,将对应的 identities 对象进行处理
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this._state._distinct_id || this._state.distinct_id;
var history_login_id = this._state.history_login_id ? this._state.history_login_id : {};
var old_login_id_name = history_login_id.name;
// 解密 iddentities
if (this._state.identities && isString(this._state.identities)) {
var identities = JSON.parse(rot13defs(this._state.identities));
this._state.identities = identities;
}
// 初始化处理匿名 ID 及 初始化 identities
if (!this._state.identities || !isObject(this._state.identities) || isEmptyObject(this._state.identities)) {
this._state.identities = {};
this._state.identities[IDENTITIES.identity_id] = getUUID();
}
function delIdentitiesProp(value) {
for (var identitiesProp in store._state.identities) {
if (hasOwnProperty$1.call(store._state.identities, identitiesProp)) {
if (identitiesProp !== IDENTITIES.identity_id && identitiesProp !== value) {
delete store._state.identities[identitiesProp];
}
}
}
}
// 以下处理登录 ID 的相关逻辑
if (first_id) {
// 处理存在老的 3.0 登录 ID 逻辑,及不存在登录 ID 的情况
if (old_login_id_name && hasOwnProperty$1.call(this._state.identities, old_login_id_name)) {
if (this._state.identities[old_login_id_name] !== distinct_id) {
this._state.identities[old_login_id_name] = distinct_id;
delIdentitiesProp(old_login_id_name);
this._state.history_login_id.value = distinct_id;
}
} else {
this._state.identities[IDENTITY_KEY.LOGIN] = distinct_id;
delIdentitiesProp(IDENTITY_KEY.LOGIN);
this._state.history_login_id = {
name: IDENTITY_KEY.LOGIN,
value: distinct_id
};
}
} else {
this._state.history_login_id = {
name: '',
value: ''
};
}
this.save();
},
getFirstId: function () {
return this._state._first_id || this._state.first_id;
},
/**
* 获取当前 distinct_id,如果有 IDM3 状态下的登录的 distinctId 则返回此 ID 值,若没有则返回当前的匿名 ID
* @returns distinct_id
*/
getDistinctId: function () {
var loginDistinctId = this.getLoginDistinctId();
if (loginDistinctId) {
return loginDistinctId;
} else {
return this._state._distinct_id || this._state.distinct_id;
}
},
getUnionId: function () {
var obj = {};
var first_id = this._state._first_id || this._state.first_id;
var distinct_id = this.getDistinctId();
if (first_id && distinct_id) {
obj['login_id'] = distinct_id;
obj['anonymous_id'] = first_id;
} else {
obj['anonymous_id'] = distinct_id;
}
return obj;
},
// 区别于 identities,这里会加入 $identities_anonymous_id
getIdentities: function () {
var iden = JSON.parse(JSON.stringify(this._state.identities));
iden.$identity_anonymous_id = this.getAnonymousId();
return iden;
},
getAnonymousId: function () {
return this.getUnionId().anonymous_id;
},
/**
* 新增 getHistoryLoginId 接口,用以获取到老的登录用户 ID 标识
*/
getHistoryLoginId: function () {
if (isObject(this._state.history_login_id)) {
return this._state.history_login_id;
} else {
return null;
}
},
/**
* 获取当前的登录情况下的 distinctId
* 获取当前 distinct_id,如果为 IDM3 登录 ID,则值为登录 ID 的 name + value 的格式
* 如果为非登录状态,则直接返回 null,标识无值
*/
getLoginDistinctId: function () {
var historyLoginId = this.getHistoryLoginId();
// 存在登录 ID 对象,且登录 ID 值为真(排除登录后登出,保存 history_login_id 对象,但清空属性值的情况);否则为未登录状态,直接取当前的 distinct_id
if (isObject(historyLoginId) && historyLoginId.value) {
if (historyLoginId.name !== IDENTITY_KEY.LOGIN) {
return historyLoginId.name + '+' + historyLoginId.value;
} else {
return historyLoginId.value;
}
} else {
return null;
}
},
getProps: function () {
return this._state.props || {};
},
setProps: function (newp, isCover) {
var props = this._state.props || {};
if (!isCover) {
extend(props, newp);
this.set('props', props);
} else {
this.set('props', newp);
}
},
set: function (name, value) {
var obj = {};
if (typeof name === 'string') {
obj[name] = value;
} else if (typeof name === 'object') {
obj = name;
}
this._state = this._state || {};
for (var i in obj) {
this._state[i] = obj[i];
// 如果set('first_id') 或者 set('distinct_id'),删除对应的临时属性
if (i === 'first_id') {
delete this._state._first_id;
} else if (i === 'distinct_id') {
delete this._state._distinct_id;
// deprecated 不推荐使用,即将废弃
sa.events.emit('changeDistinctId');
}
}
this.save();
},
identitiesSet: function (params) {
var identities = {};
switch (params.type) {
case 'login':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
identities[params.id_name] = params.id;
break;
case 'logout':
identities[IDENTITIES.identity_id] = this._state.identities[IDENTITIES.identity_id];
break;
// donoting
}
this.set('identities', identities);
},
change: function (name, value) {
this._state['_' + name] = value;
},
encryptStorage: function () {
var copyState = this.getStorage();
var flag = 'data:enc;';
if (isObject(copyState)) {
copyState = flag + rot13obfs(JSON.stringify(copyState));
} else if (isString(copyState)) {
if (copyState.indexOf(flag) === -1) {
copyState = flag + rot13obfs(copyState);
}
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
save: function () {
// 深拷贝避免修改原对象
var copyState = deepCopy(this._state);
// 对 identitie 进行加密
var identities = rot13obfs(JSON.stringify(copyState.identities));
copyState.identities = identities;
// 删除临时属性避免写入微信 storage
delete copyState._first_id;
delete copyState._distinct_id;
// 是否开启本地存储加密
if (sa.para.encrypt_storage) {
var flag = 'data:enc;';
copyState = flag + rot13obfs(JSON.stringify(copyState));
}
sa.system_api.setStorageSync(sa.storageName, copyState);
},
init: function () {
var info = this.getStorage();
var flag = 'data:enc;';
var uuid = getUUID();
if (info) {
if (isString(info)) {
//判断是否有加密的字段 有就解密
if (info.indexOf(flag) !== -1) {
info = info.substring(flag.length);
info = JSON.parse(rot13defs(info));
}
}
this.toState(info);
} else {
meta.is_first_launch = true;
var time = new Date();
var visit_time = time.getTime();
time.setHours(23);
time.setMinutes(59);
time.setSeconds(60);
this.set({
distinct_id: uuid,
first_visit_time: visit_time,
first_visit_day_time: time.getTime(),
identities: {
[IDENTITIES.identity_id]: uuid
},
history_login_id: {
name: '',
value: ''
}
});
if (typeof sa.para === 'object' && typeof sa.para.identify_id === 'string') {
sa.identify(sa.para.identify_id);
}
sa.setOnceProfile({ $first_visit_time: time });
}
this.checkStoreInit && this.checkStoreInit();
}
};
sa.store = store;
/*
* @Date: 2022-12-05 16:21:58
* @File: 通用 ID2 、ID3 相关 API
*/
function trackSignup(idObj, e, p) {
var currentId, eventName, idName, distinctId;
if (_.isObject(idObj)) {
currentId = idObj.id;
eventName = idObj.event_name;
idName = idObj.id_name;
} else {
currentId = idObj;
eventName = e;
}
// 按照原有逻辑修改 distinct_id 的值
store.set('distinct_id', currentId);
// 上报 $SignUp 事件前,先获取 original_id、distinct_id 的值
if (idName && idName !== IDENTITY_KEY.LOGIN) {
distinctId = idName + '+' + currentId;
} else {
distinctId = currentId;
}
var originalId = store.getFirstId() || store.getDistinctId();
sa.prepareData({
original_id: originalId,
distinct_id: distinctId,
type: 'track_signup',
event: eventName,
properties: p
});
}
function bindWithoutCheck(name, value) {
var identities = store._state.identities;
identities[name] = value;
store.save();
sa.prepareData({
type: 'track_id_bind',
event: '$BindID'
});
}
function bind$1(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 获取当前的 login_id key
var historyLoginId = store.getHistoryLoginId();
var currentLoginIdName = historyLoginId ? historyLoginId.name : '';
var presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName];
if (_.isArray(IDENTITIES.bind_preset_id)) {
presetIdKeys = [IDENTITY_KEY.LOGIN, currentLoginIdName].concat(IDENTITIES.bind_preset_id);
}
// 通过 isPresetIdKeys 判断当前 ID 的 name 是否是预置的 ID key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, presetIdKeys)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
bindWithoutCheck(name, value);
}
function unbindWithoutCheck(name, value) {
if (hasOwnProperty.call(store._state.identities, name) && value === store._state.identities[name]) {
if (IDENTITIES.unbind_without_check && IDENTITIES.unbind_without_check.indexOf(name) < 0) {
delete store._state.identities[name];
}
store.save();
}
var distinctId = store.getDistinctId();
var firstId = store.getFirstId();
var unbindDistinctId = name + '+' + value;
if (distinctId === unbindDistinctId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
store.set('history_login_id', {
name: '',
value: ''
});
}
var para = {};
para[name] = value;
sa.prepareData({
type: 'track_id_unbind',
event: '$UnbindID',
unbind_value: para
});
}
function unbind(name, value) {
var info = '';
if (_.isNumber(value)) {
if (_.isInteger(value) && _.isSafeInteger(value) === false) {
sa.log('Value must be String');
return false;
}
value = String(value);
}
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 通过 isPresetIdKeys 判断是否是预置的 id key 值
if (!_.check.checkKeyword(name) || _.isPresetIdKeys(name, [IDENTITY_KEY.LOGIN])) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (!value || value === '') {
sa.log('Value is empty or null');
return false;
}
if (!_.isString(value)) {
sa.log('Value must be String');
return false;
}
if (!_.check.checkIdLength(value)) {
return false;
}
unbindWithoutCheck(name, value);
}
/**
* 通过自定义的登录 ID 的 key(name)值进行登录
* @param {string} name
* @param {string} id
* @returns
*/
function loginWithKey(name, id) {
sa.log('loginWithKey is deprecated !!!');
if (!_.isString(name)) {
sa.log('Key must be String');
return false;
}
// 这个单独判断 name 的 length 是为了符合测试提出的多端检查统一,保证判断 loginWithKey 的 key 值时长度超过 100 打印日志,但继续做后续 ID 绑定
// 同时 checkKeyword 未做修改,是为了保持原有统一检查逻辑不变,以免影响到其他检查
// 在 name 的 length 的值小于 100 的情况下,若其他检查不符,会做 return 处理
var info = '';
if (!_.check.checkKeyword(name) && name.length > 100) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
} else if (!_.check.checkKeyword(name)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
if (_.isPresetIdKeys(name, IDENTITIES.login_preset_id)) {
info = 'Key [' + name + '] is invalid';
sa.log(info);
return false;
}
id = _.validId(id);
// 如果 ID 不合法,直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
// 通过 isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(name, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
store._state.identities[name] = id;
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: name,
value: id
});
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp',
id_name: name
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将 login 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: name
});
}
}
function login(id) {
id = _.validId(id);
// 如果 ID 不合法直接返回
if (!id) {
return false;
}
// 如果传入的 ID 和匿名 ID 相同则返回
if (_.isSameAndAnonymousID(id)) {
return false;
}
var firstId = store.getFirstId();
var distinctId = store.getDistinctId();
var idName = IDENTITY_KEY.LOGIN;
// 通过 _.isNewLoginId 判断是否为新的登录 ID,并通过 newLoginId 保存
var newLoginId = _.isNewLoginId(idName, id);
if (newLoginId) {
// 此时并未将修改的 login_id 保存到 storage 中
if (store._state.identities) {
store._state.identities[idName] = id;
}
// 将登录 ID 保存到 history_login_id 对象中
store.set('history_login_id', {
name: idName,
value: id
});
// 处理 trackSignup 逻辑,其中 newDistinctId 作为 2.0 的 distinct_id 通过 trackSignup 进行保存
if (!firstId) {
store.set('first_id', distinctId);
}
sa.trackSignup({
id: id,
event_name: '$SignUp'
});
// trackSignup 完之后更行 storage 中的 ID
// 若登录 ID 发生改变,此时将登录 id 保存到 storage,并且清除其他 ID
store.identitiesSet({
type: 'login',
id: id,
id_name: idName
});
}
}
function logout() {
var firstId = store.getFirstId();
// IDM3 ID identities 先做更新,然后更新外层的 ID
store.identitiesSet({ type: 'logout' });
// 删除 history_login_id 的登录 ID
store.set('history_login_id', {
name: '',
value: ''
});
if (firstId) {
store.set('first_id', '');
store.set('distinct_id', firstId);
} else {
sa.log('没有first_id,logout失败');
}
}
// export function bindOpenid(openid) {
// openid = _.validId(openid);
// if (!openid) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// bind(name, openid);
// }
// export function unbindOpenid(val) {
// var id = _.validId(val);
// if (!id) {
// return false;
// }
// var name = _.getOpenidNameByAppid(IDENTITIES.openid_name);
// // 不管本地有没有都要 unbind
// unbind(name, val);
// }
function getIdentities() {
if (_.isEmptyObject(store._state)) {
return null;
} else {
return store.getIdentities() || null;
}
}
// 重置 id3 匿名 id,只有在未登录情况下可以使用!!!
function resetAnonymousIdentity(id) {
// 登录则 return
var firstId = store.getFirstId();
if (firstId) {
sa.log('resetAnonymousIdentity must be used in a logout state !');
return false;
}
if (typeof id === 'number') {
id = String(id);
}
// id 有值则替换,没值则重置
if (typeof id === 'undefined') {
var uuid = store.getUUID();
store._state.identities[IDENTITIES.identity_id] = uuid;
store.set('distinct_id', uuid);
} else if (_.validId(id)) {
store._state.identities[IDENTITIES.identity_id] = id;
store.set('distinct_id', id);
}
}
function getPresetProperties$1() {
return _.getPresetProperties();
}
function getAnonymousID() {
if (_.isEmptyObject(sa.store._state)) {
sa.log('请先初始化SDK');
} else {
return sa.store._state._first_id || sa.store._state.first_id || sa.store._state._distinct_id || sa.store._state.distinct_id;
}
}
var functions = /*#__PURE__*/Object.freeze({
__proto__: null,
trackSignup: trackSignup,
bindWithoutCheck: bindWithoutCheck,
bind: bind$1,
unbindWithoutCheck: unbindWithoutCheck,
unbind: unbind,
loginWithKey: loginWithKey,
login: login,
logout: logout,
getIdentities: getIdentities,
resetAnonymousIdentity: resetAnonymousIdentity,
getPresetProperties: getPresetProperties$1,
getAnonymousID: getAnonymousID
});
/*
* @Date: 2022-12-13 18:50:04
* @File:
*/
//对外 API 设置
for (var f in functions) {
sa[f] = functions[f];
}
/*
* @Date: 2022-09-27 17:35:17
* @File: 参数处理
*/
sa.setPara = function (para) {
sa.para = extend2Lev(sa.para, para);
var channel = [];
if (isArray(sa.para.source_channel)) {
var len = sa.para.source_channel.length;
for (var c = 0; c < len; c++) {
if (RESERVE_CHANNEL.indexOf(' ' + sa.para.source_channel[c] + ' ') === -1) {
channel.push(sa.para.source_channel[c]);
}
}
}
sa.para.source_channel = channel;
if (typeof sa.para.send_timeout !== 'number') {
sa.para.send_timeout = 1000;
}
var batch_send_default = {
send_timeout: 6000,
max_length: 6
};
// 如果已经配置为批量发送,且未定义请求撤销时间的情况下,设置请求撤销时间为 10s
if (para && para.datasend_timeout); else if (sa.para.batch_send) {
sa.para.datasend_timeout = 10000;
}
// 如果是true,转换成对象
if (sa.para.batch_send === true) {
sa.para.batch_send = extend({}, batch_send_default);
} else if (isObject(sa.para.batch_send)) {
sa.para.batch_send = extend({}, batch_send_default, sa.para.batch_send);
}
if (!sa.para.server_url) {
sa.log('请使用 setPara() 方法设置 server_url 数据接收地址');
return;
}
sa.para.preset_properties = isObject(sa.para.preset_properties) ? sa.para.preset_properties : {};
};
function buildPara(obj) {
if (obj && isObject(obj)) {
sa.setPara(obj);
} else {
//sa.log('error: 请传入正确的参数');
return false;
}
if (!obj.server_url) {
sa.log('error: server_url is empty');
return false;
} else {
return true;
}
}
function isValidListener(listener) {
if (typeof listener === 'function') {
return true;
} else if (listener && typeof listener === 'object') {
return isValidListener(listener.listener);
} else {
return false;
}
}
/**
* @class EventEmitter
* @category Event
* @example
* var e = new EventEmitter()
* e.on('HelloEvent',function(data){
* console.log('Hello Event happens',data);
* })
*
* e.emit('HelloEvent',123);
* // Hello Event happens , 123
*/
class EventEmitterBase {
constructor() {
this._events = {};
}
/**
* 添加事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
on(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].push(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prepend(eventName, listener) {
if (!eventName || !listener) {
return false;
}
if (!isValidListener(listener)) {
throw new Error('listener must be a function');
}
this._events[eventName] = this._events[eventName] || [];
var listenerIsWrapped = typeof listener === 'object';
this._events[eventName].unshift(
listenerIsWrapped
? listener
: {
listener: listener,
once: false
}
);
return this;
}
/**
* 添加事件到事件回调函数列表头,回调只执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
prependOnce(eventName, listener) {
return this.prepend(eventName, {
listener: listener,
once: true
});
}
/**
* 添加事件,该事件只能被执行一次
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
once(eventName, listener) {
return this.on(eventName, {
listener: listener,
once: true
});
}
/**
* 删除事件
* @param {String} eventName 事件名称
* @param {Function} listener 监听器函数
* @return {Object} 可链式调用
*/
off(eventName, listener) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
if (typeof listener === 'number') {
listeners.splice(listener, 1);
} else if (typeof listener === 'function') {
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i] && listeners[i].listener === listener) {
listeners.splice(i, 1);
}
}
}
return this;
}
/**
* 触发事件
* @param {String} eventName 事件名称
* @param {Array} args 传入监听器函数的参数,使用数组形式传入
* @return {Object} 可链式调用
*/
emit(eventName, args) {
var listeners = this._events[eventName];
if (!listeners) {
return false;
}
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
if (listener) {
listener.listener.call(this, args || {});
if (listener.once) {
this.off(eventName, i);
}
}
}
return this;
}
/**
* 删除某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
removeAllListeners(eventName) {
if (eventName && this._events[eventName]) {
this._events[eventName] = [];
} else {
this._events = {};
}
}
/**
* 返回某一个类型的所有事件或者所有事件
* @param {String[]} eventName 事件名称
*/
listeners(eventName) {
if (eventName && typeof eventName === 'string') {
return this._events[eventName];
} else {
return this._events;
}
}
}
/**
* ex 扩展
*/
class EventEmitterEx extends EventEmitterBase {
constructor() {
super();
this.cacheEvents = [];
this.maxLen = 20;
}
replay(eventName, listener) {
this.on(eventName, listener);
if (this.cacheEvents.length > 0) {
this.cacheEvents.forEach(function (val) {
if (val.type === eventName) {
listener.call(null, val.data);
}
});
}
}
emit(eventName, args) {
super.emit.apply(this, arguments);
this.cacheEvents.push({ type: eventName, data: args });
this.cacheEvents.length > this.maxLen ? this.cacheEvents.shift() : null;
}
}
/*
* @Date: 2022-07-07 14:20:38
* @File:
*/
var ee = {};
ee.sdk = new EventEmitterEx();
ee.data = new EventEmitterEx();
/*
* @Date: 2022-06-08 18:59:23
* @File: 老版的事件订阅发布
*/
var eventEmitter = function () {
this.sub = [];
};
eventEmitter.prototype = {
add: function (item) {
this.sub.push(item);
},
emit: function (event, data) {
this.sub.forEach(function (temp) {
temp.on(event, data);
});
}
};
var eventSub = function (handle) {
sa.events.add(this);
this._events = [];
this.handle = handle;
this.ready = false;
};
eventSub.prototype = {
on: function (event, data) {
if (this.ready) {
if (isFunction(this.handle)) {
try {
this.handle(event, data);
} catch (error) {
sa.log(error);
}
}
} else {
this._events.push({
event,
data
});
}
},
isReady: function () {
var that = this;
that.ready = true;
that._events.forEach(function (item) {
if (isFunction(that.handle)) {
try {
that.handle(item.event, item.data);
} catch (error) {
sa.log(error);
}
}
});
}
};
/*
* @Date: 2022-03-01 15:10:18
* @File: SDK 入口文件
*/
//事件发布订阅监听
sa.ee = ee;
//兼容老版的事件发布订阅
sa.eventSub = eventSub;
sa.events = new eventEmitter();
//内部全局变量
sa.meta = meta;
sa.kit = kit;
// use 插件存储
sa.modules = {};
sa.init = function (obj) {
// 是否执行过init,防止重复执行
if (meta.hasExeInit === true) {
return false;
}
meta.hasExeInit = true;
ee.sdk.emit('beforeInit');
//初始化配置参数
buildPara(obj);
ee.sdk.emit('initPara');
// ------------- 全局参数准备完毕
// 可以使用 param
ee.sdk.emit('afterInitPara');
//用户信息初始化 - SDK 必备用户信息获取
sa.store.init();
//初始化系统信息 //modules/preset-data.js
sa.system.init();
//只能写API,不用用API
ee.sdk.emit('initAPI');
//可以用非发数据API,不能用发数据API,不能写API
ee.sdk.emit('afterInitAPI');
ee.sdk.emit('afterInit');
ee.sdk.emit('ready');
//数据发送方式,单条发送还是批量发送
if (sa.para.batch_send) {
sa.system_api.getStorage('sensors_prepare_data', function (res) {
var queue = [];
if (res && res.data && isArray(res.data)) {
queue = res.data;
sa.batch_state.mem = queue.concat(sa.batch_state.mem);
}
sa.batch_state.syncStorage = true;
onAppHide();
});
batchInterval();
}
};
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getNetwork() {
return new Promise(function (resolve) {
sa.system_api.getNetworkType({
success(t) {
sa.properties.$network_type = setUpperCase(t['networkType']);
},
fail(e) {
sa.log('获取网络状态信息失败: ', e);
},
complete() {
resolve();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getSystemInfo() {
return new Promise((reslove) => {
sa.system_api.getSystemInfo({
success(res) {
var p = sa.properties;
if (isObject(res)) {
p.$manufacturer = res['brand'];
p.$model = res['model'];
p.$brand = setUpperCase(res['brand']) || '';
p.$screen_width = Number(res['screenWidth']);
p.$screen_height = Number(res['screenHeight']);
p.$os = formatSystem(res['platform']);
p.$os_version = res['system'].indexOf(' ') > -1 ? res['system'].split(' ')[1] : res['system'];
p.$mp_client_app_version = res['version'] || '';
var sdk_version = res['SDKVersion'] || '';
if (sdk_version) {
p.$mp_client_basic_library_version = sdk_version;
}
}
},
fail(e) {
sa.log('获取系统信息失败: ', e);
},
complete() {
reslove();
}
});
});
}
/*
* @Date: 2022-11-01 19:03:46
* @File: 同步获取系统信息与网络信息
*/
var system = {
inited: false,
init: function () {
var timeZoneOffset = new Date().getTimezoneOffset();
if (isNumber(timeZoneOffset)) {
sa.properties.$timezone_offset = timeZoneOffset;
}
var app_id = getAppId() || sa.para.app_id || sa.para.appid;
if (app_id) {
sa.properties.$app_id = app_id;
}
getNetwork();
getSystemInfo();
// Promise.all([network, sysytemInfo]).then(function () {
// sa.system.inited = true;
// sa.checkInit();
// });
}
};
function request(para) {
var timeout;
if (para.timeout) {
timeout = para.timeout;
delete para.timeout;
}
var rq = sa.platform_obj.request(para);
setTimeout(function () {
try {
if (isObject(rq) && isFunction(rq.abort)) {
rq.abort();
}
} catch (error) {
sa.log(error);
}
}, timeout);
}
/*
* @Date: 2022-11-01 19:03:46
* @File:
*/
function getStorage(key, complete) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (e) {
try {
sa.platform_obj.getStorage({
key: key,
success: parseRes,
fail: parseRes
});
} catch (err) {
sa.log('获取 storage 失败!', err);
}
}
function parseRes(res) {
if (res && res.data && isJSONString(res.data)) {
try {
var data = JSON.parse(res.data);
res.data = data;
} catch (err) {
sa.log('parse res.data 失败!', err);
}
}
complete(res);
}
}
function setStorage(item, val) {
var value;
try {
value = JSON.stringify(val);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
try {
sa.platform_obj.setStorage({
key: item,
data: value
});
} catch (err) {
sa.log('设置 storage 失败: ', err);
}
}
}
function getStorageSync(key) {
var store = '';
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e) {
try {
store = sa.platform_obj.getStorageSync(key);
} catch (e2) {
sa.log('获取 storage 失败!');
}
}
if (isJSONString(store)) {
store = JSON.parse(store);
}
return store;
}
function setStorageSync(key, value) {
var item;
try {
item = JSON.stringify(value);
} catch (err) {
sa.log('序列化缓存对象失败!', err);
}
var fn = function () {
sa.platform_obj.setStorageSync(key, item);
};
try {
fn();
} catch (e) {
sa.log('set Storage fail --', e);
try {
fn();
} catch (e2) {
sa.log('set Storage fail again --', e2);
}
}
}
/*
* @Date: 2021-10-13 15:29:49
* @File: 内部 API 统一
*/
function getNetworkType() {
return sa.platform_obj.getNetworkType.apply(null, arguments);
}
function getSystemInfo$1() {
return sa.platform_obj.getSystemInfo.apply(null, arguments);
}
function getAppId$1() {
var info;
if (sa.platform_obj.getAccountInfoSync) {
info = sa.platform_obj.getAccountInfoSync();
}
if (isObject(info) && isObject(info.miniProgram)) {
return info.miniProgram;
}
}
var compose = {
request: request,
getStorage: getStorage,
setStorage: setStorage,
getStorageSync: getStorageSync,
setStorageSync: setStorageSync,
getAppInfoSync: getAppId$1,
getNetworkType: getNetworkType,
getSystemInfo: getSystemInfo$1
};
const forEach$1 = Array.prototype.forEach,
slice$1 = Array.prototype.slice,
_hasOwnProperty$1 = Object.prototype.hasOwnProperty,
_toString$1 = Object.prototype.toString;
function extend$1(obj) {
each$1(slice$1.call(arguments, 1), function (source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
}
function isObject$1(obj) {
return obj !== null && typeof obj === 'object';
}
function isFunction$1(f) {
if (!f) {
return false;
}
var type = Object.prototype.toString.call(f);
return type == '[object Function]' || type == '[object AsyncFunction]' || type == '[object GeneratorFunction]';
}
function isString$1(obj) {
return _toString$1.call(obj) == '[object String]';
}
function each$1(obj, iterator, context) {
if (obj == null) {
return false;
}
if (forEach$1 && obj.forEach === forEach$1) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
return false;
}
}
} else {
for (var key in obj) {
if (_hasOwnProperty$1.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === {}) {
return false;
}
}
}
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-03 08:05:52
* @File: SDK 内部 生命周期钩子统一接口
*/
var lifeCycleHook = ['appOnLaunch', 'appOnShow', 'appOnHide', 'pageOnShow', 'pageOnLoad'];
// 内部统一生命周期 API
var miniLifeCycleAPI = {};
lifeCycleHook.forEach(function (key) {
miniLifeCycleAPI[key] = function () {
throw new Error(`需要先定义 '${key}' 才能使用`);
};
});
/**
* 按照不同平台混入内部调用的 API (初始化时调用)
*
* @public
* @param {Object} mixinAPI 需混入的 API
* @returns {void}
*/
function registerLifeCycleHook(mixinAPI) {
Object.assign(miniLifeCycleAPI, mixinAPI);
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:56
* @File:
*/
function getScene(scene_value, sa) {
if (!isObject$1(sa)) {
return false;
}
var scene_prefix = sa.meta.scene_prefix;
// 判断是否存在 scene_prefix 来确定当前小程序是否采集 scene 场景值
if (!scene_prefix || !isString$1(scene_prefix)) {
return false;
}
if (typeof scene_value === 'number' || (typeof scene_value === 'string' && scene_value !== '')) {
scene_value = scene_prefix + String(scene_value);
return scene_value;
} else {
return '未取到值';
}
}
/**
* hook function
*
* @public
* @param {Object} obj 待 hook 对象
* @param {name} method 方法名
* @param {Function} hook hook 方法
* @returns {void}
* */
function hookFunc(obj, method, hook) {
var oldMethod = obj[method];
obj[method] = function (args) {
if (isFunction$1(hook)) {
hook.call(this, args);
}
oldMethod && isFunction$1(oldMethod) && oldMethod.call(this, args);
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: app 重写逻辑
*/
function hookAppFunc(option) {
hookFunc(option, 'onLaunch', miniLifeCycleAPI['appOnLaunch']);
hookFunc(option, 'onShow', miniLifeCycleAPI['appOnShow']);
hookFunc(option, 'onHide', miniLifeCycleAPI['appOnHide']);
}
/**
* hook app
* sa 引入主 SDK
* hookAppFunc 需要监听的生命周期
*/
function proxyApp(hookAppFunc, sa) {
function initAppGlobalName(callback) {
var oldApp = App;
App = function (option) {
try {
callback && callback(option);
option[sa.para.name] = sa;
oldApp.apply(this, arguments);
} catch (error) {
oldApp.apply(this, arguments);
global.sensors.log('App:' + error);
}
};
}
//有部分小程序提供如下 API,可以在app.js 没有生命 onshow,onHide 的情况下能监听到如下生命周期
// if (isObject$1(sa) && isFunction$1(sa.platform_obj.onAppShow) && isFunction$1(sa.platform_obj.onAppHide)) {
// initAppGlobalName();
// sa.platform_obj.onAppShow(function (para) {
// if (!sa.para.launched) {
// var option = para || (isFunction$1(sa.platform_obj.getLaunchOptionsSync) && sa.platform_obj.getLaunchOptionsSync()) || {};
// miniLifeCycleAPI.appOnLaunch(option);
// sa.para.launched = true;
// }
// miniLifeCycleAPI.appOnShow(para);
// });
// sa.platform_obj.onAppHide(function () {
// miniLifeCycleAPI.appOnHide();
// });
// } else {
initAppGlobalName(hookAppFunc);
// }
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:55:28
* @File: app 生命周期数据上报模块
*/
function appOnLaunch(option, prop) {
if (!isObject$1(option)) {
global.sensors.log('appOnLaunch:请传入正确的参数');
return;
}
var obj = {};
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.meta.current_scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
} else {
obj.$scene = '未取到值';
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (global.sensors.meta.is_first_launch) {
obj.$is_first_time = true;
if (!global.sensors._.isEmptyObject(utms.pre1)) {
global.sensors.setOnceProfile(utms.pre1);
}
} else {
obj.$is_first_time = false;
}
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appLaunch) {
global.sensors.track('$MPLaunch', obj);
}
}
function appOnShow(option, prop) {
var obj = {};
global.sensors.meta.mp_show_time = new Date().getTime();
if (option && option.path) {
//注入$url\$url_path\$url_query
extend$1(obj, global.sensors._.getAppProps(option));
}
// 设置utm的信息
var utms = global.sensors._.setUtm(option, obj);
if (!global.sensors._.isEmptyObject(utms.pre2)) {
// 通过 _.setLatestChannel 来注册全局变量,替换直接通过 registerApp 来添加全局变量(主要考虑后期如果来源存 storage 情况下)
global.sensors._.setLatestChannel(utms.pre2);
}
if (option && option.scene) {
var scene = getScene(option.scene, global.sensors);
if (scene) {
obj.$scene = scene;
global.sensors.registerApp({ $latest_scene: scene });
}
}
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appShow) {
global.sensors.track('$MPShow', obj);
}
}
function appOnHide(prop) {
var current_time = new Date().getTime();
var obj = {};
if (isObject$1(prop)) {
obj = extend$1(obj, prop);
}
extend$1(obj, global.sensors._.getPageProps());
var mpShowTime = global.sensors.meta.mp_show_time;
if (mpShowTime && current_time - mpShowTime > 0 && (current_time - mpShowTime) / 3600000 < 24) {
obj.event_duration = (current_time - mpShowTime) / 1000;
}
if (global.sensors.para && global.sensors.para.autoTrack && global.sensors.para.autoTrack.appHide) {
global.sensors.track('$MPHide', obj);
}
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 全埋点 appOnHide, appOnShow, appOnLaunch 通用版本使用
*/
var presetEvents = {
appLaunch: true,
appShow: true,
appHide: true
};
var AutoTrackApp = {
name: 'AutoTrackApp'
};
AutoTrackApp.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global.sensors = sensorsdata;
global.sensors.para.autoTrack = extend$1(presetEvents, para);
//初始化全埋点埋点方法
AutoTrackApp.lifeCycleAPI();
AutoTrackApp.proxyFrameworkInterface();
};
AutoTrackApp.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.appOnLaunch = appOnLaunch;
lifeCycleAPI.appOnShow = appOnShow;
lifeCycleAPI.appOnHide = appOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackApp.proxyFrameworkInterface = function () {
proxyApp(hookAppFunc, global.sensors);
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File:
*/
/*
* @Date: 2022-04-26 18:19:16
* @File:
*/
var global$1 = {};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 15:04:43
* @File:
*/
/**
* sa 引入主 SDK
*/
function getCurrentPath$1(sa) {
var url = '未取到';
var current_page = getCurrentPage$1(sa);
if (current_page && current_page.route) {
url = current_page.route;
}
return url;
}
/**
* sa 引入主 SDK
*/
function getCurrentPage$1(sa) {
var currentPage = {};
var pages;
if (sa) {
try {
pages = isFunction$1(sa.platform_obj.getCurrentPages) ? sa.platform_obj.getCurrentPages() : getCurrentPages();
currentPage = pages[pages.length - 1];
} catch (e) {
sa.log(e);
}
} else {
console.log('getCurrentPage:请传入 sa 对象');
}
return currentPage;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:35:22
* @File: 全埋点点击事件,数据处理模块
*/
function isClick(type) {
const TYPES = {
tap: 1,
longtap: 1,
longpress: 1
};
return !!TYPES[type];
}
function createClickData(events) {
var prop = {},
event_prop = {};
var current_target = events.currentTarget || {};
var dataset = current_target.dataset || {};
prop['$element_id'] = current_target.id;
prop['$element_type'] = dataset['type'];
prop['$element_content'] = dataset['content'];
prop['$element_name'] = dataset['name'];
if (isObject$1(events.event_prop)) {
event_prop = events.event_prop;
}
prop['$url_path'] = getCurrentPath$1(global$1.sensors);
prop['$url'] = global$1.sensors._.getPageProps().$url;
prop = extend$1(prop, event_prop);
return prop;
}
var ClickTrack = {};
ClickTrack.track = function (events) {
var prop = createClickData(events);
var current_target = events.currentTarget || {};
var target = events.target || {};
var type = events['type'];
var saPara = global$1.sensors.para;
if (isObject$1(saPara.framework) && isObject$1(saPara.framework.taro) && !saPara.framework.taro.createApp) {
if (target.id && current_target.id && target.id !== current_target.id) {
return false;
}
}
if (isObject$1(prop) && type && isClick(type)) {
if (saPara.preset_events && saPara.preset_events.collect_element && saPara.preset_events.collect_element(arguments[0]) === false) {
return false;
}
global$1.sensors.track('$MPClick', prop);
}
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-18 18:20:42
* @File: 全埋点点击事件核心逻辑模块
*/
var MP_HOOKS = {
data: 1,
onLoad: 1,
onShow: 1,
onReady: 1,
onPullDownRefresh: 1,
onReachBottom: 1,
onShareAppMessage: 1,
onPageScroll: 1,
onResize: 1,
onTabItemTap: 1,
onHide: 1,
onUnload: 1
};
// 重点注意 clickProxy 不能使用 return false
function clickProxy(option, method) {
var oldFunc = option[method];
option[method] = function () {
// 在重写 oldFunc 之前就已经判断是一个方法类型,此处是做一次重复的校验
var res = oldFunc.apply(this, arguments);
var args = arguments[0];
if (isObject$1(args)) {
ClickTrack.track(args);
}
return res;
};
}
function monitorClick(option) {
var methods = [];
var autoTrack = global$1.sensors.para.autoTrack;
if (autoTrack && autoTrack.mpClick) {
methods = getMethods(option);
tabProxy(option);
var len = methods.length;
for (var i = 0; i < len; i++) {
clickProxy(option, methods[i]);
}
}
}
// 监听重写 tabBar
function tabProxy(option) {
var oldTab = option['onTabItemTap'];
option['onTabItemTap'] = function (item) {
if (oldTab) {
oldTab.apply(this, arguments);
}
var prop = {};
if (item) {
prop['$element_content'] = item.text || '';
}
prop['$element_type'] = 'tabBar';
prop['$url_path'] = item.pagePath ? item.pagePath : global$1.sensors._.getCurrentPath();
global$1.sensors.track('$MPClick', prop);
};
}
// 对 page 所有事件进行清理
function getMethods(option) {
var methods = [];
for (var m in option) {
if (typeof option[m] === 'function' && !MP_HOOKS[m]) {
methods.push(m);
}
}
return methods;
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-14 15:11:45
* @File: Page Component 重写逻辑模块
*/
// option是 Page(option) option={onLoad(){},onShow(){}}
function hookPageFunc(option) {
hookFunc(option, 'onShow', miniLifeCycleAPI['pageOnShow']);
hookFunc(option, 'onLoad', miniLifeCycleAPI['pageOnLoad']);
hookFunc(option, 'onUnload', miniLifeCycleAPI['pageOnUnload']);
hookFunc(option, 'onHide', miniLifeCycleAPI['pageOnHide']);
}
/**
* hook Page
*/
function proxyPage(hookPageFunc, monitorClick) {
var oldPage = Page;
Page = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
isFunction$1(hookPageFunc) && hookPageFunc(option);
isFunction$1(monitorClick) && monitorClick(option);
oldPage.apply(this, arguments);
} catch (error) {
oldPage.apply(this, arguments);
console.log('Page:' + error);
}
};
var oldComponent = Component;
Component = function (option) {
try {
// 针对构造页面时未传入任何对象的情况下,保证能采集页面的全埋点事件
if (!option) {
option = {};
}
if (!option.methods) {
option.methods = {};
}
isFunction$1(hookPageFunc) && hookPageFunc(option.methods);
isFunction$1(monitorClick) && monitorClick(option.methods);
oldComponent.apply(this, arguments);
} catch (e) {
oldComponent.apply(this, arguments);
console.log('Component:' + e);
}
};
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 14:21:53
* @File:
*/
var pageLeave = function () {
if (global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageLeave) {
var currentPage = {};
var router = '';
try {
currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log(error);
}
if (global$1.sensors.meta.page_show_time >= 0 && router !== '') {
var prop = {};
var page_stay_time = (Date.now() - global$1.sensors.meta.page_show_time) / 1000;
if (isNaN(page_stay_time) || page_stay_time < 0) {
page_stay_time = 0;
}
extend$1(prop, global$1.sensors._.getPageProps());
prop.event_duration = page_stay_time;
// 数据上报前,判断当前页面是否采集
global$1.sensors.track('$MPPageLeave', prop);
global$1.sensors.meta.page_show_time = -1;
}
}
};
function pageOnLoad(option) {
var currentPage = this;
if (global$1.sensors._.isObject(option)) {
try {
currentPage = getCurrentPage$1(global$1.sensors);
} catch (error) {
global$1.sensors.log('pageOnLoad:' + error);
}
currentPage.sensors_mp_url_query = global$1.sensors._.setQuery(option);
currentPage.sensors_mp_encode_url_query = global$1.sensors._.setQuery(option, true);
}
}
function pageOnShow() {
global$1.sensors.meta.page_show_time = Date.now();
var obj = {};
var router = '';
try {
var currentPage = getCurrentPage$1(global$1.sensors);
router = currentPage ? currentPage.route : '';
} catch (error) {
global$1.sensors.log('pageOnShow:' + error);
}
extend$1(obj, global$1.sensors._.getPageProps());
obj.$referrer = global$1.sensors.meta.sa_referrer;
if (global$1.sensors.para && global$1.sensors.para.autoTrack && global$1.sensors.para.autoTrack.pageShow) {
global$1.sensors.track('$MPViewScreen', obj);
}
global$1.sensors.meta.sa_referrer = router;
}
function pageOnUnload() {
pageLeave();
}
function pageOnHide() {
pageLeave();
}
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 通用全埋点事件入口,如果需要定制化,在对应平台入口进行定制化初始化
*/
var presetEvents$1 = {
pageShow: true,
mpClick: true,
pageLeave: false
};
var AutoTrackPage = {
name: 'AutoTrackPage'
};
AutoTrackPage.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
global$1.sensors = sensorsdata;
global$1.sensors.para.autoTrack = extend$1(presetEvents$1, para);
//初始化全埋点埋点方法
AutoTrackPage.lifeCycleAPI();
AutoTrackPage.proxyFrameworkInterface();
};
AutoTrackPage.lifeCycleAPI = function () {
var lifeCycleAPI = {};
//混入生命周期上报方法
lifeCycleAPI.pageOnShow = pageOnShow;
lifeCycleAPI.pageOnLoad = pageOnLoad;
lifeCycleAPI.pageOnUnload = pageOnUnload;
lifeCycleAPI.pageOnHide = pageOnHide;
registerLifeCycleHook(lifeCycleAPI);
};
/**
* hook 框架相关接口
*/
AutoTrackPage.proxyFrameworkInterface = function () {
proxyPage(hookPageFunc, monitorClick);
};
/*
* @Author: wangzhigang@sensorsdata.cn
* @Date: 2022-04-15 19:34:24
* @File: 平台入口
*/
var presetEvents$2 = {
appLaunch: true,
appShow: true,
appHide: true,
pageShow: true,
mpClick: true
};
var AutoTrack = {};
var _this = undefined;
AutoTrack.init = function (sensorsdata, para) {
if (!sensorsdata) {
console.log('请正确初始化 sensorsdata,才能使用插件');
return false;
}
sensorsdata.ee.sdk.on('afterInitPara', function () {
var autoTrack = extend$1(presetEvents$2, sensorsdata.para.autoTrack, para);
sensorsdata.use(AutoTrackApp, autoTrack);
sensorsdata.use(AutoTrackPage, autoTrack);
var oldPage = Page;
Page = function (option) {
option['onShow'] = option['onShow'] || function () { };
option['onLoad'] = option['onLoad'] || function () { };
option['onUnload'] = option['onUnload'] || function () { };
option['onHide'] = option['onHide'] || function () { };
oldPage.apply(_this, arguments);
};
});
};
sa.lib.name = 'XHSMini';
sa.properties.$lib = 'XHSMini';
sa.properties.$data_ingestion_source = ['XHSMini'];
sa.system = system;
sa.system_api = compose;
sa._ = _;
sa.storageName = 'sensorsdata2015_xhs';
sa.platform_obj = xhs;
sa.meta.scene_prefix = 'xhs-';
//集成全埋点事件插件
sa.use(AutoTrack);
export default sa;
// 原生SDK提供的API
import sensors from '../jssdk/alipay.js';
var _ = sensors._;
// 提供各端一致的公共API
var isParaSet = false;
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: function (para) {
if (!isParaSet) {
sa.setPara(para);
}
sensors.init(para);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
},
setPara: (para) => {
para = para || {};
let defaultValue = {
autoTrack: false
};
Object.assign(defaultValue, para);
sensors.setPara.call(sensors, defaultValue);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
isParaSet = true;
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
register: sensors.registerApp.bind(sensors),
clearRegister: () => {
console.log('web 中不支持此方法');
}
};
export default sa;
/*
* @Date: 2022-10-28 10:30:0
* @File:
*/
// 原生SDK提供的API,直接实现app对应的所有js的api,在这里再做一次bridge的api封装
let sensors = uni.requireNativePlugin('Sensorsdata-UniPlugin-App');
let cachePara = {};
let isInit = false;
let sa = {
// 提供扩展性
instance: sensors,
setPara: function (para) {
if (!isInit) {
cachePara = convertToInitSDKPara(para);
return;
}
// 初始化后,按旧有方式直接调用原生 API 进行设置
setParaAfterInitSDK(para);
},
init: function (para) {
if (!sensors.initSDK) {
console.log('原生插件未提供 initSDK 方法。');
return;
}
sensors.initSDK(deepMerge(cachePara, para));
isInit = true;
},
popupInit: sensors.popupInit.bind(sensors),
// app专用的方法
getAppFlushInterval: sensors.getFlushInterval.bind(sensors),
getAppFlushBulkSize: sensors.getFlushBulkSize.bind(sensors),
getAppSessionIntervalTime: sensors.getSessionIntervalTime.bind(sensors),
trackAppInstall: sensors.trackAppInstall.bind(sensors),
appFlush: sensors.flush.bind(sensors),
register: sensors.registerSuperProperties.bind(sensors),
unRegister: sensors.unregisterSuperProperty.bind(sensors),
clearRegister: sensors.clearSuperProperties.bind(sensors),
setProfile: sensors.profileSet.bind(sensors),
setOnceProfile: sensors.profileSetOnce.bind(sensors),
incrementProfile: sensors.profileIncrement.bind(sensors),
appendProfile: sensors.profileAppend.bind(sensors),
unsetProfile: sensors.profileUnset.bind(sensors),
deleteProfile: sensors.profileDelete.bind(sensors),
//
clearTrackTimer: sensors.clearTrackTimer.bind(sensors),
resumeTrackScreenOrientation: sensors.resumeTrackScreenOrientation.bind(sensors),
stopTrackScreenOrientation: sensors.stopTrackScreenOrientation.bind(sensors),
getScreenOrientation: sensors.getScreenOrientation.bind(sensors),
getSuperProperties: sensors.getSuperProperties.bind(sensors),
profileUnsetPushId: (pushKey = '') => {
sensors.profileUnsetPushId.call(sensors, pushKey)
},
profilePushId: (pushKey = '', pushId = '') => {
sensors.profilePushId.call(sensors, pushKey, pushId)
},
enableTrackScreenOrientation: (enable = false) => {
sensors.enableTrackScreenOrientation.call(sensors, enable)
},
trackViewScreen: (url = '', properties = {}) => {
sensors.trackViewScreen.call(sensors, url, properties)
},
trackTimerEnd: (eventName = '', properties = {}) => {
sensors.trackTimerEnd.call(sensors, eventName, properties)
},
trackTimerResume: (eventName = '') => {
sensors.trackTimerResume.call(sensors, eventName)
},
trackTimerPause: (eventName = '') => {
sensors.trackTimerPause.call(sensors, eventName)
},
trackTimerStart: (eventName = '') => {
return sensors.trackTimerStart.call(sensors, eventName)
},
removeTimer: (eventName = '') => {
sensors.removeTimer.call(sensors, eventName)
},
enableDeepLinkInstallSource: (enable = false) => {
sensors.enableDeepLinkInstallSource.call(sensors, enable);
},
trackDeepLinkLaunch: (deepLinkUrl = '', oaid = '') => {
sensors.trackDeepLinkLaunch.call(sensors, deepLinkUrl, oaid);
},
getIdentities: () => {
return sensors.getIdentities.call(sensors);
},
resetAnonymousIdentity: (identity = '') => {
sensors.resetAnonymousIdentity.call(sensors, identity);
},
//
popupLoadSuccess: (callback) => {
sensors.popupLoadSuccess(callback);
},
popupClose: (callback) => {
sensors.popupClose(callback);
},
popupClick: (callback) => {
sensors.popupClick(callback);
},
popupLoadFailed: (callback) => {
sensors.popupLoadFailed(callback);
},
enablePopup: () => {
sensors.enablePopup();
}
};
// 将老的 setPara 转换为新的 initSDK 支持的格式
function convertToInitSDKPara(para) {
para.app = para.app || {};
Object.keys(para).forEach(
(key) => {
switch (key) {
case 'app_flush_network_policy':
para.app.flush_network_policy = para[key];
delete para[key];
break;
case 'app_flush_interval':
para.app.flush_interval = para[key];
delete para[key];
break;
case 'app_flush_bulkSize':
para.app.flush_bulkSize = para[key];
delete para[key];
break;
case 'app_session_interval_time':
para.app.android = para.app.android || {};
para.app.android.session_interval_time = para[key];
delete para[key];
break;
default: break;
}
}
);
return para;
}
// 原有的 setPara 逻辑,初始化后调用 setPara 只有老的 SDK 支持,还是按老的方式调用
function setParaAfterInitSDK(para) {
if (typeof para !== 'object') {
console.log('setPara 的参数必须是 object');
return false;
}
var relation = {
server_url: 'setServerUrl',
show_log: 'enableLog',
app_flush_network_policy: 'setFlushNetworkPolicy',
app_flush_interval: 'setFlushInterval',
app_flush_bulkSize: 'setFlushBulkSize',
app_session_interval_time: 'setSessionIntervalTime',
app_data_collect: 'enableDataCollect'
};
Object.keys(para).forEach(
(key) => {
if (key in relation && typeof sensors[relation[key]] === 'function') {
if (key === 'app_data_collect') {
if (para[key] === true) {
sensors[relation[key]].call(sensors, para[key]);
}
} else {
sensors[relation[key]].call(sensors, para[key]);
}
} else {
console.log('setPara 在 App 中不支持设置' + key);
}
}
);
}
function deepMerge(target, source) {
try {
var merged = new Map();
if (!target) {
return source;
}
if (!source) {
return target;
}
function merge(t, s) {
for (var k in s) {
if (isObject(t[k]) && isObject(s[k]) && !merged.has(s[k])) {
merged.set(s[k], 1);
merge(t[k], s[k]);
} else {
t[k] = s[k];
}
}
}
function isObject(arg) {
return Object.prototype.toString.call(arg) == '[object Object]' && arg !== null;
}
merge(target, source);
} catch (e) {
return source || target;
}
return target;
}
export default sa;
// 原生SDK提供的API
import sensors from '../jssdk/baidu.js';
var _ = sensors._;
// 提供各端一致的公共API
var isParaSet = false;
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: function (para) {
if (!isParaSet) {
sa.setPara(para);
}
sensors.init(para);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
},
setPara: (para) => {
para = para || {};
let defaultValue = {
autoTrack: false
};
Object.assign(defaultValue, para);
sensors.setPara.call(sensors, defaultValue);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
isParaSet = true;
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
register: sensors.registerApp.bind(sensors),
clearRegister: () => {
console.log('web 中不支持此方法');
}
};
export default sa;
// 原生SDK提供的API
import sensors from '../jssdk/toutiao.js';
var _ = sensors._;
// 提供各端一致的公共API
var isParaSet = false;
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: function (para) {
if (!isParaSet) {
sa.setPara(para);
}
sensors.init(para);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
},
setPara: (para) => {
para = para || {};
let defaultValue = {
autoTrack: false
};
Object.assign(defaultValue, para);
sensors.setPara.call(sensors, defaultValue);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
isParaSet = true;
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
register: sensors.registerApp.bind(sensors),
clearRegister: () => {
console.log('web 中不支持此方法');
}
};
export default sa;
// 原生SDK提供的API
import sensors from '../jssdk/web.js';
import mobilePopups from "../plugin/mb-popup.esm.min"
import webPopups from "../plugin/web-popup.esm.min"
// 提供各端一致的公共API
const systemInfo = uni.getSystemInfoSync();
let popups = mobilePopups;
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: (para) => {
para = para || sa.para;
let defaultValue = {
is_track_single_page: true
};
Object.assign(defaultValue, para);
sensors.init.call(sensors, defaultValue);
var _ = sensors._;
if (para && _.isObject(para.global_properties)) {
sensors.registerPage(para.global_properties);
}
},
//弹窗初始化
popupInit: (para) => {
if (typeof para === "object" && para !== null) {
if (systemInfo.screenWidth > 1024) {
sensors.use('WebPopup', para);
popups = webPopups;
} else {
sensors.use('Popup', para);
}
}
},
setPara: (para) => {
if (typeof para === 'object') {
sa.para = para;
}
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
getAnonymousID: () => {
return sensors.quick('getAnonymousID');
},
// 获取 ID-Mapping 3.0 绑定信息
getIdentities: () => {
return sensors.getPresetProperties() && sensors.getPresetProperties().identities;
},
register: sensors.registerPage.bind(sensors),
clearRegister: () => {
console.log('web 中不支持此方法 - clearRegister');
},
quick: (event, para) => {
sensors.quick(event, para);
},
popupLoadSuccess: (callback) => {
if (popups.info.supportCustom && popups.info.supportCustom === 'withoutCampaignListener') {
popups.info.supportCustom = '';
};
if (popups.info && popups.info.popup_campaign_listener) {
popups.info.popup_campaign_listener.onStart = callback;
};
},
popupClose: (callback) => {
if (popups.info && popups.info.popup_campaign_listener) {
popups.info.popup_campaign_listener.onEnd = callback;
};
},
popupClick: (callback) => {
if (systemInfo.screenWidth <= 1024) {
if (popups.info && popups.info.popup_listener) {
popups.info.popup_listener.onClick = callback;
};
} else {
console.log('web 中不支持此方法 - popupClick 方法');
}
},
popupLoadFailed: (callback) => {
if (popups.info && popups.info.popup_campaign_listener) {
popups.info.popup_campaign_listener.onFailed = callback;
};
}
};
export default sa;
\ No newline at end of file
// 原生SDK提供的API
import sensors from '../jssdk/weixin.js';
import popups from '../plugin/wx-popup.esm.min';
var isParaSet = false;
var _ = sensors._;
// 提供各端一致的公共API
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: function (para) {
if (!isParaSet) {
sa.setPara(para);
}
sensors.init(para);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
},
//弹窗初始化
popupInit: (para) => {
if (typeof para === "object" && para !== null) {
sensors.usePlugin(popups, para);
}
},
setPara: (para) => {
para = para || {};
let defaultValue = {
autoTrack: false
};
Object.assign(defaultValue, para);
sensors.setPara.call(sensors, defaultValue);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
isParaSet = true;
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
register: sensors.registerApp.bind(sensors),
// 有这个方法但是效果不同的话,需要覆盖一下
clearRegister: () => {
console.log('web 中不支持此方法');
},
popupLoadSuccess: (callback) => {
if (popups.CAMPAIGN_ERROR && popups.CAMPAIGN_ERROR['onStart']) {
delete popups.CAMPAIGN_ERROR['onStart']
};
popups.campaign_listener.onStart = callback;
},
popupClose: (callback) => {
if (popups.CAMPAIGN_ERROR && popups.CAMPAIGN_ERROR['onEnd']) {
delete popups.CAMPAIGN_ERROR['onEnd']
};
popups.campaign_listener.onEnd = callback;
},
popupClick: (callback) => {
popups.info.popup_listener.onClick = callback;
},
popupLoadFailed: (callback) => {
if (popups.CAMPAIGN_ERROR && popups.CAMPAIGN_ERROR['onFailed']) {
delete popups.CAMPAIGN_ERROR['onFailed']
};
popups.campaign_listener.onFailed = callback;
}
};
export default sa;
// 原生SDK提供的API
import sensors from '../jssdk/xiaohongshu.js';
var _ = sensors._;
// 提供各端一致的公共API
var isParaSet = false;
let sa = {
// 提供扩展性
instance: sensors,
// 提供初始化和配置参数
init: function (para) {
if (!isParaSet) {
sa.setPara(para);
}
sensors.init(para);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
},
setPara: (para) => {
para = para || {};
let defaultValue = {
autoTrack: false
};
Object.assign(defaultValue, para);
sensors.setPara.call(sensors, defaultValue);
if (para && _.isObject(para.global_properties)) {
sensors.registerApp(para.global_properties);
}
isParaSet = true;
},
// 各端通用的常用API
getDistinctID: sensors.store.getDistinctId.bind(sensors.store),
register: sensors.registerApp.bind(sensors),
clearRegister: () => {
console.log('web 中不支持此方法');
}
};
export default sa;
{
"id": "Sensorsdata-UniPlugin-JS",
"name": "神策分析 JS 插件",
"displayName": "神策分析 JS 插件",
"version": "0.1.7",
"description": "神策分析通用 JS SDK",
"keywords": [
"SensorsData",
"SensorsAnalytics",
"神策数据",
"神策分析",
"神策智能运营"
],
"dcloudext": {
"type": "js_sdk",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
}
},
"uni_modules": {
"dependencies": [],
"encrypt": []
}
}
\ No newline at end of file
var popup={sa:{},info:{},lib_version:"0.4.2",defaultPara:{platform:"H5",preload_image:!0},serverData:{},localData:{global_popup_count:[],local_update_time:null,eventQueue:[],update_time:null},eventRule:{},convertPlans:[],isRun:!1,setArg:function(e){var t={};if(e&&"[object Object]"===Object.prototype.toString.call(e)){for(var n in e)n&&"popup_window_content"!==n&&(t[n]=e[n]);return JSON.stringify(t,null," ")}return e},log:function(){if(!0===popup.info.show_log&&"object"==typeof console&&"function"==typeof console.log)try{return arguments[0]=popup.setArg(arguments[0]),arguments[1]=popup.setArg(arguments[1]),console.log.apply(console,arguments)}catch(e){console.log(arguments[0])}},config:{storageName:"sensorsdata202002-popupdata",loadedSign:"SensorsData2015JSSDKH5PopupIsLoad"}},_={visibility:function(e){e=e||{};var t={hidden:undefined,visibilityChange:undefined,isSupported:function(){return"undefined"!=typeof this.hidden},_visible:e.onVisible,_hidden:e.onHidden,_nativeSwitch:function(){!0===document[this.hidden]?this._hidden():this._visible()},listen:function(){try{this.isSupported()?document.addEventListener(this.visibilityChange,function(){t._nativeSwitch.apply(t,arguments)},1):document.addEventListener?(window.addEventListener("focus",this._visible,1),window.addEventListener("blur",this._hidden,1)):(document.attachEvent("onfocusin",this._visible),document.attachEvent("onfocusout",this._hidden))}catch(e){}},init:function(){"undefined"!=typeof document.hidden?(this.hidden="hidden",this.visibilityChange="visibilitychange"):"undefined"!=typeof document.mozHidden?(this.hidden="mozHidden",this.visibilityChange="mozvisibilitychange"):"undefined"!=typeof document.msHidden?(this.hidden="msHidden",this.visibilityChange="msvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(this.hidden="webkitHidden",this.visibilityChange="webkitvisibilitychange"),this.listen()}};t.init()},getRgba:function(e){return"object"!=typeof e?e:"rgba("+e.r+","+e.g+","+e.b+","+e.a+")"},conversionNum:function(e){if(e){if(/^[0|1]?\.\d+$/.test(e))return 100*Number(e)+"%";var t=/^(-?\d+(\.\d+)?)px$/.exec(e);return t?(Number(t[1])/375*window.screen.width).toFixed(2)+"px":e}},boxModel:function(e){return function(t){if("object"!=typeof t)return e+":"+t+";";var n="";for(var p in t)n+=e+"-"+p+":"+_.conversionNum(t[p])+";";return n}},localStorage:{get:function(e){return window.localStorage.getItem(e)},parse:function(e){var t=null;try{t=JSON.parse(_.localStorage.get(e))||null}catch(n){}return t},set:function(e,t){window.localStorage.setItem(e,t)},remove:function(e){window.localStorage.removeItem(e)},isSupport:function(){var e=!0;try{var t="__sensorsdatasupport__",n="testIsSupportStorage";_.localStorage.set(t,n),_.localStorage.get(t)!==n&&(e=!1),_.localStorage.remove(t)}catch(p){e=!1}return e}},addEvent:function(){function e(t){return t&&(t.preventDefault=e.preventDefault,t.stopPropagation=e.stopPropagation,t._getPath=e._getPath),t}e._getPath=function(){var e=this;return this.path||this.composedPath&&this.composedPath()||function(){try{var t=e.target,n=[t];if(null===t||null===t.parentElement)return[];for(;null!==t.parentElement;)t=t.parentElement,n.unshift(t);return n}catch(p){return[]}}()},e.preventDefault=function(){this.returnValue=!1},e.stopPropagation=function(){this.cancelBubble=!0};(function(t,n,p){if(t&&t.addEventListener)t.addEventListener(n,function(t){t._getPath=e._getPath,p.call(this,t)},!1);else{var o="on"+n,i=t[o];t[o]=function(t,n,p){return function(o){if(!(o=o||e(window.event)))return undefined;o.target=o.srcElement;var i,a,r=!0;return"function"==typeof p&&(i=p(o)),a=n.call(t,o),!1!==i&&!1!==a||(r=!1),r}}(t,p,i)}}).apply(null,arguments)},extend:function(e){var t=Array.prototype.slice;return _.each(t.call(arguments,1),function(t){for(var n in t)void 0!==t[n]&&(e[n]=t[n])}),e},extend2Lev:function(e){return _.each(Array.prototype.slice.call(arguments,1),function(t){for(var n in t)void 0!==t[n]&&(_.isObject(t[n])&&_.isObject(e[n])?_.extend(e[n],t[n]):e[n]=t[n])}),e},each:function(e,t,n){var p=Object.prototype.hasOwnProperty,o=Array.prototype.forEach,i={};if(null==e)return!1;if(o&&e.forEach===o)e.forEach(t,n);else if(e.length===+e.length){for(var a=0,r=e.length;a<r;a++)if(a in e&&t.call(n,e[a],a,e)===i)return!1}else for(var s in e)if(p.call(e,s)&&t.call(n,e[s],s,e)===i)return!1},xhr:function(e){if(e)return"undefined"!=typeof window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:"undefined"!=typeof XDomainRequest?new XDomainRequest:null;if("undefined"!=typeof window.XMLHttpRequest)return new XMLHttpRequest;if(window.ActiveXObject)try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}},ajax:function(e){function t(e){if(!e)return"";try{return JSON.parse(e)}catch(t){return{}}}e.timeout=e.timeout||2e4,e.credentials="undefined"==typeof e.credentials||e.credentials;var n=_.xhr(e.cors);if(!n)return!1;e.type||(e.type=e.data?"POST":"GET");var p,o=(e=_.extend({success:function(){},error:function(){}},e)).success,i=e.error;e.success=function(e){o(e),p&&(clearTimeout(p),p=null)},e.error=function(e){i(e),p&&(clearTimeout(p),p=null)},p=setTimeout(function(){!function(){try{_.isObject(n)&&n.abort&&n.abort()}catch(t){sd.log(t)}p&&(clearTimeout(p),p=null,e.error&&e.error(),n.onreadystatechange=null,n.onload=null,n.onerror=null)}()},e.timeout),"undefined"!=typeof XDomainRequest&&n instanceof XDomainRequest&&(n.onload=function(){e.success&&e.success(t(n.responseText)),n.onreadystatechange=null,n.onload=null,n.onerror=null},n.onerror=function(){e.error&&e.error(t(n.responseText),n.status),n.onreadystatechange=null,n.onerror=null,n.onload=null}),n.onreadystatechange=function(){try{4==n.readyState&&(n.status>=200&&n.status<300||304==n.status?e.success(t(n.responseText)):e.error(t(n.responseText),n.status),n.onreadystatechange=null,n.onload=null)}catch(p){n.onreadystatechange=null,n.onload=null}},n.open(e.type,e.url,!0);try{e.credentials&&(n.withCredentials=!0),_.isObject(e.header)&&_.each(e.header,function(e,t){n.setRequestHeader&&n.setRequestHeader(t,e)}),e.data&&(e.cors||n.setRequestHeader&&n.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===e.contentType?n.setRequestHeader&&n.setRequestHeader("Content-type","application/json; charset=UTF-8"):n.setRequestHeader&&n.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(a){sd.log(a)}n.send(e.data||null)},getUuid:function(){var e=function(){return Math.random().toString(16).replace(".","")};return function(){var t=function(){for(var e=1*new Date,t=0;e==1*new Date;)t++;return e.toString(16)+t.toString(16)}()+"-"+e()+"-"+e();return t||(String(Math.random())+String(Math.random())+String(Math.random())).slice(2,15)}},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},isEmptyObject:function(e){var t=Object.prototype.hasOwnProperty;if(_.isObject(e)){for(var n in e)if(t.call(e,n))return!1;return!0}return!1},filter:function(e,t,n){var p=Object.prototype.hasOwnProperty;if(e.filter)return e.filter(t);for(var o=[],i=0;i<e.length;i++)if(p.call(e,i)){var a=e[i];t.call(n,a,i,e)&&o.push(a)}return o},isObject:function(e){return null!=e&&"[object Object]"==Object.prototype.toString.call(e)},getConvertNumberValue:function(e){return _.isString(e)&&(e=Number(e)),Math.floor(1e3*e)/1e3},isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},isString:function(e){return"[object String]"==Object.prototype.toString.call(e)},isDate:function(e){return"[object Date]"==Object.prototype.toString.call(e)},isBoolean:function(e){return"[object Boolean]"==Object.prototype.toString.call(e)},isNumber:function(e){return"[object Number]"==Object.prototype.toString.call(e)&&/[\d\.]+/.test(String(e))},isFunction:function(e){if(!e)return!1;var t=Object.prototype.toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},getURLSearchParams:function(e){for(var t=function(e){return decodeURIComponent(e)},n={},p=(e=e||"").substring(1).split("&"),o=0;o<p.length;o++){var i=p[o].indexOf("=");if(-1!==i){var a=p[o].substring(0,i),r=p[o].substring(i+1);a=t(a),r=t(r),n[a]=r}}return n},URL:function(e){var t,n={},p=["hash","host","hostname","href","origin","password","pathname","port","protocol","search","username"];if("function"==typeof window.URL&&function(){try{return"http://modernizr.com/"===new URL("http://modernizr.com/").href}catch(e){return!1}}())(n=new URL(e)).searchParams||(n.searchParams=(t=_.getURLSearchParams(n.search),{get:function(e){return t[e]}}));else{if(!1===/^https?:\/\/.+/.test(e))throw"Invalid URL";var o=document.createElement("a");o.href=e;for(var i=p.length-1;i>=0;i--){var a=p[i];n[a]=o[a]}n.hostname&&"string"==typeof n.pathname&&0!==n.pathname.indexOf("/")&&(n.pathname="/"+n.pathname),n.searchParams=function(){var e=_.getURLSearchParams(n.search);return{get:function(t){return e[t]}}}()}return n},contentLoaded:function(e,t){var n=!1,p=!0,o=e.document,i=o.documentElement,a=o.addEventListener,r=a?"addEventListener":"attachEvent",s=a?"removeEventListener":"detachEvent",u=a?"":"on",l=function(p){"readystatechange"==p.type&&"complete"!=o.readyState||(("load"==p.type?e:o)[s](u+p.type,l,!1),!n&&(n=!0)&&t.call(e,p.type||p))},c=function(){try{i.doScroll("left")}catch(e){return void setTimeout(c,50)}l("poll")};if("complete"==o.readyState)t.call(e,"lazy");else{if(!a&&i.doScroll){try{p=!e.frameElement}catch(_){}p&&c()}o[r](u+"DOMContentLoaded",l,!1),o[r](u+"readystatechange",l,!1),e[r](u+"load",l,!1)}},indexOf:function(e,t){var n=e.indexOf;if(n)return n.call(e,t);for(var p=0;p<e.length;p++)if(t===e[p])return p;return-1}};popup._=_,popup.isSupportPopup=function(){return _.localStorage.isSupport()},popup.listenPageStateChange=function(){var e=!0;_.visibility({onVisible:function(){popup.log("\u9875\u9762\u89e6\u53d1visible-",(new Date).getMinutes(),"\u5206",(new Date).getSeconds()),!1===e&&(popup.updateDataAndSetListen.startState(),e=!0)},onHidden:function(){popup.log("\u9875\u9762\u89e6\u53d1hidden-",(new Date).getMinutes(),"\u5206",(new Date).getSeconds()),!0===e&&(popup.updateDataAndSetListen.stopAllState(),e=!1)}})},popup.getWebSDK=function(){return!!(_.isObject(window.sensorsDataAnalytic201505)&&_.isObject(window.sensorsDataAnalytic201505.readyState)&&window.sensorsDataAnalytic201505.readyState.state>=3)&&window.sensorsDataAnalytic201505},popup.getPopupInfo=function(e){if(!_.isObject(e)||!_.isObject(e.template))return{};var t={$sf_msg_title:"",$sf_msg_content:"",$sf_msg_image_url:""};return function n(e){_.each(e.subviews,function(e){var p=e.properties||{};"title"===p.msgType?t.$sf_msg_title=p.text:"content"===p.msgType?t.$sf_msg_content=p.text:"image"===e.type&&(t.$sf_msg_image_url=p.image),e.subviews&&n(e)})}(e.template),t},popup.getSFCampaign=function(e){e=_.isObject(e)?e:{};var t={planId:"",name:"",content:null,type:""};return t.planId=e.plan_id||"",t.name=e.cname||"",t.content=_.isObject(e.popup_window_content)?e.popup_window_content.content:"",t.type=_.isObject(e.popup_window_content)&&e.popup_window_content.popup_type?e.popup_window_content.popup_type:"PRESET",t},popup.getImageList=function(e){if(!_.isArray(e))return!1;for(var t,n,p=new RegExp('("(backgroundImage|image)":"(http(s)?://.[^"]*)")',"g"),o=new RegExp('http(s)?://.[^S^"]*'),i={},a=e.length,r=[],s=0;s<a;s++)if(_.isObject(e[s])&&"ACTIVE"===e[s].status.toLocaleUpperCase()&&!0===e[s].is_audience&&(e[s].strategy_id?!1!==e[s].is_trigger:!0!==e[s].is_control_group)&&e[s].popup_window_content&&e[s].popup_window_content.content&&(t=e[s].popup_window_content.content.match(p)))for(var u=0,l=t.length;u<l;u++)(n=t[u].match(o))&&n.length>0&&(i[n[0]]||(i[n[0]]=1));return _.each(i,function(e,t){r.push(t)}),r},popup.setIsLoad=function(){if(window.self===window.top){if(window[popup.config.loadedSign])return!1;if("undefined"==typeof window[popup.config.loadedSign])return window[popup.config.loadedSign]=!0,!0}else try{return!window.top[popup.config.loadedSign]&&(window.top[popup.config.loadedSign]=!0,!0)}catch(e){return popup.log("\u975e\u540c\u57df\u540diframe\u5185\u5d4c\u4e0d\u80fd\u83b7\u53d6\u7236\u7ea7\u7a97\u4f53\u5185\u5bb9",e),!0}};var IMAGE_MAP={close:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAMAAAAPdrEwAAAAe1BMVEUAAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////NgkbwAAAAKHRSTlMA5if6t/B0UjMSxpAtJB4MBfTr30oY6NjV0r2loZ6XkoaBenFp3UA/LNePaQAAAsxJREFUWMOsltlygzAMRRXMZsAsAZJmX9v6/7+wg1QXpjGxCDkvyWTIQZauDcCgzKLrPtnUSyGW9SbZX6OshDcQh36lH6j8MJ7pTZd6lGX6sr0IP7SDj7CA6chLoBkEFzm14nM1/P/2eGti1RZFq+LmdtwGw7afJ1Ue1dogcGCW4QptqCO2OPe1IbnL0Y7dE23wc2bJgSn44MFTvIMwLeMUXqZGfGKUkp+MPC2dwUjMGhWwUL7pnXRUsdbIIpow84VG1k9Xmf1e5U8Kq/R/68memAPqcggTCQUNc9SdL+iCL5jMd0B1j/RErh3LYrRyLa2po2x8KngJ9Uk5sWUwpZoVvIiiulNLhMwgHDhDED2MEH8X3zCDL4HV/R8lRTOEWYS0KWzt8GEm/mNLihpHKOeqJY6yLqDnbO42F1r9eXCzitMOfkuqfvkXTId6h1phSi5/ncbgneAtnDCAxTAzIn+POhfDFOObzAEsNLu0HXO06a4BCwd89wEk1h2ezdwl0rObvS5nNreHurg/lxKwsNPoHjXrHVhI+lMK3xjvMH4YelYzCSzc8V3zrx9CWtu5MG67eWEdhBSmI+GT7eIZt+Nny7YJ+y8ON9/cF1tWVL7LzTdTi6sSMtw9AE432wwl7u6MzqotMNwcM7Glc/TafRyB4+aa4dhdcoV993EDlptphlt3zZ72TgM8N88MDe3vDQWE5V6tWGaKyAbwqaiA5+aZQeETkk6QFtxuvhlaOkVwwxfgdq/IvHKbocBj6ac5OzYCIASBKGo10n+HBgakMswbaYDgTmX3fzgafhD4G+Hhg1cGXnT4PMFHVayCdVcBXGBu7cKwACOOC2YwTsIQ7KI7LBywJrlyByupK9Kw/lto4VFLAqLdmRwJiBDWwjDOI0QPPhPXRn3yTlyrILND4w7oOw3h5AlTPk5U/ddrZSk4RWW+C9hp2rgru6GiP/678n2UFPV1AAAAAElFTkSuQmCC"},NODE_NAME_MAP={row:"div",column:"div",label:"pre",image:"img",button:"button",link:"button",image_button:"img"},NODE_STYLE_MAP={textAlign:"text-align",font:"font-size",backgroundColor:"background-color",borderWidth:function(e){return"border-width: "+e+";border-style: solid;"},borderColor:"border-color",cornerRadius:"border-radius",backgroundImage:function(e){return"background-image:url("+e+");background-repeat: no-repeat;background-size: 100% 100%;"},margin:_.boxModel("margin"),padding:_.boxModel("padding"),maxHeight:"max-height",maxWidth:"max-width",scrollableX:function(e){if(e)return"overflow-x:auto;"},scrollableY:function(e){if(e)return"overflow-y:auto;"}};function ElementRender(e){this.properties=e.properties,this.template=e.template,this.maskEle=null,this.containerEle=null,this.msg={$sf_msg_title:"",$sf_msg_content:"",$sf_msg_image_url:"",$sf_succeed:"",$sf_fail_reason:"",$sf_msg_id:"",plan:{}},this.popupCheckInstance=null}ElementRender.prototype={constructor:ElementRender,render:function(){var e=this;return!document.querySelector("div[data-sf-mask]")&&(e.template.isRoot=!0,e.containerEle=e.createView(e.template),e.maskEle=e.getElement({nodeName:"div",style:e.getStyle({position:"fixed",width:"100%",height:"100%",top:"0px",left:"0px",backgroundColor:_.getRgba(e.properties.maskColor),"z-index":999998})}),_.addEvent(e.maskEle,"click",function(t){if(t.target.getAttribute("data-ele-mask")&&e.properties.maskCloseEnabled)return popup.track.maskClick(e),!1;popup.track.elementClickCallback(t,e)}),e.maskEle.setAttribute("data-sf-mask",!0),e.maskEle.appendChild(e.containerEle),_.contentLoaded(window,function(){e.appendPopup()}),!0)},appendPopup:function(){if(window.self===window.top)document.body.appendChild(this.maskEle);else try{window.top.document.body.appendChild(this.maskEle)}catch(e){document.body.appendChild(this.maskEle)}},getElement:function(e){var t=e.nodeName||"div",n=e.style,p=e.attr,o=e.child,i=e.action,a=e.element_info,r=document.createElement(t);return n&&r.setAttribute("style",n),p&&_.each(p,function(e,t){e&&(r[t]=e)}),o&&o.length&&_.each(o,function(e){if(!e)return!1;r.appendChild(e)}),i&&i.H5&&i.H5.length&&r.setAttribute("data-action",JSON.stringify(i.H5)),a&&r.setAttribute("data-info",JSON.stringify(a)),r},getStyle:function(e){var t="",n=["msgType","text","image","name","isHidden","align","localImageName"];return _.each(e,function(e,p){e=_.conversionNum(e);var o=NODE_STYLE_MAP[p];if(_.indexOf(n,p)>=0)return!1;_.isString(o)?t+=o+":"+_.getRgba(e)+";":_.isFunction(o)?t+=o(e)+";":t+=p+":"+_.getRgba(e)+";"}),t},createView:function(e){var t=[],n={"box-sizing":"border-box",display:"block","pointer-events":"auto",overflow:"hidden"},p={},o=NODE_NAME_MAP[e.type]||null;e.properties=e.properties||{},e.layout=e.layout||{};var i=e.properties.font,a=i?1.7*parseInt(i)+"px":"normal";if(e.properties.isHidden)return!1;switch(e.properties.text?p.innerText=e.properties.text:e.properties.image&&(e.properties.localImageName?p.src=IMAGE_MAP[e.properties.localImageName]:p.src=e.properties.image),e.isRoot&&(e.layout.margin.top="-40px",_.extend(n,{position:"relative","z-index":999999,"pointer-events":"none"})),e.type){case"row":n.display="flex";break;case"link":_.extend(n,{"text-decoration":"underline",outline:"none","letter-spacing":"1px","line-height":a});break;case"label":_.extend(n,{"white-space":"pre-wrap","word-wrap":"break-word","letter-spacing":"1px","line-height":a,"margin-top":"0px","margin-bottom":"0px"});break;case"button":_.extend(n,{outline:"none","letter-spacing":"1px","line-height":a})}_.extend(n,e.layout,e.properties),e.subviews&&e.subviews.length>0&&_.each(e.subviews,function(e){t.push(this.createView(e))},this);var r=this.getElement({element_info:{$sf_msg_element_type:e.type,$sf_msg_element_content:e.properties.text||""},nodeName:o,attr:p,style:this.getStyle(n),child:t,action:e.action});if(e.layout.align){var s=document.createElement("div");n="display:flex;justify-content:"+{center:"center",left:"flex-start",right:"flex-end"}[e.layout.align]+";";return e.isRoot?(n+="width:100%;height:100%;overflow-y:auto;box-sizing: border-box;align-items:center;",s.setAttribute("style",n),s.setAttribute("data-ele-mask",!0)):s.setAttribute("style",n),s.appendChild(r),s}return r},destory:function(){var e=this.msg.plan.plan_id||"";if(window.self===window.top)document.body.removeChild(this.maskEle);else try{window.top.document.body.removeChild(this.maskEle)}catch(t){document.body.removeChild(this.maskEle)}popup.info.popup_listener.onClose(e),popup.info.popup_campaign_listener.onEnd(popup.getSFCampaign(this.msg.plan)),this.popupCheckInstance&&this.popupCheckInstance.resetPopupIntervalWindow()}},popup.ElementRender=ElementRender,popup.handlerCampaign=function(e){var t,n=e,p=_.getUuid()(),o=n.plan.popup_window_content;if(!_.isObject(o))return n.popupFailed(1001,!1,{uuid:p,content:"",plan:n.plan}),!1;if(o.content)try{t=JSON.parse(o.content)}catch(u){popup.log(u)}var i=popup.getSFCampaign(n.plan),a={state:"",isCustom:!1},r=!0;try{r=popup.info.popup_campaign_listener.shouldStart(i)}catch(u){r=!1,popup.log(u)}var s={uuid:p,content:t,plan:n.plan};switch(n.plan.strategy_id?n.plan.is_trigger?r?"CUSTOMIZED"===o.popup_type?"withoutCampaignListener"===popup.info.supportCustom?a.state="CAMPAIGN_CUSTOMIZED_NULL_LISTENER":"withoutStart"===popup.info.supportCustom?a.state="CAMPAIGN_CUSTOMIZED_LISTENER_NULL_START":_.isString(o.content)?a.state="CAMPAIGN_TRIGGER_CUSTOMIZED_START":a.state="DIALOG_NOT_SHOW_JSON_FAILED":"PRESET"===o.popup_type&&_.isObject(t)&&_.isObject(t.properties)&&_.isObject(t.template)?a.state="DIALOG_SHOW":a.state="DIALOG_NOT_SHOW_JSON_FAILED":a.state="CAMPAIGN_NOT_START_LISTENER_START":a.state="CAMPAIGN_NOT_START_TRIGGER":n.plan.is_control_group?a.state="DIALOG_NOT_SHOW":r?_.isObject(t)&&t.properties&&t.template?a.state="DIALOG_SHOW":a.state="DIALOG_NOT_SHOW_JSON_FAILED":a.state="CAMPAIGN_NOT_START_LISTENER_START",a.isCustom=!(!o.popup_type||"CUSTOMIZED"!==o.popup_type),popup.log("campaign:",a,"plan:",n.plan.cname),a.state){case"DIALOG_SHOW":n.showPopup(s);break;case"CAMPAIGN_TRIGGER_CUSTOMIZED_START":n.customCampaign(s);break;case"CAMPAIGN_NOT_START_LISTENER_START":n.popupFailed(1004,a.isCustom,s);break;case"CAMPAIGN_CUSTOMIZED_NULL_LISTENER":case"CAMPAIGN_CUSTOMIZED_LISTENER_NULL_START":n.popupFailed(1006,a.isCustom,s);break;case"DIALOG_NOT_SHOW_JSON_FAILED":n.popupFailed(1001,a.isCustom,s);break;case"CAMPAIGN_NOT_START_TRIGGER":n.popupFailed(1005,a.isCustom,s);break;case"DIALOG_NOT_SHOW":n.popupFailed(1003,a.isCustom,s);break;default:popup.log("CampaignState\u5f02\u5e38")}},popup.track={getPublicProps:function(e){var t=e.plan,n={$sf_lib_version:popup.lib_version,$sf_plan_type:"\u8fd0\u8425\u8ba1\u5212",$sf_channel_service_name:"SENSORS_FOCUS",$sf_channel_category:"POPUP",$sf_platform_tag:popup.info.platform,$sf_msg_id:e.$sf_msg_id};return _.isEmptyObject(t)||!_.isObject(t)?n:(n.$sf_plan_id=t.plan_id+"",n.$sf_plan_strategy_id=t.strategy_id?t.strategy_id:t.is_control_group?"-1":"0",t.audience_id&&(n.$sf_audience_id=t.audience_id+""),n)},popupDisplay:function(e){var t={$sf_msg_title:e.$sf_msg_title,$sf_msg_content:e.$sf_msg_content,$sf_msg_image_url:e.$sf_msg_image_url,$sf_succeed:e.$sf_succeed,$sf_fail_reason:e.$sf_fail_reason};this.trackEvent("$PlanPopupDisplay",t,e)},trackEvent:function(e,t,n){var p=popup.track.getPublicProps(n);_.extend(t,p),_.each(t,function(e,n){""!==e&&e!==undefined||delete t[n]}),popup.sa.track(e,t)},maskClick:function(e){if(!e.msg)return!1;var t={$sf_close_type:"POPUP_CLOSE_MASK",$sf_msg_title:e.msg.$sf_msg_title,$sf_msg_content:e.msg.$sf_msg_content,$sf_msg_image_url:e.msg.$sf_msg_image_url,$sf_msg_element_type:"mask",$sf_msg_action_id:e.properties.maskActionId};this.trackEvent("$PlanPopupClick",t,e.msg),e.destory()},elementClickCallback:function(e,t){var n=e.target,p=n.getAttribute("data-action"),o=n.getAttribute("data-info"),i=t.msg||{};if(!p)return!1;try{var a=(JSON.parse(p)||{})[0],r=JSON.parse(o)||{}}catch(e){popup.log("elementClickCallback error",e)}var s={type:a.type,value:_.isString(a.value)?a.value:"",extra:_.isObject(a.value)?a.value:""},u=t.msg.plan?t.msg.plan.plan_id:"",l={$sf_msg_title:i.$sf_msg_title,$sf_msg_content:i.$sf_msg_content,$sf_msg_image_url:i.$sf_msg_image_url,$sf_msg_element_type:r.$sf_msg_element_type,$sf_msg_element_content:r.$sf_msg_element_content,$sf_msg_element_action:a.type,$sf_msg_action_id:a.id,$sf_close_type:"close"===a.type?a.$sf_close_type:""};this.trackEvent("$PlanPopupClick",l,i);try{popup.info.popup_listener.onClick(u,s)}catch(e){popup.log("popup_listener.onClick error",e)}if("close"===a.type)t.destory();else if(a.closeable&&t.destory(),"auto"===popup.info.popup_listener.openlink&&"openlink"===a.type){if("http"!==a.value.slice(0,4))return!1;window.location.href=a.value}}};var salog=popup.log;popup.changeCovertStatus=function(e){var t=JSON.parse(JSON.stringify(popup.convertPlans));_.each(t,function(t,n){if(!t.is_in_convert_window)return!1;var p=t.is_in_convert_window.step,o=t.is_in_convert_window.uuid;if(popup.convertPlans[n].is_in_convert_window.step=Math.min(2*p,6e5),!e)return!1;_.each(e,function(e){e.popup_display_uuid===o&&e.convert_time&&(salog("--\u8f6c\u5316\u7a97\u53e3- \u76ee\u6807\u4e8b\u4ef6\u5df2\u7ecf\u5b8c\u6210 - \u6ee1\u8db3",popup.convertPlans[n].plan_id),delete popup.convertPlans[n].is_in_convert_window,popup.convertPlans.splice(n,1))})}),popup.updateDataAndSetListen.updateLocalData()},popup.asyncConvert=function(e){var t=popup.info.project,n=!1;if(!e&&0===popup.convertPlans.length)return!1;e&&(_.each(popup.convertPlans,function(t){t.plan_id===e.plan_id&&(n=!0)}),n||popup.convertPlans.push(e)),function p(){if(_.isEmptyObject(popup.localData)||!_.isArray(popup.convertPlans)||0===popup.convertPlans.length)return!1;var e=JSON.parse(JSON.stringify(popup.convertPlans)),n=e[0].is_in_convert_window&&e[0].is_in_convert_window.step||5e3,o=[];if(_.each(e,function(e,t){return!!e.is_in_convert_window&&((new Date).getTime()>e.is_in_convert_window.expire_time?(salog("--\u8f6c\u5316\u7a97\u53e3\u8d85\u65f6\u5df2\u7ecf\u8fc7\u671f - \u6ee1\u8db3",popup.convertPlans[t].plan_id),delete popup.convertPlans[t].is_in_convert_window,popup.convertPlans.splice(t,1),popup.updateDataAndSetListen.updateLocalData(),!1):(o.push(e.is_in_convert_window.uuid),e.is_in_convert_window.step||(e.is_in_convert_window.step=5e3,popup.convertPlans[t].is_in_convert_window.step=5e3),void(n>e.is_in_convert_window.step&&(n=e.is_in_convert_window.step))))}),!o.length)return!1;popup.asyncConvert.timer&&clearTimeout(popup.asyncConvert.timer),popup.asyncConvert.timer=setTimeout(function(){_.ajax({url:popup.info.api_base_url+"/sfo/popup_displays?project="+encodeURIComponent(t)+"&popup_display_uuids="+encodeURIComponent(o)+"&time="+(new Date).getTime(),type:"GET",cors:!0,credentials:!1,contentType:"application/json",success:function(e){popup.changeCovertStatus(e),p()},error:function(){popup.changeCovertStatus(),p()}})},n)}()},popup.ruleTime={getExpire:function(e,t){var n=t,p=Number(e.value)||0,o=Number(e.value)||0,i=String(e.unit).toLowerCase(),a=null,r={day:function(){return(a=new Date(n)).setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+864e5*(o-1)},week:function(){var e=(a=new Date(n)).getDay();0===e&&(e=7);var t=7-e;return a.setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+24*t*60*60*1e3+7*(o-1)*24*60*60*1e3},month:function(){var e=(a=new Date(n)).getMonth()+o;return e>=11?(a.setFullYear(a.getFullYear()+parseInt(e/12)),a.setMonth(e%12)):a.setMonth(e),a.setDate(1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0),a.getTime()},second:function(e){var t={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return a=new Date(n),e in t&&(o=t[e]*p),a.getTime()+o}};return!0!==e.natural?r.second(i):i in r?r[i]():void 0},getLast:function(e,t){var n=Number(e.value)||0,p=Number(e.value)-1||0,o=String(e.unit).toLowerCase(),i=null,a={day:function(){return(i=new Date(t)).setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-864e5*p},week:function(){var e=(i=new Date(t)).getDay();return 0===e&&(e=7),--e,i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-(24*e*60*60*1e3+7*p*24*60*60*1e3)},month:function(){var e=(i=new Date(t)).getMonth()+1-p;return e<=0?(i.setFullYear(i.getFullYear()+(parseInt(e/12)-1)),i.setMonth(12+e%12-1)):i.setMonth(e-1),i.setDate(1),i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.getTime()},second:function(e){var p={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return i=new Date(t),e in p&&(o=p[e]*n),i.getTime()-o}};return!0!==e.natural?a.second(o):o in a?a[o]():void 0},getArrMatchCount:function(e,t){var n=0;for(n=0;n<e.length;n++)if(t>=e[n])return n;return e.length}},popup.eventTriggerProcess=function(){if(!popup.updateDataAndSetListen.active_state)return!1;if(!_.isArray(popup.localData.eventQueue))return!1;if(0===popup.localData.eventQueue.length)return!1;if(popup.isRun)return!1;salog("\u4e8b\u4ef6\u961f\u5217---eventQueue",popup.localData.eventQueue);var e=!1,t=popup.localData.eventQueue[0],n=popup.eventRule[t.event];popup.isRun=!0,popup.localData.eventQueue.shift(),popup.updateDataAndSetListen.updateLocalData(),_.isArray(n)&&_.isObject(n[0])&&n.length>0&&(salog("--------------------\u89e6\u53d1\u4e8b\u4ef6\u5f00\u59cb--------------------"),_.each(n,function(e){_.isObject(e)&&"undefined"!=typeof e.match_state&&delete e.match_state,new popup.RuleCheck(e,t)}),_.each(n,function(t){!0===t.match_state?!1===e?(e=!0,salog("\u68c0\u67e5\u5b8c\u6bd5-\u4f18\u5148\u5f39\u7a97-\u5f00\u59cb",t.plan.cname),new popup.PopupCheck(t,!0)):!0===e&&(salog("\u68c0\u67e5\u5b8c\u6bd5-\u975e\u4f18\u5148\u5f39\u7a97-\u4e0d\u6e32\u67d3",t.plan.cname),new popup.PopupCheck(t,!1)):salog("\u68c0\u67e5\u5b8c\u6bd5-\u8ba1\u5212-\u4e0d\u6ee1\u8db3",t.plan.cname)}),e||popup.completeWindowLifecycle(),salog("--------------------\u89e6\u53d1\u4e8b\u4ef6\u7ed3\u675f--------------------"))},popup.completeWindowLifecycle=function(){popup.isRun=!1,popup.eventTriggerProcess()},popup.PopupCheck=function(e,t){this.plan=e.plan,this.current_time=(new Date).getTime(),t?this.renderPopup():this.hidePopup(),popup.updateDataAndSetListen.updateLocalData()},popup.PopupCheck.prototype.createPopupWindow=function(e,t){this.startConvertWindow(e),this.startPopupIntervalWindow(this.current_time),this.startPopupLimitWindow(),this.setGlobalLimit(),this.deletePlanAllWindow(),t&&popup.completeWindowLifecycle()},popup.PopupCheck.prototype.hidePopup=function(){this.deletePlanAllWindow()},popup.PopupCheck.prototype.renderPopup=function(){popup.handlerCampaign(this)},popup.PopupCheck.prototype.popupFailed=function(e,t,n){var p={1001:"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",1003:"\u5bf9\u7167\u7ec4",1004:"campaignShouldStart \u63a5\u53e3\u8fd4\u56de false",1005:"\u8ba1\u5212\u4e0b\u53d1 is_trigger \u4e3a false",1006:"\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03"}[e],o=popup.getPopupInfo(n.content);o.$sf_msg_id=n.uuid,o.plan=n.plan,o.$sf_succeed=!1,o.$sf_fail_reason=p,popup.track.popupDisplay(o),!t&&popup.info.popup_listener&&_.isFunction(popup.info.popup_listener.onLoadFailed)&&popup.info.popup_listener.onLoadFailed(n.plan.plan_id,e,p),popup.info.popup_campaign_listener.onFailed(popup.getSFCampaign(n.plan),e,p),this.createPopupWindow(n.uuid,!0)},popup.PopupCheck.prototype.customCampaign=function(e){var t=popup.getSFCampaign(e.plan),n=popup.getPopupInfo(e.content);n.$sf_msg_id=e.uuid,n.plan=e.plan,n.$sf_succeed=!0,popup.track.popupDisplay(n),popup.info.popup_campaign_listener.onStart(t),this.createPopupWindow(e.uuid,!0)},popup.PopupCheck.prototype.showPopup=function(e){if(!popup.ElementRender)return popup.log("\u6682\u4e0d\u652f\u6301\u9884\u7f6e\u5f39\u7a97UI"),!1;var t=new popup.ElementRender(e.content),n=popup.getPopupInfo(e.content);if(n.$sf_msg_id=e.uuid,n.plan=e.plan,n.$sf_succeed=!0,_.extend(t.msg,n),t.popupCheckInstance=this,popup.track.popupDisplay(n),!t.render())return salog("\u5f53\u524d\u9875\u9762\u5df2\u6709\u4e00\u4e2a\u5f39\u6846\u6b63\u5728\u6e32\u67d3\uff0c\u672c\u6b21\u5f39\u6846\u4e0d\u6e32\u67d3\uff01"),!1;popup.info.popup_campaign_listener.onStart(popup.getSFCampaign(e.plan)),this.createPopupWindow(e.uuid),popup.info.popup_listener.onLoadSuccess(e.plan.plan_id)},popup.PopupCheck.prototype.startConvertWindow=function(e){salog("--\u5f39\u7a97\u5c55\u793a-\u8f6c\u5316\u7a97\u53e3\u8bbe\u7f6e",this.plan.cname),_.isObject(this.plan.convert_window)&&this.plan.convert_window.value&&(this.plan.is_in_convert_window={expire_time:popup.ruleTime.getExpire(this.plan.convert_window,this.current_time),start_time:this.current_time,uuid:e},popup.asyncConvert(this.plan))},popup.PopupCheck.prototype.startPopupIntervalWindow=function(e){_.isObject(this.plan.popup_interval)&&this.plan.popup_interval.value&&(this.plan.is_in_popup_interval_window=popup.ruleTime.getExpire(this.plan.popup_interval,e))},popup.PopupCheck.prototype.resetPopupIntervalWindow=function(){var e=(new Date).getTime();this.startPopupIntervalWindow(e),this.resetGlobalLimit(e),popup.completeWindowLifecycle()},popup.PopupCheck.prototype.startPopupLimitWindow=function(){salog("--\u5f39\u7a97\u5c55\u793a-\u53c2\u4e0e\u9650\u5236\u7a97\u53e3\u8bbe\u7f6e\u91cd\u7f6e"),_.isObject(this.plan.re_enter)&&this.plan.re_enter.value&&(_.isObject(this.plan.is_in_popup_limit_window)?this.plan.is_in_popup_limit_window.count++:this.plan.is_in_popup_limit_window={expire_time:popup.ruleTime.getExpire(this.plan.re_enter,this.current_time),count:1})},popup.PopupCheck.prototype.setGlobalLimit=function(){salog("--\u5f39\u7a97\u5c55\u793a-\u5168\u5c40\u5f39\u7a97\u6b21\u6570\u8bbe\u7f6e"),_.isArray(popup.localData.global_popup_count)||(popup.localData.global_popup_count=[]),popup.localData.global_popup_count.unshift(this.current_time);for(var e=popup.localData.global_popup_count,t=e[e.length-1];t+7776e6<this.current_time||e.length>3e3;)e.pop(),t=e[e.length-1]},popup.PopupCheck.prototype.resetGlobalLimit=function(e){_.isArray(popup.localData.global_popup_count)&&popup.localData.global_popup_count.length>0&&(popup.localData.global_popup_count.shift(),popup.localData.global_popup_count.unshift(e))},popup.PopupCheck.prototype.deletePlanAllWindow=function(){var e=this.plan.pattern_popup.matcher_list;_.isArray(e)&&_.each(e,function(e){e.is_in_window&&(salog("--\u5f39\u7a97\u5c55\u793a-\u91cd\u7f6e\u5404\u4e2a\u89c4\u5219\u7684\u7a97\u53e3\u8ba1\u7b97-\u6210\u529f"),delete e.is_in_window)})},popup.RuleCheck=function(e,t){this.plan_match=e,this.plan=e.plan,this.rule_arr=e.rule,this.event_data=t,this.current_time=(new Date).getTime();var n="-------------\u68c0\u67e5-\u8ba1\u5212-("+this.plan.cname+")";_.each(this.rule_arr,function(e){n+="--\u5305\u542b\u89c4\u5219-("+e.event_name+"\uff09-\u89e6\u53d1"+e.params[0]+"\u6b21"}),salog(n),salog(this.plan),this.checkPlanIsExpire(),popup.updateDataAndSetListen.updateLocalData()},popup.RuleCheck.prototype.checkPlanIsExpire=function(){!this.plan.expire_at||_.isNumber(this.plan.expire_at)&&this.current_time<this.plan.expire_at?(salog("--\u8fc7\u671f-\u6ee1\u8db3",this.plan.cname),this.checkPlanIsAudience()):salog("--\u8fc7\u671f-\u4e0d\u6ee1\u8db3",this.plan.cname)},popup.RuleCheck.prototype.checkPlanIsAudience=function(){!0===this.plan.is_audience?(salog("--\u662f\u5426\u53d7\u4f17-\u6ee1\u8db3",this.plan.cname),this.checkPlanSuspend()):salog("--\u662f\u5426\u53d7\u4f17-\u4e0d\u6ee1\u8db3",this.plan.cname)},popup.RuleCheck.prototype.checkPlanSuspend=function(){this.plan.status&&"SUSPEND"===this.plan.status?salog("--\u6682\u505c-\u4e0d\u6ee1\u8db3",this.plan.cname):(salog("--\u6682\u505c-\u6ee1\u8db3",this.plan.cname),this.checkConvert())},popup.RuleCheck.prototype.checkConvert=function(){if(_.isObject(this.plan.is_in_convert_window)&&this.plan.is_in_convert_window.expire_time>this.current_time)salog("--\u5b58\u5728\u8f6c\u5316\u7a97\u53e3 - \u4e0d\u6ee1\u8db3",this.plan.is_in_convert_window);else if(_.isObject(this.plan.is_in_convert_window)&&this.current_time>this.plan.is_in_convert_window.expire_time){salog("--\u8f6c\u5316\u7a97\u53e3\u8d85\u65f6\u5df2\u7ecf\u8fc7\u671f - \u6ee1\u8db3",this.plan.plan_id),delete this.plan.is_in_convert_window;for(var e=0;e<popup.convertPlans.length;e++)this.plan.plan_id===popup.convertPlans[e].plan_id&&(popup.convertPlans.splice(e,1),e--);this.checkGlobalPopupInterval()}else salog("--\u4e0d\u5b58\u5728\u8f6c\u5316\u7a97\u53e3 - \u6ee1\u8db3",this.plan.is_in_convert_window),this.checkGlobalPopupInterval()},popup.RuleCheck.prototype.checkGlobalPopupInterval=function(){var e=popup.localData.global_popup_count;if(_.isArray(e)&&e.length>=1){var t=popup.ruleTime.getLast(popup.localData.popup_interval_global,this.current_time);t>e[0]?(salog("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3-"+t+">\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+e[0]),this.checkPopupInterval()):salog("\u68c0\u67e5-\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3-"+t+"<\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+e[0])}else salog("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ca1\u6709\u5f39\u8fc7\u7a97-\u6ee1\u8db3"),this.checkPopupInterval()},popup.RuleCheck.prototype.checkPopupInterval=function(){_.isNumber(this.plan.is_in_popup_interval_window)?this.current_time>this.plan.is_in_popup_interval_window?(salog("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5927\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3"),this.plan.is_in_popup_interval_window=null,this.checkProperties()):salog("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5c0f\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3"):(salog("--\u5f39\u7a97\u95f4\u9694-\u7a97\u53e3\u4e0d\u5b58\u5728-\u65b0\u5f00"),this.plan.is_in_popup_interval_window=null,this.checkProperties())},popup.RuleCheck.prototype.checkProperties=function(){var e={equal:function(e,t){if(!_.isNumber(e)&&!_.isString(e))return!1;for(var n=0,p=t.length;n<p;n++){if(!_.isNumber(t[n])&&!_.isString(t[n]))return!1;if(_.isString(e)){if(e===(_.isString(t[n])?t[n]:String(t[n])))return!0}else if(_.getConvertNumberValue(e)===_.getConvertNumberValue(t[n]))return!0}return!1},notEqual:function(e,t){if(!_.isNumber(e)&&!_.isString(e))return!1;for(var n=0,p=t.length;n<p;n++){if(!_.isNumber(t[n])&&!_.isString(t[n]))return!1;if(_.isString(e)){if(e===(_.isString(t[n])?t[n]:String(t[n])))return!1}else if(_.getConvertNumberValue(e)===_.getConvertNumberValue(t[n]))return!1}return!0},contain:function(e,t){return!!_.isString(e)&&e.indexOf(t[0])>=0},notContain:function(e,t){return!!_.isString(e)&&-1===e.indexOf(t[0])},isTrue:function(e){return!0===e},isFalse:function(e){return!1===e},isSet:function(e){return void 0!==e},notSet:function(e){return void 0===e},isEmpty:function(e){if(!_.isString(e)&&!_.isArray(e))return!1;if(_.isString(e))return""===e;for(var t=0;t<e.length;t++){if(""!==e[t].replace(/^\s+|\s+$/g,""))return!1}return!0},isNotEmpty:function(e){if(!_.isString(e)&&!_.isArray(e))return!1;if(_.isString(e))return""!==e;for(var t=0;t<e.length;t++){if(""===e[t].replace(/^\s+|\s+$/g,""))return!1}return!0},less:function(e,t){return!!_.isNumber(e)&&("undefined"!=typeof t[0]&&_.getConvertNumberValue(e)<_.getConvertNumberValue(t[0]))},greater:function(e,t){return!!_.isNumber(e)&&("undefined"!=typeof t[0]&&_.getConvertNumberValue(e)>_.getConvertNumberValue(t[0]))},between:function(e,t){if(!_.isNumber(e))return!1;if("undefined"==typeof t[0]&&"undefined"==typeof t[1])return!1;var n=_.getConvertNumberValue(e),p=_.getConvertNumberValue(t[0]),o=_.getConvertNumberValue(t[1]);return n>=p&&n<=o},isIn:function(e,t){if(!_.isArray(e))return!1;for(var n=0;n<e.length;n++)if(_.indexOf(t,e[n])>=0)return!0;return!1},notInclude:function(e,t){if(!_.isArray(e))return!1;for(var n=0;n<e.length;n++)if(-1===_.indexOf(t,e[n]))return!0;return!1},absolute_between:function(e,t){try{var n=new Date(t[0]),p=new Date(t[1]),o=new Date(e);return o>=n&&o<=p}catch(i){salog("absolute_between Error",i)}},absoluteBetween:function(e,t){try{var n=new Date(t[0]),p=new Date(t[1]),o=new Date(e);return o>=n&&o<=p}catch(i){salog("absolute_between Error",i)}}},t=this,n=_.filter(this.rule_arr,function(n){if(!n.filter||n.filter.conditions&&0===n.filter.conditions.length)return!0;var p=n.filter,o=p.relation,i="or"===String(o).toLowerCase(),a="and"===String(o).toLowerCase(),r=!!a,s=!0;return _.each(p.conditions,function(n){if(!s)return!1;if(!n.field)return!1;var p=n.field.lastIndexOf("."),o=n.params,u="in"===n["function"]?"isIn":n["function"];if(!e[u])return r=!1,s=!1,!1;if(p<0)return!1;var l=n.field.slice(p+1),c=t.event_data.properties[l],_=e[u](c,o);i&&_&&(r=!0,s=!1),a&&!_&&(r=!1,s=!1)}),r});_.isArray(n)&&n.length>0?(this.checkWindowAndMatch(n),salog("--\u5c5e\u6027\u5339\u914d-\u6ee1\u8db3",n)):salog("--\u5c5e\u6027\u5339\u914d-\u4e0d\u6ee1\u8db3")},popup.RuleCheck.prototype.checkWindowAndMatch=function(e){var t=this,n=[];_.each(e,function(e){if(!e.params||!e.params[0])return salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570\u636e\u5f02\u5e38"),!1;var p=Number(e.params[0]);1===p?n.push(e):p>1&&_.isObject(e.window)&&e.window.value>0&&(!_.isObject(e.is_in_window)||!_.isNumber(e.is_in_window.expire_time)||e.is_in_window.expire_time<t.current_time?e.is_in_window={expire_time:popup.ruleTime.getExpire(e.window,t.current_time),count:1}:e.is_in_window.count=e.is_in_window.count+1,e.is_in_window.count>=p?n.push(e):salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570",e.is_in_window.count,"\u4e0d\u5339\u914d\u5f53\u524d\u6b21\u6570",p))}),n.length>0?(salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",n),this.checkGlobalPopupLimit()):salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6ca1\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",n)},popup.RuleCheck.prototype.checkGlobalPopupLimit=function(){var e=popup.localData.msg_limit_global,t=!0,n=this;_.isObject(e)&&!0===e.is_in_use&&_.isArray(e.limits)&&_.isArray(popup.localData.global_popup_count)&&!0===this.plan.global_msg_limit_enabled?(_.each(e.limits,function(e){if(_.isObject(e)&&_.isNumber(e.limit)){var p=popup.ruleTime.getLast(e,n.current_time),o=popup.ruleTime.getArrMatchCount(popup.localData.global_popup_count,p);salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u5df2\u7ecf\u5f39\u7a97\u6b21\u6570-"+o+"-\u9650\u5236\u7684\u6b21\u6570"+e.limit+"-\u9650\u5236\u65f6\u95f4-"+p),t=o<e.limit?t&&!0:t&&!1}}),t?(salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236- \u6ee1\u8db3"),this.checkPopupLimit()):salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u4e0d\u6ee1\u8db3")):(salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236- \u6ee1\u8db3"),this.checkPopupLimit())},popup.RuleCheck.prototype.checkPopupLimit=function(){if(!_.isObject(this.plan.re_enter)||!_.isNumber(this.plan.re_enter.value)||!_.isNumber(this.plan.re_enter.limit))return this.plan_match.match_state=!0,!1;_.isObject(this.plan.is_in_popup_limit_window)&&_.isNumber(this.plan.is_in_popup_limit_window.expire_time)&&_.isNumber(this.plan.is_in_popup_limit_window.count)?this.plan.is_in_popup_limit_window.expire_time<this.current_time?(salog("--\u53c2\u4e0e\u9650\u5236-\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236\u7a97\u53e3-\u5f00\u542f\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window,this.plan_match.match_state=!0):this.plan.is_in_popup_limit_window.count<this.plan.re_enter.limit?(salog("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4e14\u5728\u53c2\u4e0e\u9650\u5236\u6b21\u6570\u5185-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0):salog("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4f46\u662f\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236-\u4e0d\u6ee1\u8db3",this.plan.is_in_popup_limit_window):(this.plan.is_in_popup_limit_window?(salog("--\u53c2\u4e0e\u9650\u5236-\u6709\u7a97\u53e3\u4f46\u662f\u7a97\u53e3\u6570\u636e\u5f02\u5e38-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window):salog("--\u53c2\u4e0e\u9650\u5236-\u4e0d\u5b58\u5728\u7a97\u53e3-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0)},popup.store={delete_time:2592e6,init:function(){this.migrateLocalData(),popup.localData=this.getLocalData(),_.isNumber(popup.localData.config_pull_interval_ms)&&popup.localData.config_pull_interval_ms>0&&(popup.updateDataAndSetListen.interval_time=popup.localData.config_pull_interval_ms),this.removeLocalData(),popup.log("\u521d\u59cb\u5316-\u83b7\u53d6-\u5185\u5b58-localData")},getJSONData:function(){return _.localStorage.parse(popup.config.storageName)},saveJSONData:function(e){_.localStorage.set(popup.config.storageName,JSON.stringify(e))},migrateLocalData:function(){var e=this.getJSONData()||{},t=popup.sa.store.getDistinctId();if(e.popup_sdk_users&&e.popup_sdk_plans)return!1;var n={popup_sdk_plans:{},popup_sdk_users:{}};n.popup_sdk_plans[t]=e,n.popup_sdk_users[t]={user_id:t},this.saveJSONData(n)},getLocalData:function(){var e=this.getJSONData(),t=popup.sa.store.getDistinctId(),n=null;return e?(_.isObject(e.popup_sdk_users[t])&&e.popup_sdk_users[t].user_id&&(n=e.popup_sdk_users[t].user_id),n&&_.isObject(e.popup_sdk_plans[n])?(e.popup_sdk_plans[n].update_time=(new Date).getTime(),this.saveJSONData(e),e.popup_sdk_plans[n]):{}):{}},saveLocalData:function(){var e=this.getJSONData(),t=popup.sa.store.getDistinctId(),n=null;if(!e)return!1;e.popup_sdk_users&&_.isObject(e.popup_sdk_users[t])&&e.popup_sdk_users[t].user_id&&(n=e.popup_sdk_users[t].user_id,e.popup_sdk_plans[n]=popup.localData,this.saveJSONData(e))},removeLocalData:function(){var e=this.getJSONData(),t=this.delete_time;if(!e||!e.popup_sdk_plans||!e.popup_sdk_users)return!1;var n=JSON.parse(JSON.stringify(e.popup_sdk_plans)),p=JSON.parse(JSON.stringify(e.popup_sdk_users)),o=(new Date).getTime(),i=[];_.each(n,function(n,p){o-n.update_time>t&&(delete e.popup_sdk_plans[p],i.push(p))}),_.each(p,function(t,n){i.length>0&&_.each(i,function(p){t.user_id&&p===t.user_id&&delete e.popup_sdk_users[n]})}),this.saveJSONData(e)}},popup.updateDataAndSetListen={active_state:!0,interval_time:6e5,save_interval:null,data_interval:null,image_list:null,local_data:null,filterConvertPlans:function(){var e=popup.localData.popup_plans;if(!e||!_.isArray(e))return!1;var t=_.filter(e,function(e){return!!e.convert_window&&!!e.is_in_convert_window});popup.convertPlans=t,popup.log("\u521d\u59cb\u5316-\u5f02\u6b65\u7684convertWindow",popup.convertPlans),popup.asyncConvert()},diffData:function(){var e=popup.localData,t=JSON.parse(JSON.stringify(popup.serverData)),n=(new Date).getTime();if(!t||_.isEmptyObject(t))return!1;var p=n-t.server_current_time;if(Math.abs(p)>=6e5)return!1;if(!e||_.isEmptyObject(e)||!e.popup_plans||0===e.popup_plans.length)return _.extend(popup.localData,t),!1;var o=t.popup_plans;_.each(o,function(t,n){var p=null;if(_.each(e.popup_plans,function(e){e.plan_id===t.plan_id&&(p=e,t.audience_id||delete p.audience_id,_.isObject(t.window_update)&&_.each(t.window_update,function(e,n){p.window_update&&p.window_update[n]===e||("trigger_window"===n?p.pattern_popup.matcher_list=t.pattern_popup.matcher_list:"convert_window"===n&&p.is_in_convert_window&&t.convert_window&&p.is_in_convert_window.start_time&&(p.is_in_convert_window.expire_time=popup.ruleTime.getExpire(t.convert_window,p.is_in_convert_window.start_time)))}))}),!p)return!1;if(!t.window_update&&p.last_update_config_time!==t.last_update_config_time)return!1;var i=p.pattern_popup.matcher_list;_.extend2Lev(p,t),p.pattern_popup.matcher_list=i,o[n]=p}),_.extend(popup.localData,t)},getEventRule:function(){var e=popup.localData.popup_plans,t={};if(!e||!_.isArray(e))return!1;_.each(e,function(e){var n=e.pattern_popup.matcher_list;_.each(n,function(n){var p={plan:e,rule:[n]},o=n.event_name,i=!1;if(t[o]){if(_.each(t[o],function(t){t.plan.plan_id===e.plan_id&&(t.rule.push(n),i=!0)}),i)return!1;t[o].push(p)}else t[o]=[p]})}),_.each(t,function(e){e.sort(function(e,t){var n=t.plan.absolute_priority-e.plan.absolute_priority;return 0===n?t.plan.plan_id-e.plan.plan_id:n})}),popup.eventRule=t,popup.log("\u521d\u59cb\u5316-\u5f97\u5230\u4e8b\u4ef6\u548c\u8ba1\u5212\u7684\u5173\u7cfb"),popup.log("--------------------\u521d\u59cb\u5316\u5b8c\u6210--------------------\u7b49\u5f85\u4e8b\u4ef6\u89e6\u53d1\u8ba1\u5212--------------------")},registerListen:function(){var e=this;popup.sa.events.on("send",function(t){t.event&&popup.eventRule[t.event]&&(_.isArray(popup.localData.eventQueue)||(popup.localData.eventQueue=[]),popup.localData.eventQueue.push(t),e.updateLocalData(),popup.eventTriggerProcess())}),popup.sa.events.on("changeDistinctId",function(t){e.changeId()}),popup.sa.events.isReady()},setListenEvent:function(){this.diffData(),this.filterConvertPlans(),this.getEventRule(),this.updateLocalData()},loadImage:function(e){if(e.length<1)return!1;if(JSON.stringify(e)===JSON.stringify(this.image_list))return!1;this.image_list=e;for(var t=0;t<e.length;t++)n=e[t],void 0,(new Image).src=n;var n},getDataFromServer:function(e,t){var n=this,p=encodeURIComponent(popup.sa.store.getDistinctId()),o=encodeURIComponent(popup.info.platform),i=encodeURIComponent(popup.info.project);e=_.isFunction(e)?e:function(){},t=_.isFunction(t)?t:function(){},_.ajax({url:popup.info.api_base_url+"/sfo/user_popup_configs?distinct_id="+p+"&platform="+o+"&project="+i+"&time="+(new Date).getTime()+"&sdk_version="+popup.lib_version,type:"GET",cors:!0,credentials:!1,contentType:"application/json",success:function(p){if(!n.active_state)return t(),!1;popup.log("\u521d\u59cb\u5316-\u4fee\u6539-serverData-ajax\u83b7\u53d6"),_.isObject(p)&&p.server_current_time&&p.popup_plans&&/\d+\.\d+/.test(p.min_sdk_version_required)&&parseFloat(p.min_sdk_version_required)<=parseFloat(popup.lib_version)?(popup.serverData=p,_.isNumber(p.config_pull_interval_ms)&&p.config_pull_interval_ms>0&&(n.interval_time=p.config_pull_interval_ms),popup.serverData.local_update_time=(new Date).getTime(),popup.info.preload_image&&n.loadImage(popup.getImageList(p.popup_plans)),n.updateUserPlans(),n.setListenEvent()):(popup.log("\u521d\u59cb\u5316-\u6570\u636e\u5f02\u5e38-\u8bf7\u6c42\u8fd4\u56de\u7684\u6570\u636e\u9519\u8bef-\u4e2d\u6b62"),popup.serverData={},popup.localData={},n.updateLocalData()),e(),n.setIntervalTime(n.interval_time)},error:function(){if(!n.active_state)return t(),!1;popup.log("\u521d\u59cb\u5316-\u6570\u636e\u5f02\u5e38-\u8bf7\u6c42\u9519\u8bef-\u4e2d\u6b62"),popup.serverData={},e(),n.setIntervalTime(n.interval_time)}})},updateUserPlans:function(){var e=popup.store.getJSONData(),t=popup.sa.store.getDistinctId(),n=popup.serverData.user_id;e.popup_sdk_users[t]={user_id:n||t},n?e.popup_sdk_plans[n]?popup.localData=e.popup_sdk_plans[n]:e.popup_sdk_plans[t]&&(popup.localData=e.popup_sdk_plans[t],delete e.popup_sdk_plans[t]):e.popup_sdk_plans[t]&&(popup.localData=e.popup_sdk_plans[t]),popup.localData.update_time=(new Date).getTime(),popup.store.saveJSONData(e)},setIntervalTime:function(e){var t=this;this.data_interval=setTimeout(function(){popup.log("10\u5206\u949f\u5b9a\u65f6\u66f4\u65b0\u6570\u636e\u5f00\u59cb-------"),t.getDataFromServer()},e)},setFirstListen:function(){var e=this;this.getDataFromServer(function(){e.registerListen()})},updateLocalData:function(){var e=JSON.stringify(popup.localData);this.local_data!==e&&(this.local_data=e,popup.store.saveLocalData())},initial:function(){popup.store.init();var e=popup.localData.local_update_time,t=(new Date).getTime();if(_.isNumber(e)){var n=t-e;n<=0||n>=this.interval_time?this.setFirstListen():(this.setIntervalTime(this.interval_time-n),this.setListenEvent(),this.registerListen(),popup.info.preload_image&&this.loadImage(popup.getImageList(popup.localData.popup_plans)))}else this.setFirstListen()},changeId:function(){this.stopAllState(),this.startState({getLocalData:!1})},stopAllState:function(){this.active_state=!1,popup.eventRule={},this.data_interval&&window.clearTimeout(this.data_interval),this.save_interval&&window.clearInterval(this.save_interval),popup.asyncConvert.timer&&window.clearTimeout(popup.asyncConvert.timer),popup.convertPlans=[],popup.localData={},this.resetState()},resetState:function(){if("WEB"===popup.info.platform)return!1;!document.querySelector("div[data-sf-mask]")&&popup.isRun&&(popup.isRun=!1)},startState:function(e){this.active_state=!0,(e=e||{getLocalData:!0}).getLocalData&&(this.resetState(),popup.localData=popup.store.getLocalData()),this.getDataFromServer()}},popup.testSend={hasParam:function(){var e=_.URL(window.location.href).searchParams,t=e.get("sf_popup_test")||"",n=e.get("popup_window_id")||"",p=e.get("platform");return!(!t||!n)&&{sf_popup_test:t,popup_window_id:n,platform:p}},start:function(){var e=popup.info.project,t=popup.info.platform,n=this.hasParam().popup_window_id,p=this.hasParam().platform,o=encodeURIComponent(popup.sa.store.getDistinctId());if("WEB"===p)return popup.log("WEB\u7aef\u6d4b\u8bd5\u5f39\u7a97\u8bf7\u5728PC\u8bbe\u5907\u6253\u5f00\uff01"),!1;_.ajax({url:popup.info.api_base_url+"/sfo/popup_windows/"+n+"?project="+encodeURIComponent(e)+"&time="+(new Date).getTime()+"&sdk_version="+popup.lib_version+"&platform="+encodeURIComponent(t)+"&distinct_id="+o,type:"GET",credentials:!1,cors:!0,contentType:"application/json",success:function(e){var t,n=_.getUuid();_.isObject(e)||(popup.sa.log("\u6d4b\u8bd5\u5f39\u7a97-\u670d\u52a1\u7aef\u6570\u636e\u683c\u5f0f\u4e0d\u5408\u6cd5",e),e={});try{t=JSON.parse(e.content)}catch(i){popup.sa.log("\u6d4b\u8bd5\u5f39\u7a97-content\u89e3\u6790\u5931\u8d25,content:",e,i)}var p=popup.getPopupInfo(t);p.$sf_msg_id=n;var o={content:e.content,type:e.popup_type||"PRESET"};e.popup_type&&"CUSTOMIZED"===e.popup_type?_.isString(e.content)?"withoutCampaignListener"===popup.info.supportCustom||"withoutStart"===popup.info.supportCustom?(p.$sf_succeed=!1,p.$sf_fail_reason="\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03",popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onFailed(o,1006,"\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03")):(p.$sf_succeed=!0,popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onStart(o)):(p.$sf_succeed=!1,p.$sf_fail_reason="\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onFailed(o,1001,"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e")):_.isObject(t)&&_.isObject(t.properties)&&_.isObject(t.template)?(new popup.ElementRender(t).render(),p.$sf_succeed=!0,popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onStart(o),popup.info.popup_listener.onLoadSuccess()):(p.$sf_succeed=!1,p.$sf_fail_reason="\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",popup.track.popupDisplay(p),popup.info.popup_listener.onLoadFailed("",1001,"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.info.popup_campaign_listener.onFailed(o,1001,"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"))},error:function(e){popup.log("\u6d4b\u8bd5\u5f39\u7a97\u83b7\u53d6\u6570\u636e\u9519\u8bef",e)}})}},popup.setPara=function(e){_.isObject(e)||(e={}),popup.info=_.extend({},popup.defaultPara,e),popup.sa=popup.getWebSDK();var t=popup.sa;if(!t)return popup.log("web js sdk \u8fd8\u6ca1\u6709\u521d\u59cb\u5316\u5b8c\u6210"),!1;if(!_.isString(popup.info.api_base_url)||"http"!==popup.info.api_base_url.slice(0,4))return popup.log("popup \u5fc5\u987b\u586b\u5199\u6709\u6548 api_base_url"),!1;if("http:"===popup.info.api_base_url.slice(0,5)&&"https:"===location.protocol)return popup.log("\u60a8\u7684\u5f53\u524d\u9875\u9762\u662fhttps\u7684\u5730\u5740\uff0capi_base_url \u4e5f\u5fc5\u987b\u662fhttps\uff01"),!1;if(popup.info.api_base_url="/"===popup.info.api_base_url.slice(-1)?popup.info.api_base_url.slice(0,-1):popup.info.api_base_url,!_.isString(t.para.server_url)||"http"!==t.para.server_url.slice(0,4))return popup.log("server_url \u5fc5\u987b\u586b\u5199\u6709\u6548\u6570\u636e\u63a5\u6536\u5730\u5740"),!1;if(popup.info.project||(popup.info.project=_.URL(t.para.server_url).searchParams.get("project")||"default"),_.isObject(popup.info.popup_listener)){var n=popup.info.popup_listener;_.isFunction(n.onClick)||(popup.info.popup_listener.onClick=function(){}),_.isFunction(n.onLoadSuccess)||(popup.info.popup_listener.onLoadSuccess=function(){}),_.isFunction(n.onLoadFailed)||(popup.info.popup_listener.onLoadFailed=function(){}),_.isFunction(n.onClose)||(popup.info.popup_listener.onClose=function(){}),_.isString(n.openlink)?"auto"!==n.openlink&&"customize"!==n.openlink&&(popup.info.popup_listener.openlink="customize"):popup.info.popup_listener.openlink="customize"}else popup.info.popup_listener={onClick:function(){},onLoadSuccess:function(){},onLoadFailed:function(){},onClose:function(){},openlink:"customize"};return popup.info.supportCustom=!0,_.isObject(popup.info.popup_campaign_listener)?(_.isFunction(popup.info.popup_campaign_listener.shouldStart)||(popup.info.popup_campaign_listener.shouldStart=function(){return!0}),_.isFunction(popup.info.popup_campaign_listener.onStart)||(popup.info.supportCustom="withoutStart",popup.info.popup_campaign_listener.onStart=function(){}),_.isFunction(popup.info.popup_campaign_listener.onEnd)||(popup.info.popup_campaign_listener.onEnd=function(){}),_.isFunction(popup.info.popup_campaign_listener.onFailed)||(popup.info.popup_campaign_listener.onFailed=function(){})):(popup.info.supportCustom="withoutCampaignListener",popup.info.popup_campaign_listener={shouldStart:function(){return!0},onStart:function(){},onEnd:function(){},onFailed:function(){}}),!0},popup.getBridgeState=function(){return!_.isObject(popup.sa.para.app_js_bridge)||!popup.sa.para.app_js_bridge.is_mui&&(!popup.sa.bridge||!popup.sa.bridge.is_verify_success)},popup.init=function(){if(!popup.isSupportPopup())return!1;if(window.screen.width&&Number(window.screen.width)>1024)return"object"==typeof console&&console.log&&console.log("H5 \u5f39\u7a97\u4ec5\u652f\u6301\u79fb\u52a8\u7aef\u548c ipad\uff0c\u6216\u8005\u5c4f\u5e55\u5bbd\u5ea6\u5c0f\u4e8e\u7b49\u4e8e 1024\u3002"),!1;var e={};return arguments.length>0&&(1===arguments.length&&_.isObject(arguments[0])?e=arguments[0]:arguments.length>=2&&_.isObject(arguments[1])&&(e=arguments[1])),!!this.setPara(e)&&(popup.info.platform="H5",!!popup.setIsLoad()&&(!!this.getBridgeState()&&void(popup.testSend.hasParam()?popup.testSend.start():(popup.listenPageStateChange(),popup.updateDataAndSetListen.initial()))))},window.SensorsDataWebJSSDKPlugin&&"[object Object]"==Object.prototype.toString.call(window.SensorsDataWebJSSDKPlugin)?(window.SensorsDataWebJSSDKPlugin.popup=window.SensorsDataWebJSSDKPlugin.popup||popup,window.SensorsDataWebJSSDKPlugin.Popup=window.SensorsDataWebJSSDKPlugin.Popup||popup):window.SensorsDataWebJSSDKPlugin={popup:popup,Popup:popup};export default popup;
\ No newline at end of file
var popup={sa:{},info:{},lib_version:"0.4.2",defaultPara:{platform:"H5",preload_image:!0},serverData:{},localData:{global_popup_count:[],local_update_time:null,eventQueue:[],update_time:null},eventRule:{},convertPlans:[],isRun:!1,setArg:function(t){var e={};if(t&&"[object Object]"===Object.prototype.toString.call(t)){for(var n in t)n&&"popup_window_content"!==n&&(e[n]=t[n]);return JSON.stringify(e,null," ")}return t},log:function(){if(!0===popup.info.show_log&&"object"==typeof console&&"function"==typeof console.log)try{return arguments[0]=popup.setArg(arguments[0]),arguments[1]=popup.setArg(arguments[1]),console.log.apply(console,arguments)}catch(t){console.log(arguments[0])}},config:{storageName:"sensorsdata202002-webpopupdata",loadedSign:"SensorsData2015JSSDKWebPopupIsLoad"}},_={visibility:function(t){t=t||{};var e={hidden:undefined,visibilityChange:undefined,isSupported:function(){return"undefined"!=typeof this.hidden},_visible:t.onVisible,_hidden:t.onHidden,_nativeSwitch:function(){!0===document[this.hidden]?this._hidden():this._visible()},listen:function(){try{this.isSupported()?document.addEventListener(this.visibilityChange,function(){e._nativeSwitch.apply(e,arguments)},1):document.addEventListener?(window.addEventListener("focus",this._visible,1),window.addEventListener("blur",this._hidden,1)):(document.attachEvent("onfocusin",this._visible),document.attachEvent("onfocusout",this._hidden))}catch(t){}},init:function(){"undefined"!=typeof document.hidden?(this.hidden="hidden",this.visibilityChange="visibilitychange"):"undefined"!=typeof document.mozHidden?(this.hidden="mozHidden",this.visibilityChange="mozvisibilitychange"):"undefined"!=typeof document.msHidden?(this.hidden="msHidden",this.visibilityChange="msvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(this.hidden="webkitHidden",this.visibilityChange="webkitvisibilitychange"),this.listen()}};e.init()},getRgba:function(t){return"object"!=typeof t?t:"rgba("+t.r+","+t.g+","+t.b+","+t.a+")"},conversionNum:function(t){if(t){if(/^[0|1]?\.\d+$/.test(t))return 100*Number(t)+"%";var e=/^(-?\d+(\.\d+)?)px$/.exec(t);return e?(Number(e[1])/375*window.screen.width).toFixed(2)+"px":t}},boxModel:function(t){return function(e){if("object"!=typeof e)return t+":"+e+";";var n="";for(var p in e)n+=t+"-"+p+":"+_.conversionNum(e[p])+";";return n}},localStorage:{get:function(t){return window.localStorage.getItem(t)},parse:function(t){var e=null;try{e=JSON.parse(_.localStorage.get(t))||null}catch(n){}return e},set:function(t,e){window.localStorage.setItem(t,e)},remove:function(t){window.localStorage.removeItem(t)},isSupport:function(){var t=!0;try{var e="__sensorsdatasupport__",n="testIsSupportStorage";_.localStorage.set(e,n),_.localStorage.get(e)!==n&&(t=!1),_.localStorage.remove(e)}catch(p){t=!1}return t}},addEvent:function(){function t(e){return e&&(e.preventDefault=t.preventDefault,e.stopPropagation=t.stopPropagation,e._getPath=t._getPath),e}t._getPath=function(){var t=this;return this.path||this.composedPath&&this.composedPath()||function(){try{var e=t.target,n=[e];if(null===e||null===e.parentElement)return[];for(;null!==e.parentElement;)e=e.parentElement,n.unshift(e);return n}catch(p){return[]}}()},t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0};(function(e,n,p){if(e&&e.addEventListener)e.addEventListener(n,function(e){e._getPath=t._getPath,p.call(this,e)},!1);else{var o="on"+n,i=e[o];e[o]=function(e,n,p){return function(o){if(!(o=o||t(window.event)))return undefined;o.target=o.srcElement;var i,a,r=!0;return"function"==typeof p&&(i=p(o)),a=n.call(e,o),!1!==i&&!1!==a||(r=!1),r}}(e,p,i)}}).apply(null,arguments)},extend:function(t){var e=Array.prototype.slice;return _.each(e.call(arguments,1),function(e){for(var n in e)void 0!==e[n]&&(t[n]=e[n])}),t},extend2Lev:function(t){return _.each(Array.prototype.slice.call(arguments,1),function(e){for(var n in e)void 0!==e[n]&&(_.isObject(e[n])&&_.isObject(t[n])?_.extend(t[n],e[n]):t[n]=e[n])}),t},each:function(t,e,n){var p=Object.prototype.hasOwnProperty,o=Array.prototype.forEach,i={};if(null==t)return!1;if(o&&t.forEach===o)t.forEach(e,n);else if(t.length===+t.length){for(var a=0,r=t.length;a<r;a++)if(a in t&&e.call(n,t[a],a,t)===i)return!1}else for(var s in t)if(p.call(t,s)&&e.call(n,t[s],s,t)===i)return!1},xhr:function(t){if(t)return"undefined"!=typeof window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:"undefined"!=typeof XDomainRequest?new XDomainRequest:null;if("undefined"!=typeof window.XMLHttpRequest)return new XMLHttpRequest;if(window.ActiveXObject)try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}},ajax:function(t){function e(t){if(!t)return"";try{return JSON.parse(t)}catch(e){return{}}}t.timeout=t.timeout||2e4,t.credentials="undefined"==typeof t.credentials||t.credentials;var n=_.xhr(t.cors);if(!n)return!1;t.type||(t.type=t.data?"POST":"GET");var p,o=(t=_.extend({success:function(){},error:function(){}},t)).success,i=t.error;t.success=function(t){o(t),p&&(clearTimeout(p),p=null)},t.error=function(t){i(t),p&&(clearTimeout(p),p=null)},p=setTimeout(function(){!function(){try{_.isObject(n)&&n.abort&&n.abort()}catch(e){sd.log(e)}p&&(clearTimeout(p),p=null,t.error&&t.error(),n.onreadystatechange=null,n.onload=null,n.onerror=null)}()},t.timeout),"undefined"!=typeof XDomainRequest&&n instanceof XDomainRequest&&(n.onload=function(){t.success&&t.success(e(n.responseText)),n.onreadystatechange=null,n.onload=null,n.onerror=null},n.onerror=function(){t.error&&t.error(e(n.responseText),n.status),n.onreadystatechange=null,n.onerror=null,n.onload=null}),n.onreadystatechange=function(){try{4==n.readyState&&(n.status>=200&&n.status<300||304==n.status?t.success(e(n.responseText)):t.error(e(n.responseText),n.status),n.onreadystatechange=null,n.onload=null)}catch(p){n.onreadystatechange=null,n.onload=null}},n.open(t.type,t.url,!0);try{t.credentials&&(n.withCredentials=!0),_.isObject(t.header)&&_.each(t.header,function(t,e){n.setRequestHeader&&n.setRequestHeader(e,t)}),t.data&&(t.cors||n.setRequestHeader&&n.setRequestHeader("X-Requested-With","XMLHttpRequest"),"application/json"===t.contentType?n.setRequestHeader&&n.setRequestHeader("Content-type","application/json; charset=UTF-8"):n.setRequestHeader&&n.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(a){sd.log(a)}n.send(t.data||null)},getUuid:function(){var t=function(){return Math.random().toString(16).replace(".","")};return function(){var e=function(){for(var t=1*new Date,e=0;t==1*new Date;)e++;return t.toString(16)+e.toString(16)}()+"-"+t()+"-"+t();return e||(String(Math.random())+String(Math.random())+String(Math.random())).slice(2,15)}},trim:function(t){return t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},isEmptyObject:function(t){var e=Object.prototype.hasOwnProperty;if(_.isObject(t)){for(var n in t)if(e.call(t,n))return!1;return!0}return!1},filter:function(t,e,n){var p=Object.prototype.hasOwnProperty;if(t.filter)return t.filter(e);for(var o=[],i=0;i<t.length;i++)if(p.call(t,i)){var a=t[i];e.call(n,a,i,t)&&o.push(a)}return o},isObject:function(t){return null!=t&&"[object Object]"==Object.prototype.toString.call(t)},getConvertNumberValue:function(t){return _.isString(t)&&(t=Number(t)),Math.floor(1e3*t)/1e3},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},isString:function(t){return"[object String]"==Object.prototype.toString.call(t)},isDate:function(t){return"[object Date]"==Object.prototype.toString.call(t)},isBoolean:function(t){return"[object Boolean]"==Object.prototype.toString.call(t)},isNumber:function(t){return"[object Number]"==Object.prototype.toString.call(t)&&/[\d\.]+/.test(String(t))},isFunction:function(t){if(!t)return!1;var e=Object.prototype.toString.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e},getURLSearchParams:function(t){for(var e=function(t){return decodeURIComponent(t)},n={},p=(t=t||"").substring(1).split("&"),o=0;o<p.length;o++){var i=p[o].indexOf("=");if(-1!==i){var a=p[o].substring(0,i),r=p[o].substring(i+1);a=e(a),r=e(r),n[a]=r}}return n},URL:function(t){var e,n={},p=["hash","host","hostname","href","origin","password","pathname","port","protocol","search","username"];if("function"==typeof window.URL&&function(){try{return"http://modernizr.com/"===new URL("http://modernizr.com/").href}catch(t){return!1}}())(n=new URL(t)).searchParams||(n.searchParams=(e=_.getURLSearchParams(n.search),{get:function(t){return e[t]}}));else{if(!1===/^https?:\/\/.+/.test(t))throw"Invalid URL";var o=document.createElement("a");o.href=t;for(var i=p.length-1;i>=0;i--){var a=p[i];n[a]=o[a]}n.hostname&&"string"==typeof n.pathname&&0!==n.pathname.indexOf("/")&&(n.pathname="/"+n.pathname),n.searchParams=function(){var t=_.getURLSearchParams(n.search);return{get:function(e){return t[e]}}}()}return n},contentLoaded:function(t,e){var n=!1,p=!0,o=t.document,i=o.documentElement,a=o.addEventListener,r=a?"addEventListener":"attachEvent",s=a?"removeEventListener":"detachEvent",u=a?"":"on",l=function(p){"readystatechange"==p.type&&"complete"!=o.readyState||(("load"==p.type?t:o)[s](u+p.type,l,!1),!n&&(n=!0)&&e.call(t,p.type||p))},c=function(){try{i.doScroll("left")}catch(t){return void setTimeout(c,50)}l("poll")};if("complete"==o.readyState)e.call(t,"lazy");else{if(!a&&i.doScroll){try{p=!t.frameElement}catch(_){}p&&c()}o[r](u+"DOMContentLoaded",l,!1),o[r](u+"readystatechange",l,!1),t[r](u+"load",l,!1)}},indexOf:function(t,e){var n=t.indexOf;if(n)return n.call(t,e);for(var p=0;p<t.length;p++)if(e===t[p])return p;return-1}};popup._=_,popup.isSupportPopup=function(){return _.localStorage.isSupport()},popup.listenPageStateChange=function(){var t=!0;_.visibility({onVisible:function(){popup.log("\u9875\u9762\u89e6\u53d1visible-",(new Date).getMinutes(),"\u5206",(new Date).getSeconds()),!1===t&&(popup.updateDataAndSetListen.startState(),t=!0)},onHidden:function(){popup.log("\u9875\u9762\u89e6\u53d1hidden-",(new Date).getMinutes(),"\u5206",(new Date).getSeconds()),!0===t&&(popup.updateDataAndSetListen.stopAllState(),t=!1)}})},popup.getWebSDK=function(){return!!(_.isObject(window.sensorsDataAnalytic201505)&&_.isObject(window.sensorsDataAnalytic201505.readyState)&&window.sensorsDataAnalytic201505.readyState.state>=3)&&window.sensorsDataAnalytic201505},popup.getPopupInfo=function(t){if(!_.isObject(t)||!_.isObject(t.template))return{};var e={$sf_msg_title:"",$sf_msg_content:"",$sf_msg_image_url:""};return function n(t){_.each(t.subviews,function(t){var p=t.properties||{};"title"===p.msgType?e.$sf_msg_title=p.text:"content"===p.msgType?e.$sf_msg_content=p.text:"image"===t.type&&(e.$sf_msg_image_url=p.image),t.subviews&&n(t)})}(t.template),e},popup.getSFCampaign=function(t){t=_.isObject(t)?t:{};var e={planId:"",name:"",content:null,type:""};return e.planId=t.plan_id||"",e.name=t.cname||"",e.content=_.isObject(t.popup_window_content)?t.popup_window_content.content:"",e.type=_.isObject(t.popup_window_content)&&t.popup_window_content.popup_type?t.popup_window_content.popup_type:"PRESET",e},popup.getImageList=function(t){if(!_.isArray(t))return!1;for(var e,n,p=new RegExp('("(backgroundImage|image)":"(http(s)?://.[^"]*)")',"g"),o=new RegExp('http(s)?://.[^S^"]*'),i={},a=t.length,r=[],s=0;s<a;s++)if(_.isObject(t[s])&&"ACTIVE"===t[s].status.toLocaleUpperCase()&&!0===t[s].is_audience&&(t[s].strategy_id?!1!==t[s].is_trigger:!0!==t[s].is_control_group)&&t[s].popup_window_content&&t[s].popup_window_content.content&&(e=t[s].popup_window_content.content.match(p)))for(var u=0,l=e.length;u<l;u++)(n=e[u].match(o))&&n.length>0&&(i[n[0]]||(i[n[0]]=1));return _.each(i,function(t,e){r.push(e)}),r},popup.setIsLoad=function(){if(window.self===window.top){if(window[popup.config.loadedSign])return!1;if("undefined"==typeof window[popup.config.loadedSign])return window[popup.config.loadedSign]=!0,!0}else try{return!window.top[popup.config.loadedSign]&&(window.top[popup.config.loadedSign]=!0,!0)}catch(t){return popup.log("\u975e\u540c\u57df\u540diframe\u5185\u5d4c\u4e0d\u80fd\u83b7\u53d6\u7236\u7ea7\u7a97\u4f53\u5185\u5bb9",t),!0}},popup.handlerCampaign=function(t){var e,n=t,p=_.getUuid()(),o=n.plan.popup_window_content;if(!_.isObject(o))return n.popupFailed(1001,!1,{uuid:p,content:"",plan:n.plan}),!1;if(o.content)try{e=JSON.parse(o.content)}catch(u){popup.log(u)}var i=popup.getSFCampaign(n.plan),a={state:"",isCustom:!1},r=!0;try{r=popup.info.popup_campaign_listener.shouldStart(i)}catch(u){r=!1,popup.log(u)}var s={uuid:p,content:e,plan:n.plan};switch(n.plan.is_trigger?r?"CUSTOMIZED"===o.popup_type?"withoutCampaignListener"===popup.info.supportCustom?a.state="CAMPAIGN_CUSTOMIZED_NULL_LISTENER":"withoutStart"===popup.info.supportCustom?a.state="CAMPAIGN_CUSTOMIZED_LISTENER_NULL_START":_.isString(o.content)?a.state="CAMPAIGN_TRIGGER_CUSTOMIZED_START":a.state="DIALOG_NOT_SHOW_JSON_FAILED":("PRESET"===o.popup_type&&popup.log("\u6b64\u7248\u672csdk\u4e0d\u652f\u6301\u9884\u7f6e\u5f39\u7a97"),a.state="DIALOG_NOT_SHOW_JSON_FAILED"):a.state="CAMPAIGN_NOT_START_LISTENER_START":a.state="CAMPAIGN_NOT_START_TRIGGER",a.isCustom=!(!o.popup_type||"CUSTOMIZED"!==o.popup_type),popup.log("campaign:",a,"plan:",n.plan.cname),a.state){case"CAMPAIGN_TRIGGER_CUSTOMIZED_START":n.customCampaign(s);break;case"CAMPAIGN_NOT_START_LISTENER_START":n.popupFailed(1004,a.isCustom,s);break;case"CAMPAIGN_CUSTOMIZED_NULL_LISTENER":case"CAMPAIGN_CUSTOMIZED_LISTENER_NULL_START":n.popupFailed(1006,a.isCustom,s);break;case"DIALOG_NOT_SHOW_JSON_FAILED":n.popupFailed(1001,a.isCustom,s);break;case"CAMPAIGN_NOT_START_TRIGGER":n.popupFailed(1005,a.isCustom,s);break;default:popup.log("CampaignState\u5f02\u5e38")}},popup.track={getPublicProps:function(t){var e=t.plan,n={$sf_lib_version:popup.lib_version,$sf_plan_type:"\u8fd0\u8425\u8ba1\u5212",$sf_channel_service_name:"SENSORS_FOCUS",$sf_channel_category:"POPUP",$sf_platform_tag:popup.info.platform,$sf_msg_id:t.$sf_msg_id};return _.isEmptyObject(e)||!_.isObject(e)?n:(n.$sf_plan_id=e.plan_id+"",n.$sf_plan_strategy_id=e.strategy_id?e.strategy_id:e.is_control_group?"-1":"0",e.audience_id&&(n.$sf_audience_id=e.audience_id+""),n)},popupDisplay:function(t){var e={$sf_msg_title:t.$sf_msg_title,$sf_msg_content:t.$sf_msg_content,$sf_msg_image_url:t.$sf_msg_image_url,$sf_succeed:t.$sf_succeed,$sf_fail_reason:t.$sf_fail_reason};this.trackEvent("$PlanPopupDisplay",e,t)},trackEvent:function(t,e,n){var p=popup.track.getPublicProps(n);_.extend(e,p),_.each(e,function(t,n){""!==t&&t!==undefined||delete e[n]}),popup.sa.track(t,e)},maskClick:function(t){if(!t.msg)return!1;var e={$sf_close_type:"POPUP_CLOSE_MASK",$sf_msg_title:t.msg.$sf_msg_title,$sf_msg_content:t.msg.$sf_msg_content,$sf_msg_image_url:t.msg.$sf_msg_image_url,$sf_msg_element_type:"mask",$sf_msg_action_id:t.properties.maskActionId};this.trackEvent("$PlanPopupClick",e,t.msg),t.destory()},elementClickCallback:function(t,e){var n=t.target,p=n.getAttribute("data-action"),o=n.getAttribute("data-info"),i=e.msg||{};if(!p)return!1;try{var a=(JSON.parse(p)||{})[0],r=JSON.parse(o)||{}}catch(t){popup.log("elementClickCallback error",t)}var s={type:a.type,value:_.isString(a.value)?a.value:"",extra:_.isObject(a.value)?a.value:""},u=e.msg.plan?e.msg.plan.plan_id:"",l={$sf_msg_title:i.$sf_msg_title,$sf_msg_content:i.$sf_msg_content,$sf_msg_image_url:i.$sf_msg_image_url,$sf_msg_element_type:r.$sf_msg_element_type,$sf_msg_element_content:r.$sf_msg_element_content,$sf_msg_element_action:a.type,$sf_msg_action_id:a.id,$sf_close_type:"close"===a.type?a.$sf_close_type:""};this.trackEvent("$PlanPopupClick",l,i);try{popup.info.popup_listener.onClick(u,s)}catch(t){popup.log("popup_listener.onClick error",t)}if("close"===a.type)e.destory();else if(a.closeable&&e.destory(),"auto"===popup.info.popup_listener.openlink&&"openlink"===a.type){if("http"!==a.value.slice(0,4))return!1;window.location.href=a.value}}};var salog=popup.log;popup.changeCovertStatus=function(t){var e=JSON.parse(JSON.stringify(popup.convertPlans));_.each(e,function(e,n){if(!e.is_in_convert_window)return!1;var p=e.is_in_convert_window.step,o=e.is_in_convert_window.uuid;if(popup.convertPlans[n].is_in_convert_window.step=Math.min(2*p,6e5),!t)return!1;_.each(t,function(t){t.popup_display_uuid===o&&t.convert_time&&(salog("--\u8f6c\u5316\u7a97\u53e3- \u76ee\u6807\u4e8b\u4ef6\u5df2\u7ecf\u5b8c\u6210 - \u6ee1\u8db3",popup.convertPlans[n].plan_id),delete popup.convertPlans[n].is_in_convert_window,popup.convertPlans.splice(n,1))})}),popup.updateDataAndSetListen.updateLocalData()},popup.asyncConvert=function(t){var e=popup.info.project,n=!1;if(!t&&0===popup.convertPlans.length)return!1;t&&(_.each(popup.convertPlans,function(e){e.plan_id===t.plan_id&&(n=!0)}),n||popup.convertPlans.push(t)),function p(){if(_.isEmptyObject(popup.localData)||!_.isArray(popup.convertPlans)||0===popup.convertPlans.length)return!1;var t=JSON.parse(JSON.stringify(popup.convertPlans)),n=t[0].is_in_convert_window&&t[0].is_in_convert_window.step||5e3,o=[];if(_.each(t,function(t,e){return!!t.is_in_convert_window&&((new Date).getTime()>t.is_in_convert_window.expire_time?(salog("--\u8f6c\u5316\u7a97\u53e3\u8d85\u65f6\u5df2\u7ecf\u8fc7\u671f - \u6ee1\u8db3",popup.convertPlans[e].plan_id),delete popup.convertPlans[e].is_in_convert_window,popup.convertPlans.splice(e,1),popup.updateDataAndSetListen.updateLocalData(),!1):(o.push(t.is_in_convert_window.uuid),t.is_in_convert_window.step||(t.is_in_convert_window.step=5e3,popup.convertPlans[e].is_in_convert_window.step=5e3),void(n>t.is_in_convert_window.step&&(n=t.is_in_convert_window.step))))}),!o.length)return!1;popup.asyncConvert.timer&&clearTimeout(popup.asyncConvert.timer),popup.asyncConvert.timer=setTimeout(function(){_.ajax({url:popup.info.api_base_url+"/sfo/popup_displays?project="+encodeURIComponent(e)+"&popup_display_uuids="+encodeURIComponent(o)+"&time="+(new Date).getTime(),type:"GET",cors:!0,credentials:!1,contentType:"application/json",success:function(t){popup.changeCovertStatus(t),p()},error:function(){popup.changeCovertStatus(),p()}})},n)}()},popup.ruleTime={getExpire:function(t,e){var n=e,p=Number(t.value)||0,o=Number(t.value)||0,i=String(t.unit).toLowerCase(),a=null,r={day:function(){return(a=new Date(n)).setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+864e5*(o-1)},week:function(){var t=(a=new Date(n)).getDay();0===t&&(t=7);var e=7-t;return a.setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+24*e*60*60*1e3+7*(o-1)*24*60*60*1e3},month:function(){var t=(a=new Date(n)).getMonth()+o;return t>=11?(a.setFullYear(a.getFullYear()+parseInt(t/12)),a.setMonth(t%12)):a.setMonth(t),a.setDate(1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0),a.getTime()},second:function(t){var e={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return a=new Date(n),t in e&&(o=e[t]*p),a.getTime()+o}};return!0!==t.natural?r.second(i):i in r?r[i]():void 0},getLast:function(t,e){var n=Number(t.value)||0,p=Number(t.value)-1||0,o=String(t.unit).toLowerCase(),i=null,a={day:function(){return(i=new Date(e)).setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-864e5*p},week:function(){var t=(i=new Date(e)).getDay();return 0===t&&(t=7),--t,i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-(24*t*60*60*1e3+7*p*24*60*60*1e3)},month:function(){var t=(i=new Date(e)).getMonth()+1-p;return t<=0?(i.setFullYear(i.getFullYear()+(parseInt(t/12)-1)),i.setMonth(12+t%12-1)):i.setMonth(t-1),i.setDate(1),i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.getTime()},second:function(t){var p={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return i=new Date(e),t in p&&(o=p[t]*n),i.getTime()-o}};return!0!==t.natural?a.second(o):o in a?a[o]():void 0},getArrMatchCount:function(t,e){var n=0;for(n=0;n<t.length;n++)if(e>=t[n])return n;return t.length}},popup.eventTriggerProcess=function(){if(!popup.updateDataAndSetListen.active_state)return!1;if(!_.isArray(popup.localData.eventQueue))return!1;if(0===popup.localData.eventQueue.length)return!1;if(popup.isRun)return!1;salog("\u4e8b\u4ef6\u961f\u5217---eventQueue",popup.localData.eventQueue);var t=!1,e=popup.localData.eventQueue[0],n=popup.eventRule[e.event];popup.isRun=!0,popup.localData.eventQueue.shift(),popup.updateDataAndSetListen.updateLocalData(),_.isArray(n)&&_.isObject(n[0])&&n.length>0&&(salog("--------------------\u89e6\u53d1\u4e8b\u4ef6\u5f00\u59cb--------------------"),_.each(n,function(t){_.isObject(t)&&"undefined"!=typeof t.match_state&&delete t.match_state,new popup.RuleCheck(t,e)}),_.each(n,function(e){!0===e.match_state?!1===t?(t=!0,salog("\u68c0\u67e5\u5b8c\u6bd5-\u4f18\u5148\u5f39\u7a97-\u5f00\u59cb",e.plan.cname),new popup.PopupCheck(e,!0)):!0===t&&(salog("\u68c0\u67e5\u5b8c\u6bd5-\u975e\u4f18\u5148\u5f39\u7a97-\u4e0d\u6e32\u67d3",e.plan.cname),new popup.PopupCheck(e,!1)):salog("\u68c0\u67e5\u5b8c\u6bd5-\u8ba1\u5212-\u4e0d\u6ee1\u8db3",e.plan.cname)}),t||popup.completeWindowLifecycle(),salog("--------------------\u89e6\u53d1\u4e8b\u4ef6\u7ed3\u675f--------------------"))},popup.completeWindowLifecycle=function(){popup.isRun=!1,popup.eventTriggerProcess()},popup.PopupCheck=function(t,e){this.plan=t.plan,this.current_time=(new Date).getTime(),e?this.renderPopup():this.hidePopup(),popup.updateDataAndSetListen.updateLocalData()},popup.PopupCheck.prototype.createPopupWindow=function(t,e){this.startConvertWindow(t),this.startPopupIntervalWindow(this.current_time),this.startPopupLimitWindow(),this.setGlobalLimit(),this.deletePlanAllWindow(),e&&popup.completeWindowLifecycle()},popup.PopupCheck.prototype.hidePopup=function(){this.deletePlanAllWindow()},popup.PopupCheck.prototype.renderPopup=function(){popup.handlerCampaign(this)},popup.PopupCheck.prototype.popupFailed=function(t,e,n){var p={1001:"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",1003:"\u5bf9\u7167\u7ec4",1004:"campaignShouldStart \u63a5\u53e3\u8fd4\u56de false",1005:"\u8ba1\u5212\u4e0b\u53d1 is_trigger \u4e3a false",1006:"\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03"}[t],o=popup.getPopupInfo(n.content);o.$sf_msg_id=n.uuid,o.plan=n.plan,o.$sf_succeed=!1,o.$sf_fail_reason=p,popup.track.popupDisplay(o),!e&&popup.info.popup_listener&&_.isFunction(popup.info.popup_listener.onLoadFailed)&&popup.info.popup_listener.onLoadFailed(n.plan.plan_id,t,p),popup.info.popup_campaign_listener.onFailed(popup.getSFCampaign(n.plan),t,p),this.createPopupWindow(n.uuid,!0)},popup.PopupCheck.prototype.customCampaign=function(t){var e=popup.getSFCampaign(t.plan),n=popup.getPopupInfo(t.content);n.$sf_msg_id=t.uuid,n.plan=t.plan,n.$sf_succeed=!0,popup.track.popupDisplay(n),popup.info.popup_campaign_listener.onStart(e),this.createPopupWindow(t.uuid,!0)},popup.PopupCheck.prototype.showPopup=function(t){if(!popup.ElementRender)return popup.log("\u6682\u4e0d\u652f\u6301\u9884\u7f6e\u5f39\u7a97UI"),!1;var e=new popup.ElementRender(t.content),n=popup.getPopupInfo(t.content);if(n.$sf_msg_id=t.uuid,n.plan=t.plan,n.$sf_succeed=!0,_.extend(e.msg,n),e.popupCheckInstance=this,popup.track.popupDisplay(n),!e.render())return salog("\u5f53\u524d\u9875\u9762\u5df2\u6709\u4e00\u4e2a\u5f39\u6846\u6b63\u5728\u6e32\u67d3\uff0c\u672c\u6b21\u5f39\u6846\u4e0d\u6e32\u67d3\uff01"),!1;popup.info.popup_campaign_listener.onStart(popup.getSFCampaign(t.plan)),this.createPopupWindow(t.uuid),popup.info.popup_listener.onLoadSuccess(t.plan.plan_id)},popup.PopupCheck.prototype.startConvertWindow=function(t){salog("--\u5f39\u7a97\u5c55\u793a-\u8f6c\u5316\u7a97\u53e3\u8bbe\u7f6e",this.plan.cname),_.isObject(this.plan.convert_window)&&this.plan.convert_window.value&&(this.plan.is_in_convert_window={expire_time:popup.ruleTime.getExpire(this.plan.convert_window,this.current_time),start_time:this.current_time,uuid:t},popup.asyncConvert(this.plan))},popup.PopupCheck.prototype.startPopupIntervalWindow=function(t){_.isObject(this.plan.popup_interval)&&this.plan.popup_interval.value&&(this.plan.is_in_popup_interval_window=popup.ruleTime.getExpire(this.plan.popup_interval,t))},popup.PopupCheck.prototype.resetPopupIntervalWindow=function(){var t=(new Date).getTime();this.startPopupIntervalWindow(t),this.resetGlobalLimit(t),popup.completeWindowLifecycle()},popup.PopupCheck.prototype.startPopupLimitWindow=function(){salog("--\u5f39\u7a97\u5c55\u793a-\u53c2\u4e0e\u9650\u5236\u7a97\u53e3\u8bbe\u7f6e\u91cd\u7f6e"),_.isObject(this.plan.re_enter)&&this.plan.re_enter.value&&(_.isObject(this.plan.is_in_popup_limit_window)?this.plan.is_in_popup_limit_window.count++:this.plan.is_in_popup_limit_window={expire_time:popup.ruleTime.getExpire(this.plan.re_enter,this.current_time),count:1})},popup.PopupCheck.prototype.setGlobalLimit=function(){salog("--\u5f39\u7a97\u5c55\u793a-\u5168\u5c40\u5f39\u7a97\u6b21\u6570\u8bbe\u7f6e"),_.isArray(popup.localData.global_popup_count)||(popup.localData.global_popup_count=[]),popup.localData.global_popup_count.unshift(this.current_time);for(var t=popup.localData.global_popup_count,e=t[t.length-1];e+7776e6<this.current_time||t.length>3e3;)t.pop(),e=t[t.length-1]},popup.PopupCheck.prototype.resetGlobalLimit=function(t){_.isArray(popup.localData.global_popup_count)&&popup.localData.global_popup_count.length>0&&(popup.localData.global_popup_count.shift(),popup.localData.global_popup_count.unshift(t))},popup.PopupCheck.prototype.deletePlanAllWindow=function(){var t=this.plan.pattern_popup.matcher_list;_.isArray(t)&&_.each(t,function(t){t.is_in_window&&(salog("--\u5f39\u7a97\u5c55\u793a-\u91cd\u7f6e\u5404\u4e2a\u89c4\u5219\u7684\u7a97\u53e3\u8ba1\u7b97-\u6210\u529f"),delete t.is_in_window)})},popup.RuleCheck=function(t,e){this.plan_match=t,this.plan=t.plan,this.rule_arr=t.rule,this.event_data=e,this.current_time=(new Date).getTime();var n="-------------\u68c0\u67e5-\u8ba1\u5212-("+this.plan.cname+")";_.each(this.rule_arr,function(t){n+="--\u5305\u542b\u89c4\u5219-("+t.event_name+"\uff09-\u89e6\u53d1"+t.params[0]+"\u6b21"}),salog(n),salog(this.plan),this.checkPlanIsExpire(),popup.updateDataAndSetListen.updateLocalData()},popup.RuleCheck.prototype.checkPlanIsExpire=function(){!this.plan.expire_at||_.isNumber(this.plan.expire_at)&&this.current_time<this.plan.expire_at?(salog("--\u8fc7\u671f-\u6ee1\u8db3",this.plan.cname),this.checkPlanIsAudience()):salog("--\u8fc7\u671f-\u4e0d\u6ee1\u8db3",this.plan.cname)},popup.RuleCheck.prototype.checkPlanIsAudience=function(){!0===this.plan.is_audience?(salog("--\u662f\u5426\u53d7\u4f17-\u6ee1\u8db3",this.plan.cname),this.checkPlanSuspend()):salog("--\u662f\u5426\u53d7\u4f17-\u4e0d\u6ee1\u8db3",this.plan.cname)},popup.RuleCheck.prototype.checkPlanSuspend=function(){this.plan.status&&"SUSPEND"===this.plan.status?salog("--\u6682\u505c-\u4e0d\u6ee1\u8db3",this.plan.cname):(salog("--\u6682\u505c-\u6ee1\u8db3",this.plan.cname),this.checkConvert())},popup.RuleCheck.prototype.checkConvert=function(){if(_.isObject(this.plan.is_in_convert_window)&&this.plan.is_in_convert_window.expire_time>this.current_time)salog("--\u5b58\u5728\u8f6c\u5316\u7a97\u53e3 - \u4e0d\u6ee1\u8db3",this.plan.is_in_convert_window);else if(_.isObject(this.plan.is_in_convert_window)&&this.current_time>this.plan.is_in_convert_window.expire_time){salog("--\u8f6c\u5316\u7a97\u53e3\u8d85\u65f6\u5df2\u7ecf\u8fc7\u671f - \u6ee1\u8db3",this.plan.plan_id),delete this.plan.is_in_convert_window;for(var t=0;t<popup.convertPlans.length;t++)this.plan.plan_id===popup.convertPlans[t].plan_id&&(popup.convertPlans.splice(t,1),t--);this.checkGlobalPopupInterval()}else salog("--\u4e0d\u5b58\u5728\u8f6c\u5316\u7a97\u53e3 - \u6ee1\u8db3",this.plan.is_in_convert_window),this.checkGlobalPopupInterval()},popup.RuleCheck.prototype.checkGlobalPopupInterval=function(){var t=popup.localData.global_popup_count;if(_.isArray(t)&&t.length>=1){var e=popup.ruleTime.getLast(popup.localData.popup_interval_global,this.current_time);e>t[0]?(salog("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3-"+e+">\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+t[0]),this.checkPopupInterval()):salog("\u68c0\u67e5-\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3-"+e+"<\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+t[0])}else salog("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ca1\u6709\u5f39\u8fc7\u7a97-\u6ee1\u8db3"),this.checkPopupInterval()},popup.RuleCheck.prototype.checkPopupInterval=function(){_.isNumber(this.plan.is_in_popup_interval_window)?this.current_time>this.plan.is_in_popup_interval_window?(salog("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5927\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3"),this.plan.is_in_popup_interval_window=null,this.checkProperties()):salog("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5c0f\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3"):(salog("--\u5f39\u7a97\u95f4\u9694-\u7a97\u53e3\u4e0d\u5b58\u5728-\u65b0\u5f00"),this.plan.is_in_popup_interval_window=null,this.checkProperties())},popup.RuleCheck.prototype.checkProperties=function(){var t={equal:function(t,e){if(!_.isNumber(t)&&!_.isString(t))return!1;for(var n=0,p=e.length;n<p;n++){if(!_.isNumber(e[n])&&!_.isString(e[n]))return!1;if(_.isString(t)){if(t===(_.isString(e[n])?e[n]:String(e[n])))return!0}else if(_.getConvertNumberValue(t)===_.getConvertNumberValue(e[n]))return!0}return!1},notEqual:function(t,e){if(!_.isNumber(t)&&!_.isString(t))return!1;for(var n=0,p=e.length;n<p;n++){if(!_.isNumber(e[n])&&!_.isString(e[n]))return!1;if(_.isString(t)){if(t===(_.isString(e[n])?e[n]:String(e[n])))return!1}else if(_.getConvertNumberValue(t)===_.getConvertNumberValue(e[n]))return!1}return!0},contain:function(t,e){return!!_.isString(t)&&t.indexOf(e[0])>=0},notContain:function(t,e){return!!_.isString(t)&&-1===t.indexOf(e[0])},isTrue:function(t){return!0===t},isFalse:function(t){return!1===t},isSet:function(t){return void 0!==t},notSet:function(t){return void 0===t},isEmpty:function(t){if(!_.isString(t)&&!_.isArray(t))return!1;if(_.isString(t))return""===t;for(var e=0;e<t.length;e++){if(""!==t[e].replace(/^\s+|\s+$/g,""))return!1}return!0},isNotEmpty:function(t){if(!_.isString(t)&&!_.isArray(t))return!1;if(_.isString(t))return""!==t;for(var e=0;e<t.length;e++){if(""===t[e].replace(/^\s+|\s+$/g,""))return!1}return!0},less:function(t,e){return!!_.isNumber(t)&&("undefined"!=typeof e[0]&&_.getConvertNumberValue(t)<_.getConvertNumberValue(e[0]))},greater:function(t,e){return!!_.isNumber(t)&&("undefined"!=typeof e[0]&&_.getConvertNumberValue(t)>_.getConvertNumberValue(e[0]))},between:function(t,e){if(!_.isNumber(t))return!1;if("undefined"==typeof e[0]&&"undefined"==typeof e[1])return!1;var n=_.getConvertNumberValue(t),p=_.getConvertNumberValue(e[0]),o=_.getConvertNumberValue(e[1]);return n>=p&&n<=o},isIn:function(t,e){if(!_.isArray(t))return!1;for(var n=0;n<t.length;n++)if(_.indexOf(e,t[n])>=0)return!0;return!1},notInclude:function(t,e){if(!_.isArray(t))return!1;for(var n=0;n<t.length;n++)if(-1===_.indexOf(e,t[n]))return!0;return!1},absolute_between:function(t,e){try{var n=new Date(e[0]),p=new Date(e[1]),o=new Date(t);return o>=n&&o<=p}catch(i){salog("absolute_between Error",i)}},absoluteBetween:function(t,e){try{var n=new Date(e[0]),p=new Date(e[1]),o=new Date(t);return o>=n&&o<=p}catch(i){salog("absolute_between Error",i)}}},e=this,n=_.filter(this.rule_arr,function(n){if(!n.filter||n.filter.conditions&&0===n.filter.conditions.length)return!0;var p=n.filter,o=p.relation,i="or"===String(o).toLowerCase(),a="and"===String(o).toLowerCase(),r=!!a,s=!0;return _.each(p.conditions,function(n){if(!s)return!1;if(!n.field)return!1;var p=n.field.lastIndexOf("."),o=n.params,u="in"===n["function"]?"isIn":n["function"];if(!t[u])return r=!1,s=!1,!1;if(p<0)return!1;var l=n.field.slice(p+1),c=e.event_data.properties[l],_=t[u](c,o);i&&_&&(r=!0,s=!1),a&&!_&&(r=!1,s=!1)}),r});_.isArray(n)&&n.length>0?(this.checkWindowAndMatch(n),salog("--\u5c5e\u6027\u5339\u914d-\u6ee1\u8db3",n)):salog("--\u5c5e\u6027\u5339\u914d-\u4e0d\u6ee1\u8db3")},popup.RuleCheck.prototype.checkWindowAndMatch=function(t){var e=this,n=[];_.each(t,function(t){if(!t.params||!t.params[0])return salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570\u636e\u5f02\u5e38"),!1;var p=Number(t.params[0]);1===p?n.push(t):p>1&&_.isObject(t.window)&&t.window.value>0&&(!_.isObject(t.is_in_window)||!_.isNumber(t.is_in_window.expire_time)||t.is_in_window.expire_time<e.current_time?t.is_in_window={expire_time:popup.ruleTime.getExpire(t.window,e.current_time),count:1}:t.is_in_window.count=t.is_in_window.count+1,t.is_in_window.count>=p?n.push(t):salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570",t.is_in_window.count,"\u4e0d\u5339\u914d\u5f53\u524d\u6b21\u6570",p))}),n.length>0?(salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",n),this.checkGlobalPopupLimit()):salog("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6ca1\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",n)},popup.RuleCheck.prototype.checkGlobalPopupLimit=function(){var t=popup.localData.msg_limit_global,e=!0,n=this;_.isObject(t)&&!0===t.is_in_use&&_.isArray(t.limits)&&_.isArray(popup.localData.global_popup_count)&&!0===this.plan.global_msg_limit_enabled?(_.each(t.limits,function(t){if(_.isObject(t)&&_.isNumber(t.limit)){var p=popup.ruleTime.getLast(t,n.current_time),o=popup.ruleTime.getArrMatchCount(popup.localData.global_popup_count,p);salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u5df2\u7ecf\u5f39\u7a97\u6b21\u6570-"+o+"-\u9650\u5236\u7684\u6b21\u6570"+t.limit+"-\u9650\u5236\u65f6\u95f4-"+p),e=o<t.limit?e&&!0:e&&!1}}),e?(salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236- \u6ee1\u8db3"),this.checkPopupLimit()):salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u4e0d\u6ee1\u8db3")):(salog("--\u5168\u5c40\u5f39\u7a97\u9650\u5236- \u6ee1\u8db3"),this.checkPopupLimit())},popup.RuleCheck.prototype.checkPopupLimit=function(){if(!_.isObject(this.plan.re_enter)||!_.isNumber(this.plan.re_enter.value)||!_.isNumber(this.plan.re_enter.limit))return this.plan_match.match_state=!0,!1;_.isObject(this.plan.is_in_popup_limit_window)&&_.isNumber(this.plan.is_in_popup_limit_window.expire_time)&&_.isNumber(this.plan.is_in_popup_limit_window.count)?this.plan.is_in_popup_limit_window.expire_time<this.current_time?(salog("--\u53c2\u4e0e\u9650\u5236-\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236\u7a97\u53e3-\u5f00\u542f\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window,this.plan_match.match_state=!0):this.plan.is_in_popup_limit_window.count<this.plan.re_enter.limit?(salog("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4e14\u5728\u53c2\u4e0e\u9650\u5236\u6b21\u6570\u5185-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0):salog("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4f46\u662f\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236-\u4e0d\u6ee1\u8db3",this.plan.is_in_popup_limit_window):(this.plan.is_in_popup_limit_window?(salog("--\u53c2\u4e0e\u9650\u5236-\u6709\u7a97\u53e3\u4f46\u662f\u7a97\u53e3\u6570\u636e\u5f02\u5e38-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window):salog("--\u53c2\u4e0e\u9650\u5236-\u4e0d\u5b58\u5728\u7a97\u53e3-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0)},popup.store={delete_time:2592e6,init:function(){this.migrateLocalData(),popup.localData=this.getLocalData(),_.isNumber(popup.localData.config_pull_interval_ms)&&popup.localData.config_pull_interval_ms>0&&(popup.updateDataAndSetListen.interval_time=popup.localData.config_pull_interval_ms),this.removeLocalData(),popup.log("\u521d\u59cb\u5316-\u83b7\u53d6-\u5185\u5b58-localData")},getJSONData:function(){return _.localStorage.parse(popup.config.storageName)},saveJSONData:function(t){_.localStorage.set(popup.config.storageName,JSON.stringify(t))},migrateLocalData:function(){var t=this.getJSONData()||{},e=popup.sa.store.getDistinctId();if(t.popup_sdk_users&&t.popup_sdk_plans)return!1;var n={popup_sdk_plans:{},popup_sdk_users:{}};n.popup_sdk_plans[e]=t,n.popup_sdk_users[e]={user_id:e},this.saveJSONData(n)},getLocalData:function(){var t=this.getJSONData(),e=popup.sa.store.getDistinctId(),n=null;return t?(_.isObject(t.popup_sdk_users[e])&&t.popup_sdk_users[e].user_id&&(n=t.popup_sdk_users[e].user_id),n&&_.isObject(t.popup_sdk_plans[n])?(t.popup_sdk_plans[n].update_time=(new Date).getTime(),this.saveJSONData(t),t.popup_sdk_plans[n]):{}):{}},saveLocalData:function(){var t=this.getJSONData(),e=popup.sa.store.getDistinctId(),n=null;if(!t)return!1;t.popup_sdk_users&&_.isObject(t.popup_sdk_users[e])&&t.popup_sdk_users[e].user_id&&(n=t.popup_sdk_users[e].user_id,t.popup_sdk_plans[n]=popup.localData,this.saveJSONData(t))},removeLocalData:function(){var t=this.getJSONData(),e=this.delete_time;if(!t||!t.popup_sdk_plans||!t.popup_sdk_users)return!1;var n=JSON.parse(JSON.stringify(t.popup_sdk_plans)),p=JSON.parse(JSON.stringify(t.popup_sdk_users)),o=(new Date).getTime(),i=[];_.each(n,function(n,p){o-n.update_time>e&&(delete t.popup_sdk_plans[p],i.push(p))}),_.each(p,function(e,n){i.length>0&&_.each(i,function(p){e.user_id&&p===e.user_id&&delete t.popup_sdk_users[n]})}),this.saveJSONData(t)}},popup.updateDataAndSetListen={active_state:!0,interval_time:6e5,save_interval:null,data_interval:null,image_list:null,local_data:null,filterConvertPlans:function(){var t=popup.localData.popup_plans;if(!t||!_.isArray(t))return!1;var e=_.filter(t,function(t){return!!t.convert_window&&!!t.is_in_convert_window});popup.convertPlans=e,popup.log("\u521d\u59cb\u5316-\u5f02\u6b65\u7684convertWindow",popup.convertPlans),popup.asyncConvert()},diffData:function(){var t=popup.localData,e=JSON.parse(JSON.stringify(popup.serverData)),n=(new Date).getTime();if(!e||_.isEmptyObject(e))return!1;var p=n-e.server_current_time;if(Math.abs(p)>=6e5)return!1;if(!t||_.isEmptyObject(t)||!t.popup_plans||0===t.popup_plans.length)return _.extend(popup.localData,e),!1;var o=e.popup_plans;_.each(o,function(e,n){var p=null;if(_.each(t.popup_plans,function(t){t.plan_id===e.plan_id&&(p=t,e.audience_id||delete p.audience_id,_.isObject(e.window_update)&&_.each(e.window_update,function(t,n){p.window_update&&p.window_update[n]===t||("trigger_window"===n?p.pattern_popup.matcher_list=e.pattern_popup.matcher_list:"convert_window"===n&&p.is_in_convert_window&&e.convert_window&&p.is_in_convert_window.start_time&&(p.is_in_convert_window.expire_time=popup.ruleTime.getExpire(e.convert_window,p.is_in_convert_window.start_time)))}))}),!p)return!1;if(!e.window_update&&p.last_update_config_time!==e.last_update_config_time)return!1;var i=p.pattern_popup.matcher_list;_.extend2Lev(p,e),p.pattern_popup.matcher_list=i,o[n]=p}),_.extend(popup.localData,e)},getEventRule:function(){var t=popup.localData.popup_plans,e={};if(!t||!_.isArray(t))return!1;_.each(t,function(t){var n=t.pattern_popup.matcher_list;_.each(n,function(n){var p={plan:t,rule:[n]},o=n.event_name,i=!1;if(e[o]){if(_.each(e[o],function(e){e.plan.plan_id===t.plan_id&&(e.rule.push(n),i=!0)}),i)return!1;e[o].push(p)}else e[o]=[p]})}),_.each(e,function(t){t.sort(function(t,e){var n=e.plan.absolute_priority-t.plan.absolute_priority;return 0===n?e.plan.plan_id-t.plan.plan_id:n})}),popup.eventRule=e,popup.log("\u521d\u59cb\u5316-\u5f97\u5230\u4e8b\u4ef6\u548c\u8ba1\u5212\u7684\u5173\u7cfb"),popup.log("--------------------\u521d\u59cb\u5316\u5b8c\u6210--------------------\u7b49\u5f85\u4e8b\u4ef6\u89e6\u53d1\u8ba1\u5212--------------------")},registerListen:function(){var t=this;popup.sa.events.on("send",function(e){e.event&&popup.eventRule[e.event]&&(_.isArray(popup.localData.eventQueue)||(popup.localData.eventQueue=[]),popup.localData.eventQueue.push(e),t.updateLocalData(),popup.eventTriggerProcess())}),popup.sa.events.on("changeDistinctId",function(e){t.changeId()}),popup.sa.events.isReady()},setListenEvent:function(){this.diffData(),this.filterConvertPlans(),this.getEventRule(),this.updateLocalData()},loadImage:function(t){if(t.length<1)return!1;if(JSON.stringify(t)===JSON.stringify(this.image_list))return!1;this.image_list=t;for(var e=0;e<t.length;e++)n=t[e],void 0,(new Image).src=n;var n},getDataFromServer:function(t,e){var n=this,p=encodeURIComponent(popup.sa.store.getDistinctId()),o=encodeURIComponent(popup.info.platform),i=encodeURIComponent(popup.info.project);t=_.isFunction(t)?t:function(){},e=_.isFunction(e)?e:function(){},_.ajax({url:popup.info.api_base_url+"/sfo/user_popup_configs?distinct_id="+p+"&platform="+o+"&project="+i+"&time="+(new Date).getTime()+"&sdk_version="+popup.lib_version,type:"GET",cors:!0,credentials:!1,contentType:"application/json",success:function(p){if(!n.active_state)return e(),!1;popup.log("\u521d\u59cb\u5316-\u4fee\u6539-serverData-ajax\u83b7\u53d6"),_.isObject(p)&&p.server_current_time&&p.popup_plans&&/\d+\.\d+/.test(p.min_sdk_version_required)&&parseFloat(p.min_sdk_version_required)<=parseFloat(popup.lib_version)?(popup.serverData=p,_.isNumber(p.config_pull_interval_ms)&&p.config_pull_interval_ms>0&&(n.interval_time=p.config_pull_interval_ms),popup.serverData.local_update_time=(new Date).getTime(),popup.info.preload_image&&n.loadImage(popup.getImageList(p.popup_plans)),n.updateUserPlans(),n.setListenEvent()):(popup.log("\u521d\u59cb\u5316-\u6570\u636e\u5f02\u5e38-\u8bf7\u6c42\u8fd4\u56de\u7684\u6570\u636e\u9519\u8bef-\u4e2d\u6b62"),popup.serverData={},popup.localData={},n.updateLocalData()),t(),n.setIntervalTime(n.interval_time)},error:function(){if(!n.active_state)return e(),!1;popup.log("\u521d\u59cb\u5316-\u6570\u636e\u5f02\u5e38-\u8bf7\u6c42\u9519\u8bef-\u4e2d\u6b62"),popup.serverData={},t(),n.setIntervalTime(n.interval_time)}})},updateUserPlans:function(){var t=popup.store.getJSONData(),e=popup.sa.store.getDistinctId(),n=popup.serverData.user_id;t.popup_sdk_users[e]={user_id:n||e},n?t.popup_sdk_plans[n]?popup.localData=t.popup_sdk_plans[n]:t.popup_sdk_plans[e]&&(popup.localData=t.popup_sdk_plans[e],delete t.popup_sdk_plans[e]):t.popup_sdk_plans[e]&&(popup.localData=t.popup_sdk_plans[e]),popup.localData.update_time=(new Date).getTime(),popup.store.saveJSONData(t)},setIntervalTime:function(t){var e=this;this.data_interval=setTimeout(function(){popup.log("10\u5206\u949f\u5b9a\u65f6\u66f4\u65b0\u6570\u636e\u5f00\u59cb-------"),e.getDataFromServer()},t)},setFirstListen:function(){var t=this;this.getDataFromServer(function(){t.registerListen()})},updateLocalData:function(){var t=JSON.stringify(popup.localData);this.local_data!==t&&(this.local_data=t,popup.store.saveLocalData())},initial:function(){popup.store.init();var t=popup.localData.local_update_time,e=(new Date).getTime();if(_.isNumber(t)){var n=e-t;n<=0||n>=this.interval_time?this.setFirstListen():(this.setIntervalTime(this.interval_time-n),this.setListenEvent(),this.registerListen(),popup.info.preload_image&&this.loadImage(popup.getImageList(popup.localData.popup_plans)))}else this.setFirstListen()},changeId:function(){this.stopAllState(),this.startState({getLocalData:!1})},stopAllState:function(){this.active_state=!1,popup.eventRule={},this.data_interval&&window.clearTimeout(this.data_interval),this.save_interval&&window.clearInterval(this.save_interval),popup.asyncConvert.timer&&window.clearTimeout(popup.asyncConvert.timer),popup.convertPlans=[],popup.localData={},this.resetState()},resetState:function(){if("WEB"===popup.info.platform)return!1;!document.querySelector("div[data-sf-mask]")&&popup.isRun&&(popup.isRun=!1)},startState:function(t){this.active_state=!0,(t=t||{getLocalData:!0}).getLocalData&&(this.resetState(),popup.localData=popup.store.getLocalData()),this.getDataFromServer()}},popup.testSend={hasParam:function(){var t=_.URL(window.location.href).searchParams,e=t.get("sf_popup_test")||"",n=t.get("popup_window_id")||"",p=t.get("platform");return!(!e||!n)&&{sf_popup_test:e,popup_window_id:n,platform:p}},start:function(){if("WEB"!==this.hasParam().platform)return popup.log("H5\u6d4b\u8bd5\u5f39\u7a97\u8bf7\u5728\u79fb\u52a8\u7aef\u67e5\u770b\uff01"),!1;this.webCampaign()},webCampaign:function(){var t=popup.info.project,e=popup.info.platform,n=this.hasParam().popup_window_id,p=encodeURIComponent(popup.sa.store.getDistinctId());_.ajax({url:popup.info.api_base_url+"/sfo/popup_windows/"+n+"?project="+encodeURIComponent(t)+"&time="+(new Date).getTime()+"&sdk_version="+popup.lib_version+"&platform="+encodeURIComponent(e)+"&distinct_id="+p,type:"GET",credentials:!1,cors:!0,contentType:"application/json",success:function(t){var e,n=_.getUuid();_.isObject(t)||(popup.sa.log("\u6d4b\u8bd5\u5f39\u7a97-\u670d\u52a1\u7aef\u6570\u636e\u683c\u5f0f\u4e0d\u5408\u6cd5",t),t={});try{e=JSON.parse(t.content)}catch(i){popup.sa.log("\u6d4b\u8bd5\u5f39\u7a97-content\u89e3\u6790\u5931\u8d25,content:",t,i)}var p=popup.getPopupInfo(e);p.$sf_msg_id=n;var o={content:t.content,type:t.popup_type||"CUSTOMIZED"};_.isString(t.content)?"withoutCampaignListener"===popup.info.supportCustom||"withoutStart"===popup.info.supportCustom?(p.$sf_succeed=!1,p.$sf_fail_reason="\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03",popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onFailed(o,1006,"\u81ea\u5b9a\u4e49\u89e6\u8fbe\u8ba1\u5212\u672a\u5b9e\u73b0\u5f39\u7a97\u751f\u547d\u5468\u671f\u56de\u8c03")):(p.$sf_succeed=!0,popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onStart(o)):(p.$sf_succeed=!1,p.$sf_fail_reason="\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",popup.track.popupDisplay(p),popup.info.popup_campaign_listener.onFailed(o,1001,"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"))},error:function(t){popup.log("\u6d4b\u8bd5\u5f39\u7a97\u83b7\u53d6\u6570\u636e\u9519\u8bef",t)}})}},popup.setPara=function(t){_.isObject(t)||(t={}),popup.info=_.extend({},popup.defaultPara,t),popup.sa=popup.getWebSDK();var e=popup.sa;return e?_.isString(popup.info.api_base_url)&&"http"===popup.info.api_base_url.slice(0,4)?"http:"===popup.info.api_base_url.slice(0,5)&&"https:"===location.protocol?(popup.log("\u60a8\u7684\u5f53\u524d\u9875\u9762\u662fhttps\u7684\u5730\u5740\uff0capi_base_url \u4e5f\u5fc5\u987b\u662fhttps\uff01"),!1):(popup.info.api_base_url="/"===popup.info.api_base_url.slice(-1)?popup.info.api_base_url.slice(0,-1):popup.info.api_base_url,_.isString(e.para.server_url)&&"http"===e.para.server_url.slice(0,4)?(popup.info.project||(popup.info.project=_.URL(e.para.server_url).searchParams.get("project")||"default"),popup.info.supportCustom=!0,_.isObject(popup.info.popup_campaign_listener)?(_.isFunction(popup.info.popup_campaign_listener.shouldStart)||(popup.info.popup_campaign_listener.shouldStart=function(){return!0}),_.isFunction(popup.info.popup_campaign_listener.onStart)||(popup.info.supportCustom="withoutStart",popup.info.popup_campaign_listener.onStart=function(){}),_.isFunction(popup.info.popup_campaign_listener.onEnd)||(popup.info.popup_campaign_listener.onEnd=function(){}),_.isFunction(popup.info.popup_campaign_listener.onFailed)||(popup.info.popup_campaign_listener.onFailed=function(){})):(popup.info.supportCustom="withoutCampaignListener",popup.info.popup_campaign_listener={shouldStart:function(){return!0},onStart:function(){},onEnd:function(){},onFailed:function(){}}),!0):(popup.log("server_url \u5fc5\u987b\u586b\u5199\u6709\u6548\u6570\u636e\u63a5\u6536\u5730\u5740"),!1)):(popup.log("popup \u5fc5\u987b\u586b\u5199\u6709\u6548 api_base_url"),!1):(popup.log("web js sdk \u8fd8\u6ca1\u6709\u521d\u59cb\u5316\u5b8c\u6210"),!1)},popup.init=function(){if(!popup.isSupportPopup())return!1;if(window.screen.width&&Number(window.screen.width)<=1024)return"object"==typeof console&&console.log&&console.log("Web \u5f39\u7a97\u4ec5\u652f\u6301 PC\u7aef\uff0c\u4e14\u5c4f\u5e55\u5bbd\u5ea6\u5927\u4e8e 1024"),!1;var t={};return arguments.length>0&&(1===arguments.length&&_.isObject(arguments[0])?t=arguments[0]:arguments.length>=2&&_.isObject(arguments[1])&&(t=arguments[1])),!!this.setPara(t)&&(popup.info.platform="WEB",!!popup.setIsLoad()&&void(popup.testSend.hasParam()?popup.testSend.start():(popup.listenPageStateChange(),popup.updateDataAndSetListen.initial())))},window.SensorsDataWebJSSDKPlugin&&"[object Object]"===Object.prototype.toString.call(window.SensorsDataWebJSSDKPlugin)?window.SensorsDataWebJSSDKPlugin.WebPopup=window.SensorsDataWebJSSDKPlugin.WebPopup||popup:window.SensorsDataWebJSSDKPlugin={WebPopup:popup};export default popup;
\ No newline at end of file
var popup={sa:{},info:{app_id:"",show_log:!0},campaign_listener:{},lib_version:"0.4.4",defaultPara:{platform:"MINIPROGRAM",preload_image:!0,defer_render:!1},serverData:{},localData:{},event_list:[],popuping:!1,convertPlans:[],eventRule:{},popupTree:{},log:function(){if(popup.info.show_log&&"object"==typeof console&&console.log)try{return console.log.apply(console,arguments)}catch(t){console.log(arguments[0])}},CAMPAIGN_ERROR:{}},_={getRgba:function(t){return"object"!=typeof t?t:"rgba("+t.r+","+t.g+","+t.b+","+t.a+")"},getRpx:function(t){if(t){if(/^[0|1]?\.\d+$/.test(t))return 100*Number(t)+"%";var e=/^(-?\d+(\.\d+)?)px$/.exec(t);return e?2*Number(e[1])+"rpx":t}},extend:function(t){var e=Array.prototype.slice;return _.each(e.call(arguments,1),function(e){for(var p in e)void 0!==e[p]&&(t[p]=e[p])}),t},each:function(t,e,p){var n=Array.prototype.forEach,o={};if(null==t)return!1;if(n&&t.forEach===n)t.forEach(e,p);else if(t.length===+t.length){for(var i=0,r=t.length;i<r;i++)if(i in t&&e.call(p,t[i],i,t)===o)return!1}else for(var a in t)if(hasOwnProperty.call(t,a)&&e.call(p,t[a],a,t)===o)return!1},extend2Lev:function(t){var e=Array.prototype.slice;return _.each(e.call(arguments,1),function(e){for(var p in e)void 0!==e[p]&&null!==e[p]&&(_.isObject(e[p])&&_.isObject(t[p])?_.extend(t[p],e[p]):t[p]=e[p])}),t},getUuid:function(){var t=function(){return Math.random().toString(16).replace(".","")};return function(){var e=function(){for(var t=1*new Date,e=0;t==1*new Date;)e++;return t.toString(16)+e.toString(16)}()+"-"+t()+"-"+t();return e||(String(Math.random())+String(Math.random())+String(Math.random())).slice(2,15)}},trim:function(t){return t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},isEmptyObject:function(t){var e=Object.prototype.hasOwnProperty;if(_.isObject(t)){for(var p in t)if(e.call(t,p))return!1;return!0}return!1},filter:function(t,e,p){var n=Object.prototype.hasOwnProperty;if(t.filter)return t.filter(e);for(var o=[],i=0;i<t.length;i++)if(n.call(t,i)){var r=t[i];e.call(p,r,i,t)&&o.push(r)}return o},isObject:function(t){return null!=t&&"[object Object]"==Object.prototype.toString.call(t)},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},isString:function(t){return"[object String]"==Object.prototype.toString.call(t)},isDate:function(t){return"[object Date]"==Object.prototype.toString.call(t)},isBoolean:function(t){return"[object Boolean]"==Object.prototype.toString.call(t)},isNumber:function(t){return"[object Number]"==Object.prototype.toString.call(t)&&/[\d\.]+/.test(String(t))},isFunction:function(t){if(!t)return!1;var e=Object.prototype.toString.call(t);return"[object Function]"==e||"[object AsyncFunction]"==e},getURLSearchParams:function(t){for(var e=function(t){return decodeURIComponent(t)},p={},n=(t||"").split("&"),o=0;o<n.length;o++){var i=n[o].indexOf("=");if(-1!==i){var r=n[o].substring(0,i),a=n[o].substring(i+1);r=e(r),a=e(a),p[r]=a}}return p},setStorageSync:function(t,e){var p=function(){wx.setStorageSync(t,e)};try{p()}catch(t){logger.info("set Storage fail --",t);try{p()}catch(t){logger.info("set Storage fail again --",t)}}},getStorageSync:function(t){var e="";try{e=wx.getStorageSync(t)}catch(p){try{e=wx.getStorageSync(t)}catch(t){logger.info("getStorage fail")}}return e},parseStorageSync:function(t){var e=null;try{e=JSON.parse(_.getStorageSync(t))||null}catch(t){}return e}};_.isArray=Array.isArray||function(t){return"[object Array]"===toString.call(t)},_.matchImage=function(t){for(var e,p,n,o=new RegExp('("(backgroundImage|image)":"(http(s)?://.[^"]*))',"g"),i=new RegExp("http(s)?://.[^S]*"),r={},a=t.length,u=[],s=0;s<a;s++)if(e=!1,_.isObject(t[s])&&"ACTIVE"===t[s].status.toLocaleUpperCase()&&t[s].is_audience&&(t[s].hasOwnProperty("strategy_id")?t[s].is_trigger&&(e=!0):t[s].is_control_group||(e=!0)),e&&t[s].popup_window_content&&t[s].popup_window_content.content&&(p=t[s].popup_window_content.content.match(o)))for(var l=0,c=p.length;l<c;l++)(n=p[l].match(i))&&n.length>0&&(r[n[0]]||(r[n[0]]=1));return _.each(r,function(t,e){u.push(e)}),u},_.getConvertNumberValue=function(t){return _.isString(t)&&(t=Number(t)),Math.floor(1e3*t)/1e3},_.wxrequest=function(t){var e=wx.request(t);setTimeout(function(){_.isObject(e)&&_.isFunction(e.abort)&&e.abort()},3e4)},_.getProject=function(t){if(t&&t.split("?")[1]){var e=decodeURIComponent(t.split("?")[1]);return _.getURLSearchParams(e).project||"default"}return"default"},_.getCurrentPage=function(){var t=getCurrentPages(),e=t[t.length-1];return!!_.isObject(e)&&e},popup._=_,popup.handleEvents=function(t,e){if("send"===t){if(popup.popuping)return popup.event_list.push(e),!1;e.event&&popup.eventRule[e.event]&&popup.eventTriggerProcess(popup.eventRule[e.event],e)}if("changeDistinctId"===t&&popup.updateAndListenPlan.changeId(),"popup_display"===t){popup.popuping=!0;try{popup.info.popup_listener.onLoadSuccess(e.plan.plan_id)}catch(t){popup.log("popup_listener.onLoad error",t)}}if("popup_load_fail"===t){var p=e.plan_id,n=e.fail_code,o=e.fail_reason;try{popup.info.popup_listener.onLoadFailed(p,n,o)}catch(t){popup.log("popup_listener.onLoad error",t)}}if("popup_click"===t&&popup.track.popupClick(e),"popup_end"===t){popup.popuping=!1;var i={name:e.plan.cname,plan_id:e.plan.plan_id,content:e.plan.popup_window_content?e.plan.popup_window_content.content:"",type:e.plan.popup_window_content?e.plan.popup_window_content.popup_type:""};popup.CAMPAIGN_ERROR.onEnd||popup.campaign_listener.onEnd(i);try{popup.info.popup_listener.onClose(e.plan.plan_id)}catch(t){popup.log("popup_listener.onLoad error",t)}popup.updateGlobalCount(),popup.updatePlanInterval(e.plan),_.each(popup.event_list,function(t){t.event&&popup.eventRule[t.event]&&popup.eventTriggerProcess(popup.eventRule[t.event],t)}),popup.event_list=[]}},popup.setPara=function(t){if(_.isObject(t)||(t={}),popup.info=_.extend(popup.info,popup.defaultPara,t),popup.info.app_id||popup.log("\u521d\u59cb\u5316\u53c2\u6570 appid \u6821\u9a8c\u5931\u8d25\uff0c\u65e0\u6cd5\u62c9\u53d6\u5f39\u7a97\u8ba1\u5212!"),_.isString(popup.info.api_base_url)&&"http"===popup.info.api_base_url.slice(0,4)||popup.log("popup \u5fc5\u987b\u586b\u5199\u6709\u6548 api_base_url"),popup.info.project||(popup.info.project=_.getProject(popup.sa.para.server_url)),_.isObject(popup.info.popup_listener)){var e=popup.info.popup_listener;_.isFunction(e.onClick)||(popup.info.popup_listener.onClick=function(){}),_.isFunction(e.onLoadSuccess)||(popup.info.popup_listener.onLoadSuccess=function(){}),_.isFunction(e.onLoadFailed)||(popup.info.popup_listener.onLoadFailed=function(){}),_.isFunction(e.onClose)||(popup.info.popup_listener.onClose=function(){})}else popup.info.popup_listener={onClick:function(){},onLoadSuccess:function(){},onLoadFailed:function(){},onClose:function(){}};_.isObject(t.campaign_listener)?(popup.campaign_listener=_.extend({},t.campaign_listener),popup.campaign_listener.shouldStart&&_.isFunction(popup.campaign_listener.shouldStart)||(popup.campaign_listener.shouldStart=function(){return!0},popup.CAMPAIGN_ERROR.shouldStart={error_code:"4001",reeor_txt:"NOT_DEFINED OR DEFINED_ERROR"}),popup.campaign_listener.onStart?_.isFunction(popup.campaign_listener.onStart)||(popup.CAMPAIGN_ERROR.onStart={error_code:"4002",reeor_txt:"DEFINED_TYPE_ERROR"}):popup.CAMPAIGN_ERROR.onStart={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.campaign_listener.onEnd?_.isFunction(popup.campaign_listener.onEnd)||(popup.CAMPAIGN_ERROR.onEnd={error_code:"4002",reeor_txt:"DEFINED_TYPE_ERROR"}):popup.CAMPAIGN_ERROR.onEnd={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.campaign_listener.onFailed?_.isFunction(popup.campaign_listener.onFailed)||(popup.CAMPAIGN_ERROR.onFailed={error_code:"4002",reeor_txt:"DEFINED_TYPE_ERROR"}):popup.CAMPAIGN_ERROR.onFailed={error_code:"4001",reeor_txt:"NOT_DEFINED"}):(popup.campaign_listener.shouldStart=function(){return!0},popup.CAMPAIGN_ERROR.shouldStart={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.CAMPAIGN_ERROR.onStart={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.CAMPAIGN_ERROR.onEnd={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.CAMPAIGN_ERROR.onFailed={error_code:"4001",reeor_txt:"NOT_DEFINED"},popup.CAMPAIGN_ERROR.campaign_listener={error_code:"4003",errot_txt:"CAMPAIGN_CUSTOMIZED_NULL_LISTENER OR DEFINED ERROR"})},popup.dataRender={that:null,queue:[],notify:function(t){_.isFunction(this.handle)?this.handle(this.that,t):this.queue.push(t)}},popup.popupEmitter={image_list:[],loaded:!1,notify:function(t){var e=_.getCurrentPage(),p=this;e&&_.isObject(e)&&_.isFunction(e.selectComponent)&&(popup.info.defer_render?setTimeout(function(){p.renderPopup(e,t)},0):p.renderPopup(e,t))},renderPopup:function(t,e){var p=t.selectComponent("#sensors_popup");_.isObject(p)&&_.isFunction(p.handle)?p.handle(e):popup.log("\u5f53\u524d\u9875\u9762\u672a\u96c6\u6210\u5f39\u7a97\u7ec4\u4ef6")},loadImage:function(t){if(JSON.stringify(t)!==JSON.stringify(this.image_list)&&(this.loaded=!1,this.image_list=t),!this.loaded){var e=_.getCurrentPage();if(e&&_.isObject(e)&&_.isFunction(e.selectComponent)){var p=e.selectComponent("#sensors_popup");_.isObject(p)&&_.isFunction(p.loadImage)&&(p.loadImage(t),this.loaded=!0)}}},attached:function(){this.loaded||this.loadImage(this.image_list)}},popup.testPopup=function(){wx.onAppShow(function(t){popup.updateAndListenPlan.pullPlan(),popup.testSend.start(t)})},popup.updateGlobalCount=function(){var t=popup.sa.store.getDistinctId(),e=popup.localData.user_list[t],p=(new Date).getTime();if(!_.isArray(popup.localData.plan_list[e].global_popup_count))return popup.localData.plan_list[e].global_popup_count=[],popup.localData.plan_list[e].global_popup_count.unshift(p),!1;popup.localData.plan_list[e].global_popup_count.shift(),popup.localData.plan_list[e].global_popup_count.unshift(p)},popup.updatePlanInterval=function(t){var e=(new Date).getTime();_.isObject(t)&&_.isObject(t.popup_interval)&&t.popup_interval.value&&(t.is_in_popup_interval_window=popup.ruleTime.getExpire(t.popup_interval,e))},popup.init=function(t,e){popup.log("\u5f39\u7a97\u5f00\u59cb\u521d\u59cb\u5316\uff01"),this.sa=t,this.setPara(e),this.sub=new t.eventSub(this.handleEvents),popup.updateAndListenPlan.initial(),popup.testPopup(),t.popupEmitter=popup.popupEmitter},popup.changeCovertStatus=function(t){var e=JSON.parse(JSON.stringify(popup.convertPlans));_.each(e,function(p,n){var o=p.is_in_convert_window.step,i=p.is_in_convert_window.uuid;if(popup.convertPlans[n].is_in_convert_window.step=Math.min(2*o,6e5),!t||!_.isArray(t)||0===t.length)return!1;_.each(t,function(t){t.popup_display_uuid===i&&t.convert_time&&(delete popup.convertPlans[n].is_in_convert_window,popup.convertPlans.splice(n,1),e.splice(n,1),n--)})}),popup.updateAndListenPlan.updateData()},popup.asyncConvert=function(t){var e=popup.info.project,p=!1;if(!t&&0===popup.convertPlans.length)return!1;t&&(_.each(popup.convertPlans,function(e){e.plan_id===t.plan_id&&(p=!0)}),p||popup.convertPlans.push(t)),function t(){if(_.isEmptyObject(popup.localData)||!_.isArray(popup.convertPlans)||0===popup.convertPlans.length)return!1;var p=popup.convertPlans,n=p[0].is_in_convert_window&&p[0].is_in_convert_window.step||5e3,o=[],i=Date.now();_.each(p,function(t){var e=t.is_in_convert_window;if(!e)return!1;e.step||(e.step=5e3),n>e.step&&(n=e.step)}),_.each(p,function(t){if(!t.is_in_convert_window)return!1;var e=t.is_in_convert_window.expire_time;if(i>e||n>e-i)return delete t.is_in_convert_window,!1;o.push(t.is_in_convert_window.uuid)});var r=_.filter(p,function(t){return!!t.is_in_convert_window&&i<t.is_in_convert_window.expire_time});if(popup.convertPlans=r,!o.length)return!1;popup.asyncConvert.timer&&clearTimeout(popup.asyncConvert.timer),popup.asyncConvert.timer=setTimeout(function(){_.wxrequest({url:popup.info.api_base_url+"/sfo/popup_displays?project="+encodeURIComponent(e)+"&popup_display_uuids="+encodeURIComponent(o)+"&time="+(new Date).getTime(),type:"GET",success:function(e){var p=e.data;popup.changeCovertStatus(p),t()},fail:function(){popup.changeCovertStatus(),t()}})},n)}()},popup.ruleTime={getExpire:function(t,e){var p=e,n=Number(t.value)||0,o=Number(t.value)||0,i=String(t.unit).toLowerCase(),r=null,a={day:function(){return(r=new Date(p)).setHours(23),r.setMinutes(59),r.setSeconds(59),r.setMilliseconds(999),r=r.getTime()+864e5*(o-1)},week:function(){var t=(r=new Date(p)).getDay();0===t&&(t=7);var e=7-t;return r.setHours(23),r.setMinutes(59),r.setSeconds(59),r.setMilliseconds(999),r=r.getTime()+24*e*60*60*1e3+7*(o-1)*24*60*60*1e3},month:function(){var t=(r=new Date(p)).getMonth()+o;return t>11?(r.setFullYear(r.getFullYear()+parseInt(t/12)),r.setMonth(t%12)):r.setMonth(t),r.setDate(1),r.setHours(0),r.setMinutes(0),r.setSeconds(0),r.setMilliseconds(0),r.getTime()},second:function(t){var e={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return r=new Date(p),t in e&&(o=e[t]*n),r.getTime()+o}};return!0!==t.natural?a.second(i):i in a?a[i]():void 0},getLast:function(t,e){var p=Number(t.value)||0,n=Number(t.value)-1||0,o=String(t.unit).toLowerCase(),i=null,r={day:function(){return(i=new Date(e)).setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-864e5*n},week:function(){var t=(i=new Date(e)).getDay();return 0===t&&(t=7),--t,i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i=i.getTime()-(24*t*60*60*1e3+7*n*24*60*60*1e3)},month:function(){var t=(i=new Date(e)).getMonth()+1-n;return t<=0?(i.setFullYear(i.getFullYear()+(parseInt(t/12)-1)),i.setMonth(12+t%12-1)):i.setMonth(t-1),i.setDate(1),i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.getTime()},second:function(t){var n={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3},o=null;return i=new Date(e),t in n&&(o=n[t]*p),i.getTime()-o}};return!0!==t.natural?r.second(o):o in r?r[o]():void 0},getArrMatchCount:function(t,e){var p=0;for(p=0;p<t.length;p++)if(e>=t[p])return p;return t.length},checkRule:function(t,e){var p=new Date,n=e,o=Number(t.value)||0,i=Number(t.value)-1||0,r=String(t.unit).toLowerCase(),a=null,u={day:function(){return(a=new Date(n)).setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+864e5*i,p>a},week:function(){var t=(a=new Date(n)).getDay();0===t&&(t=7);var e=7-t;return a.setHours(23),a.setMinutes(59),a.setSeconds(59),a.setMilliseconds(999),a=a.getTime()+24*e*60*60*1e3+7*i*24*60*60*1e3,p>a},month:function(){var t=(a=new Date(n)).getMonth()+i;return t>=11?(a.setFullYear(a.getFullYear()+t/11),a.setMonth(t%11)):a.setMonth(t),a.setDate(1),a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0),p>a},second:function(t){return a=new Date(n),t in inteval&&(interval_time={month:2592e6,week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3}[t]*o),p>a+null}};return!0!==t.natural?u.second(r):r in u?u[r]():void 0}},popup.eventTriggerProcess=function(t,e){var p=!1;_.isArray(t)&&t.length>0&&_.isObject(t[0])&&(popup.log("--------------------\u89e6\u53d1\u4e8b\u4ef6\u5f00\u59cb--------------------"),_.each(t,function(t){_.isObject(t)&&void 0!==t.match_state&&delete t.match_state,new popup.RuleCheck(t,e)}),_.each(t,function(t){!0===t.match_state?!1===p?(p=!0,popup.log("\u68c0\u67e5\u5b8c\u6bd5-\u4f18\u5148\u5f39\u7a97-\u5f00\u59cb",t.plan.cname),new popup.PopupCheck(t,!0)):!0===p&&(popup.log("\u68c0\u67e5\u5b8c\u6bd5-\u975e\u4f18\u5148\u5f39\u7a97-\u4e0d\u6e32\u67d3",t.plan.cname),new popup.PopupCheck(t,!1)):popup.log("\u68c0\u67e5\u5b8c\u6bd5-\u8ba1\u5212-\u4e0d\u6ee1\u8db3",t.plan.cname)}),popup.log("--------------------\u89e6\u53d1\u4e8b\u4ef6\u7ed3\u675f--------------------"))},popup.PopupCheck=function(t,e){this.plan=t.plan,this.current_time=(new Date).getTime(),e?this.displayPopup():this.hidePopup()},popup.PopupCheck.prototype.displayPopup=function(){var t=_.getUuid()(),e={props:{$sf_succeed:!0}};popup.popupTree={},e.uuid=t,e.plan=this.plan;var p=this.plan.popup_window_content,n="",o=!0;if(p&&p.content)try{n=JSON.parse(p.content),new popup.parseTree(n)}catch(t){n=!1,o=!1}else popup.log("\u8ba1\u5212\u65e0\u7a97\u4f53\u5185\u5bb9\uff01"),o=!1;e.popupTree=popup.popupTree;var i={name:this.plan.cname,plan_id:this.plan.plan_id,content:this.plan.popup_window_content?this.plan.popup_window_content.content:"",type:this.plan.popup_window_content?this.plan.popup_window_content.popup_type:""};this.plan.hasOwnProperty("strategy_id")?this.plan.is_trigger?popup.campaign_listener.shouldStart(i)?p?"CUSTOMIZED"===p.popup_type?(e.popupTree={},popup.CAMPAIGN_ERROR.onStart?(e.props={$sf_fail_reason:"onStart \u672a\u5b9a\u4e49",$sf_succeed:!1},popup.track.popupDisplay(e),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,1004,"onStart \u672a\u5b9a\u4e49")):p.content?(popup.track.popupDisplay(e),popup.campaign_listener.onStart(i),popup.info.popup_listener.onLoadSuccess(this.plan.plan_id)):(e.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u9519\u8bef",$sf_succeed:!1},popup.track.popupDisplay(e),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,1001,"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"))):o?(popup.track.popupDisplay(e),popup.CAMPAIGN_ERROR.onStart||popup.campaign_listener.onStart(i),this.renderPopup(e)):(e.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u9519\u8bef",$sf_succeed:!1},popup.track.popupDisplay(e),popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e")):(e.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u9519\u8bef",$sf_succeed:!1},popup.track.popupDisplay(e),popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e")):(e.props={$sf_fail_reason:"shouldStart \u63a5\u53e3\u8fd4\u56de false",$sf_succeed:!1},popup.track.popupDisplay(e),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1004","shouldStart \u63a5\u53e3\u8fd4\u56de false")):(e.props={$sf_fail_reason:"\u8ba1\u5212\u4e0b\u53d1 is_trigger \u4e3a false",$sf_succeed:!1},popup.track.popupDisplay(e),p&&"PRESET"===p.popup_type&&popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"1005","\u8ba1\u5212\u4e0b\u53d1 is_trigger \u4e3a false"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1005","\u8ba1\u5212\u4e0b\u53d1 is_trigger \u4e3a false")):this.plan.is_control_group?(e.props={$sf_fail_reason:"\u5bf9\u7167\u7ec4",$sf_succeed:!1},popup.track.popupDisplay(e),popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"2000","\u5bf9\u7167\u7ec4"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"2000","\u5bf9\u7167\u7ec4")):popup.campaign_listener.shouldStart(i)?o?(popup.track.popupDisplay(e),popup.CAMPAIGN_ERROR.onStart||popup.campaign_listener.onStart(i),this.renderPopup(e)):(e.props={$sf_fail_reason:"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",$sf_succeed:!1},popup.track.popupDisplay(e),popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e")):(e.props={$sf_fail_reason:"shouldStart \u63a5\u53e3\u8fd4\u56de false",$sf_succeed:!1},popup.track.popupDisplay(e),popup.info.popup_listener.onLoadFailed(this.plan.plan_id,"1004","shouldStart \u63a5\u53e3\u8fd4\u56de false"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(i,"1004","shouldStart \u63a5\u53e3\u8fd4\u56de false"));this.startConvertWindow(t),this.startPopupIntervalWindow(),this.startPopupLimitWindow(),this.setGlobalLimit(),this.deletePlanAllWindow(),popup.updateAndListenPlan.updateData()},popup.PopupCheck.prototype.hidePopup=function(){this.deletePlanAllWindow(),popup.updateAndListenPlan.updateData()},popup.PopupCheck.prototype.renderPopup=function(t){popup.log("\u6e32\u67d3\u5f39\u7a97"),popup.popupEmitter.notify(t)},popup.PopupCheck.prototype.startConvertWindow=function(t){popup.log("--\u5f39\u7a97\u5c55\u793a-\u8f6c\u5316\u7a97\u53e3\u8bbe\u7f6e"),_.isObject(this.plan.convert_window)&&this.plan.convert_window.value&&(this.plan.is_in_convert_window={expire_time:popup.ruleTime.getExpire(this.plan.convert_window,this.current_time),start_time:this.current_time,uuid:t},popup.asyncConvert(this.plan))},popup.PopupCheck.prototype.startPopupIntervalWindow=function(){_.isObject(this.plan.popup_interval)&&this.plan.popup_interval.value&&(this.plan.is_in_popup_interval_window=popup.ruleTime.getExpire(this.plan.popup_interval,this.current_time))},popup.PopupCheck.prototype.startPopupLimitWindow=function(){popup.log("--\u5f39\u7a97\u5c55\u793a-\u53c2\u4e0e\u9650\u5236\u7a97\u53e3\u8bbe\u7f6e\u91cd\u7f6e"),_.isObject(this.plan.re_enter)&&this.plan.re_enter.value&&(_.isObject(this.plan.is_in_popup_limit_window)?this.plan.is_in_popup_limit_window.count++:this.plan.is_in_popup_limit_window={expire_time:popup.ruleTime.getExpire(this.plan.re_enter,this.current_time),count:1})},popup.PopupCheck.prototype.setGlobalLimit=function(){popup.log("--\u5f39\u7a97\u5c55\u793a-\u5168\u5c40\u5f39\u7a97\u6b21\u6570\u8bbe\u7f6e");var t=popup.store.getCurrentUserPlanList();_.isArray(t.global_popup_count)||(t.global_popup_count=[]),t.global_popup_count.unshift(this.current_time);for(var e=t.global_popup_count,p=e[e.length-1];p+7776e6<this.current_time||e.length>3e3;)e.pop(),p=e[e.length-1]},popup.PopupCheck.prototype.deletePlanAllWindow=function(){var t=this.plan.pattern_popup.matcher_list;_.isArray(t)&&_.each(t,function(t){t.is_in_window&&(popup.log("--\u5f39\u7a97\u5c55\u793a-\u91cd\u7f6e\u5404\u4e2a\u89c4\u5219\u7684\u7a97\u53e3\u8ba1\u7b97-\u6210\u529f"),delete t.is_in_window)})},popup.RuleCheck=function(t,e){this.plan_match=t,this.plan=t.plan,this.rule_arr=t.rule,this.event_data=e,this.current_time=(new Date).getTime();var p="-------------\u68c0\u67e5-\u8ba1\u5212-("+this.plan.cname+")";_.each(this.rule_arr,function(t){p+="--\u5305\u542b\u89c4\u5219-("+t.event_name+"\uff09-\u89e6\u53d1"+t.params[0]+"\u6b21"}),popup.log(p),popup.log(this.plan),this.checkPlanIsExpire(),popup.updateAndListenPlan.updateData()},popup.RuleCheck.prototype.checkPlanIsExpire=function(){!this.plan.expire_at||_.isNumber(this.plan.expire_at)&&this.current_time<this.plan.expire_at?(popup.log("--\u8fc7\u671f-\u6ee1\u8db3"),this.checkPlanIsAudience()):popup.log("--\u8fc7\u671f-\u4e0d\u6ee1\u8db3")},popup.RuleCheck.prototype.checkPlanIsAudience=function(){!0===this.plan.is_audience?(popup.log("--\u662f\u5426\u53d7\u4f17-\u6ee1\u8db3"),this.checkPlanSuspend()):popup.log("--\u662f\u5426\u53d7\u4f17-\u4e0d\u6ee1\u8db3")},popup.RuleCheck.prototype.checkPlanSuspend=function(){this.plan.status&&"SUSPEND"===this.plan.status?popup.log("--\u6682\u505c-\u4e0d\u6ee1\u8db3"):(popup.log("--\u6682\u505c-\u6ee1\u8db3"),this.checkConvert())},popup.RuleCheck.prototype.checkConvert=function(){_.isObject(this.plan.is_in_convert_window)&&this.plan.is_in_convert_window.expire_time>this.current_time?popup.log("--\u5b58\u5728\u8f6c\u5316\u7a97\u53e3 - \u4e0d\u6ee1\u8db3",this.plan.is_in_convert_window):(popup.log("--\u4e0d\u5b58\u5728\u8f6c\u5316\u7a97\u53e3\u6216\u8005\u7a97\u53e3\u8d85\u65f6\u5df2\u7ecf\u8fc7\u671f - \u6ee1\u8db3",this.plan.is_in_convert_window),this.checkGlobalPopupInterval())},popup.RuleCheck.prototype.checkGlobalPopupInterval=function(){var t=popup.store.getCurrentUserPlanList(),e=t.global_popup_count;if(_.isArray(e)&&e.length>=1){var p=popup.ruleTime.getLast(t.popup_interval_global,this.current_time);p>e[0]?(popup.log("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3-"+p+">\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+e[0]),this.checkPopupInterval()):popup.log("\u68c0\u67e5-\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3-"+p+"<\u4e0a\u6b21\u5f39\u7a97\u65f6\u95f4"+e[0])}else popup.log("--\u5168\u5c40\u5f39\u7a97\u95f4\u9694-\u6ca1\u6709\u5f39\u8fc7\u7a97-\u6ee1\u8db3"),this.checkPopupInterval()},popup.RuleCheck.prototype.checkPopupInterval=function(){_.isNumber(this.plan.is_in_popup_interval_window)?this.current_time>this.plan.is_in_popup_interval_window?(popup.log("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5927\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u6ee1\u8db3"),this.plan.is_in_popup_interval_window=null,this.checkProperties()):popup.log("--\u5f39\u7a97\u95f4\u9694-\u5f53\u524d\u65f6\u95f4\u5c0f\u4e8e\u56fa\u5b9a\u5f39\u7a97\u95f4\u9694-\u4e0d\u6ee1\u8db3"):(popup.log("--\u5f39\u7a97\u95f4\u9694-\u7a97\u53e3\u4e0d\u5b58\u5728-\u65b0\u5f00"),this.plan.is_in_popup_interval_window=null,this.checkProperties())},popup.RuleCheck.prototype.checkProperties=function(){var t={equal:function(t,e){if(!_.isNumber(t)&&!_.isString(t))return!1;for(var p=0,n=e.length;p<n;p++){if(!_.isNumber(e[p])&&!_.isString(e[p]))return!1;if(_.isString(t)){if(t===(_.isString(e[p])?e[p]:String(e[p])))return!0}else if(_.getConvertNumberValue(t)===_.getConvertNumberValue(e[p]))return!0}return!1},notEqual:function(t,e){if(!_.isNumber(t)&&!_.isString(t))return!1;for(var p=0,n=e.length;p<n;p++){if(!_.isNumber(e[p])&&!_.isString(e[p]))return!1;if(_.isString(t)){if(t===(_.isString(e[p])?e[p]:String(e[p])))return!1}else if(_.getConvertNumberValue(t)===_.getConvertNumberValue(e[p]))return!1}return!0},contain:function(t,e){return!!_.isString(t)&&t.indexOf(e[0])>=0},notContain:function(t,e){return!!_.isString(t)&&-1===t.indexOf(e[0])},isTrue:function(t){return!0===t},isFalse:function(t){return!1===t},isSet:function(t){return void 0!==t},notSet:function(t){return void 0===t},isEmpty:function(t){if(!_.isString(t)&&!_.isArray(t))return!1;if(_.isString(t))return""===t;for(var e=0;e<t.length;e++){if(""!==t[e].replace(/^\s+|\s+$/g,""))return!1}return!0},isNotEmpty:function(t){if(!_.isString(t)&&!_.isArray(t))return!1;if(_.isString(t))return""!==t;for(var e=0;e<t.length;e++){if(""===t[e].replace(/^\s+|\s+$/g,""))return!1}return!0},less:function(t,e){return!!_.isNumber(t)&&t<Number(e[0])},greater:function(t,e){return!!_.isNumber(t)&&t>Number(e[0])},between:function(t,e){return!!_.isNumber(t)&&(t>=Number(e[0])&&t<=Number(e[1]))},in:function(t,e){if(!_.isArray(t))return!1;for(var p=0;p<t.length;p++)if(e.indexOf(t[p])>=0)return!0;return!1},notInclude:function(t,e){if(!_.isArray(t))return!1;for(var p=0;p<t.length;p++)if(-1===e.indexOf(t[p]))return!0;return!1},absolute_between:function(t,e){try{var p=new Date(e[0]),n=new Date(e[1]),o=new Date(t);return o>=p&&o<=n}catch(t){popup.log("absolute_between Error",t)}},absoluteBetween:function(t,e){try{var p=new Date(e[0]),n=new Date(e[1]),o=new Date(t);return o>=p&&o<=n}catch(t){popup.log("absolute_between Error",t)}}},e=this,p=_.filter(this.rule_arr,function(p){if(!p.filter||p.filter.conditions&&0===p.filter.conditions.length)return!0;var n=p.filter,o=n.relation,i="or"===String(o).toLowerCase(),r="and"===String(o).toLowerCase(),a=!!r,u=!0;return _.each(n.conditions,function(p){if(!u)return!1;if(!p.field)return!1;var n=p.field.lastIndexOf("."),o=p.params,s=p.function;if(!t[s])return a=!1,u=!1,!1;if(n<0)return!1;var l=p.field.slice(n+1),c=e.event_data.properties[l],_=t[s](c,o);i&&_&&(a=!0,u=!1),r&&!_&&(a=!1,u=!1)}),a});_.isArray(p)&&p.length>0?(this.checkWindowAndMatch(p),popup.log("--\u5c5e\u6027\u5339\u914d-\u6ee1\u8db3",p)):popup.log("--\u5c5e\u6027\u5339\u914d-\u4e0d\u6ee1\u8db3")},popup.RuleCheck.prototype.checkWindowAndMatch=function(t){var e=this,p=[];_.each(t,function(t){if(!t.params||!t.params[0])return popup.log("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570\u636e\u5f02\u5e38"),!1;var n=Number(t.params[0]);1===n?p.push(t):n>1&&_.isObject(t.window)&&t.window.value>0&&(!_.isObject(t.is_in_window)||!_.isNumber(t.is_in_window.expire_time)||t.is_in_window.expire_time<e.current_time?t.is_in_window={expire_time:popup.ruleTime.getExpire(t.window,e.current_time),count:1}:t.is_in_window.count=t.is_in_window.count+1,t.is_in_window.count>=n?p.push(t):popup.log("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u89c4\u5219\u6570",t.is_in_window.count,"\u4e0d\u5339\u914d\u5f53\u524d\u6b21\u6570",n))}),p.length>0?(popup.log("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",p),this.checkGlobalPopupLimit()):popup.log("--\u7a97\u53e3\u671f\u548c\u6b21\u6570-\u6ca1\u6709\u5339\u914d\u6210\u529f\u7684\u89c4\u5219",p)},popup.RuleCheck.prototype.checkGlobalPopupLimit=function(){var t=popup.store.getCurrentUserPlanList(),e=t.msg_limit_global,p=!0,n=this;_.isObject(e)&&!0===e.is_in_use&&_.isArray(e.limits)&&_.isArray(t.global_popup_count)&&!0===this.plan.global_msg_limit_enabled?(_.each(e.limits,function(e){if(_.isObject(e)&&_.isNumber(e.limit)){var o=popup.ruleTime.getLast(e,n.current_time),i=popup.ruleTime.getArrMatchCount(t.global_popup_count,o);popup.log("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u5df2\u7ecf\u5f39\u7a97\u6b21\u6570-"+i+"-\u9650\u5236\u7684\u6b21\u6570"+e.limit+"-\u9650\u5236\u65f6\u95f4-"+o),p=i<e.limit?p&&!0:p&&!1}}),p?this.checkPopupLimit():popup.log("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u4e0d\u6ee1\u8db3")):(popup.log("--\u5168\u5c40\u5f39\u7a97\u9650\u5236-\u4e0d\u6ee1\u8db3(\u53c2\u6570\u6b63\u5e38\uff0c\u5df2\u5f39\u8fc7\u7a97\uff0c\u5f53\u524d\u8ba1\u5212\u8bbe\u7f6e\u4e86\u9650\u5236)\u4e4b\u4e00 - \u6ee1\u8db3"),this.checkPopupLimit())},popup.RuleCheck.prototype.checkPopupLimit=function(){if(!_.isObject(this.plan.re_enter)||!_.isNumber(this.plan.re_enter.value)||!_.isNumber(this.plan.re_enter.limit))return this.plan_match.match_state=!0,!1;_.isObject(this.plan.is_in_popup_limit_window)&&_.isNumber(this.plan.is_in_popup_limit_window.expire_time)&&_.isNumber(this.plan.is_in_popup_limit_window.count)?this.plan.is_in_popup_limit_window.expire_time<this.current_time?(popup.log("--\u53c2\u4e0e\u9650\u5236-\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236\u7a97\u53e3-\u5f00\u542f\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window,this.plan_match.match_state=!0):this.plan.is_in_popup_limit_window.count<this.plan.re_enter.limit?(popup.log("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4e14\u5728\u53c2\u4e0e\u9650\u5236\u6b21\u6570\u5185-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0):popup.log("--\u53c2\u4e0e\u9650\u5236-\u5728\u7a97\u53e3\u5185\u4f46\u662f\u8d85\u8fc7\u4e86\u53c2\u4e0e\u9650\u5236-\u4e0d\u6ee1\u8db3",this.plan.is_in_popup_limit_window):(this.plan.is_in_popup_limit_window?(popup.log("--\u53c2\u4e0e\u9650\u5236-\u6709\u7a97\u53e3\u4f46\u662f\u7a97\u53e3\u6570\u636e\u5f02\u5e38-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),delete this.plan.is_in_popup_limit_window):popup.log("--\u53c2\u4e0e\u9650\u5236-\u4e0d\u5b58\u5728\u7a97\u53e3-\u5f00\u65b0\u7a97\u53e3-\u6ee1\u8db3",this.plan.is_in_popup_limit_window),this.plan_match.match_state=!0)},popup.store={getJSONData:function(){return _.parseStorageSync("sensorsdata202002-popupdata")},saveJSONData:function(){_.setStorageSync("sensorsdata202002-popupdata",JSON.stringify(popup.localData))},getUserId:function(){var t=popup.sa.store.getDistinctId();return popup.localData.user_list[t]},getCurrentUserPlanList:function(){var t=this.getUserId();return popup.localData.plan_list[t]}},popup.updateAndListenPlan={active_state:!0,interval_time:6e5,save_interval:null,data_interval:null,local_data:{},diffData:function(){var t=popup.store.getCurrentUserPlanList(),e=popup.store.getUserId(),p=JSON.parse(JSON.stringify(popup.serverData));if(!p||_.isEmptyObject(p))return!1;if(!t||_.isEmptyObject(t)||!t.popup_plans||0===t.popup_plans.length)return popup.localData.plan_list[e]=p,popup.localData.plan_list[e].update_time=Date.now(),!1;var n=p.popup_plans;_.each(n,function(e,p){var o=null;if(_.each(t.popup_plans,function(t){t.plan_id===e.plan_id&&(o=t,_.isObject(e.window_update)&&_.each(e.window_update,function(p,n){switch(n){case"trigger_window":t.window_update&&t.window_update[n]&&t.window_update[n]===p||(o.pattern_popup.matcher_list=e.pattern_popup.matcher_list);break;case"convert_window":t.window_update&&t.window_update[n]&&t.window_update[n]===p||_.isObject(o.is_in_convert_window)&&o.is_in_convert_window.expire_time&&o.is_in_convert_window.start_time&&(o.is_in_convert_window.expire_time=popup.ruleTime.getExpire(e.convert_window,o.is_in_convert_window.start_time))}}))}),!o)return!1;if(!e.window_update&&o.last_update_config_time!==e.last_update_config_time)return!1;e.audience_id||delete o.audience_id;var i=o.pattern_popup.matcher_list;_.extend2Lev(o,e),o.pattern_popup.matcher_list=i,n[p]=o});var o=t.global_popup_count;t={},o&&(t.global_popup_count=o),_.extend(t,p),t.update_time=Date.now(),popup.localData.plan_list[e]=t,popup.log("\u521d\u59cb\u5316-\u6bd4\u5bf9\u6570\u636e\u5f97\u5230\u9700\u8981\u7684-localData",popup.localData)},filterConvertPlans:function(){var t=popup.store.getCurrentUserPlanList();if(!t||_.isEmptyObject(t))return!1;var e=t.popup_plans,p=Date.now();if(!e||!_.isArray(e))return!1;var n=_.filter(e,function(t){return!!t.convert_window&&!!t.is_in_convert_window&&p<t.is_in_convert_window.expire_time});popup.convertPlans=n,popup.log("\u521d\u59cb\u5316-\u5f02\u6b65\u7684convertWindow",popup.convertPlans),popup.asyncConvert()},updateData:function(){var t=this.local_data,e=JSON.stringify(popup.localData);e!==t&&(t=e,popup.store.saveJSONData())},updateLocalData:function(){var t={get(e,p){try{return _.isObject(e[p])?(popup.localData.target[p]=new Proxy(e[p],t),new Proxy(e[p],t)):e[p]}catch(t){return e[p]}},set(t,e,p){var n=t[e];return n!==p&&popup.log("\u4fee\u6539 localdata \u6570\u636e: ",n," - ",p),t[e]=p,popup.store.saveJSONData(),!0},deleteProperty:function(t,e){return delete t[e],popup.log("deleteProperty localdata",t,e),popup.store.saveJSONData(),!0}};popup.localData=new Proxy(popup.localData,t)},getEventRule:function(){var t,e=popup.store.getCurrentUserPlanList(),p={};return!!e&&(!(!(t=e.popup_plans)||!_.isArray(t))&&(_.each(t,function(t){var e=t.pattern_popup.matcher_list;_.each(e,function(e){var n={plan:t,rule:[e]},o=e.event_name,i=!1;if(p[o]){if(_.each(p[o],function(p){p.plan.plan_id===t.plan_id&&(p.rule.push(e),i=!0)}),i)return!1;p[o].push(n)}else p[o]=[n]})}),_.each(p,function(t){t.sort(function(t,e){var p=e.plan.absolute_priority-t.plan.absolute_priority;return 0===p?e.plan.plan_id-t.plan.plan_id:p})}),popup.eventRule=p,popup.log("\u521d\u59cb\u5316-\u5f97\u5230\u4e8b\u4ef6\u548c\u8ba1\u5212\u7684\u5173\u7cfb"),void popup.log("--------------------\u521d\u59cb\u5316\u5b8c\u6210--------------------\u7b49\u5f85\u4e8b\u4ef6\u89e6\u53d1\u8ba1\u5212--------------------")))},setListenEvent:function(){this.updateUserPlans(),this.diffData(),this.filterConvertPlans(),this.getEventRule(),this.updateData()},setIntervalTime:function(t){var e=this;e.data_interval&&clearTimeout(e.data_interval),e.data_interval=setTimeout(function(){popup.log("10\u5206\u949f\u5b9a\u65f6\u4e0b\u62c9\u8ba1\u5212-------"),e.pullPlan()},t)},initial:function(){popup.distinct_id=popup.sa.store.getDistinctId();var t=popup.store.getJSONData()||{};t.user_list||t.plan_list?popup.localData=_.extend(popup.localData,t):this.transData(t),this.updateLocalPlans(),this.setListenEvent(),this.pullPlan()},changeId:function(){this.stopAllState(),this.startState()},stopAllState:function(){this.active_state=!1;var t=popup.store.getUserId();popup.eventRule={},this.data_interval&&clearTimeout(this.data_interval),this.save_interval&&clearInterval(this.save_interval),popup.asyncConvert.timer&&clearTimeout(popup.asyncConvert.timer),popup.convertPlans=[],popup.log("\u521d\u59cb\u5316-\u6e05\u7a7a-Data"),popup.serverData={},popup.localData.plan_list[t]={}},pullPlan:function(){var t=this;if(!t.active_state)return!1;var e=popup.sa.store.getDistinctId(),p=popup.info.platform,n=popup.info.project;_.wxrequest({url:popup.info.api_base_url+"/sfo/user_popup_configs?distinct_id="+encodeURIComponent(e)+"&app_id="+encodeURIComponent(popup.info.app_id)+"&sdk_version="+encodeURIComponent(popup.lib_version)+"&platform="+encodeURIComponent(p)+"&project="+encodeURIComponent(n)+"&time="+(new Date).getTime(),method:"GET",success:function(e){if(!t.active_state)return!1;var p=e.data;popup.log("\u5f39\u7a97-\u62c9\u53d6\u8ba1\u5212\u6570\u636e\u6210\u529f"),p.popup_test_window&&!_.isEmptyObject(p.popup_test_window)&&t.testRender(p.popup_test_window),_.isObject(p)&&p.server_current_time&&p.popup_plans&&p.min_sdk_version_required&&/\d+\.\d+/.test(p.min_sdk_version_required)&&parseFloat(p.min_sdk_version_required)<=parseFloat(popup.lib_version)?(popup.info.preload_image&&popup.popupEmitter.loadImage(_.matchImage(p.popup_plans)),popup.serverData=p,t.setListenEvent(),t.interval_time=p.config_pull_interval_ms,t.setIntervalTime(t.interval_time)):(popup.log("\u5f39\u7a97-\u8bf7\u6c42\u8fd4\u56de\u7684\u6570\u636e\u9519\u8bef"),popup.serverData={},t.setIntervalTime(t.interval_time))},fail:function(e){if(!t.active_state)return!1;popup.log("\u5f39\u7a97-\u8bf7\u6c42\u62c9\u53d6\u6570\u636e\u9519\u8bef: ",e),t.setIntervalTime(t.interval_time)},complete:function(){popup.sub.ready||popup.sub.isReady()}})},testRender:function(t){var e,p={content:t.content,type:t.popup_type},n=!0,o=_.getUuid()();try{e=JSON.parse(t.content)}catch(t){n=!1}var i={props:{$sf_succeed:!0},plan:{}};if(i.uuid=o,"CUSTOMIZED"===t.popup_type)i.popupTree={},popup.CAMPAIGN_ERROR.onStart?(i.props={$sf_fail_reason:"onStart \u65b9\u6cd5\u672a\u5b9a\u4e49",$sf_succeed:!1},popup.track.popupDisplay(i),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(p,"1004","onStart \u65b9\u6cd5\u672a\u5b9a\u4e49")):t.content?(popup.campaign_listener.onStart(p),popup.track.popupDisplay(i)):(i.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u9519\u8bef",$sf_succeed:!1},popup.track.popupDisplay(i),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(p));else{try{new popup.parseTree(e),i.popupTree=popup.popupTree,i.plan={popup_window_content:t}}catch(t){popup.log("--\u6d4b\u8bd5\u5f39\u7a97\u5c55\u793a-\u6e32\u67d3\u9519\u8bef",t),n=!1}n?(popup.track.popupDisplay(i),popup.CAMPAIGN_ERROR.onStart||popup.campaign_listener.onStart(p),popup.popupEmitter.notify(i)):(i.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u5f02\u5e38",$sf_succeed:!1},popup.track.popupDisplay(i),popup.info.popup_listener.onLoadFailed(void 0,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(p,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"))}},startState:function(){this.active_state=!0,popup.localData=popup.store.getJSONData()||{},this.pullPlan(),this.updateData()},transData:function(t){var e=popup.sa.store.getDistinctId(),p={user_list:{},plan_list:{}};p.user_list[e]=e,p.plan_list[e]=JSON.parse(JSON.stringify(t)),p.plan_list[e].update_time=Date.now(),popup.localData=p,popup.store.saveJSONData()},updateLocalPlans:function(){var t=popup.store.getUserId(),e=Date.now();popup.localData.plan_list[t]&&(popup.localData.plan_list[t].update_time=e),_.each(popup.localData.plan_list,function(t,p){e-t.update_time>=2592e6&&delete popup.localData.plan_list[p]})},updateUserPlans:function(){var t=popup.serverData,e=popup.sa.store.getDistinctId();t.user_id?(popup.localData.user_list[e]=t.user_id,popup.localData.plan_list[t.user_id]||popup.localData.plan_list[e]&&(popup.localData.plan_list[t.user_id]=popup.localData.plan_list[e],delete popup.localData.plan_list[e])):popup.localData.user_list[e]||(popup.localData.user_list[e]=e)}};var IMAGE_MAP={close:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAMAAAAPdrEwAAAAe1BMVEUAAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////NgkbwAAAAKHRSTlMA5if6t/B0UjMSxpAtJB4MBfTr30oY6NjV0r2loZ6XkoaBenFp3UA/LNePaQAAAsxJREFUWMOsltlygzAMRRXMZsAsAZJmX9v6/7+wg1QXpjGxCDkvyWTIQZauDcCgzKLrPtnUSyGW9SbZX6OshDcQh36lH6j8MJ7pTZd6lGX6sr0IP7SDj7CA6chLoBkEFzm14nM1/P/2eGti1RZFq+LmdtwGw7afJ1Ue1dogcGCW4QptqCO2OPe1IbnL0Y7dE23wc2bJgSn44MFTvIMwLeMUXqZGfGKUkp+MPC2dwUjMGhWwUL7pnXRUsdbIIpow84VG1k9Xmf1e5U8Kq/R/68memAPqcggTCQUNc9SdL+iCL5jMd0B1j/RErh3LYrRyLa2po2x8KngJ9Uk5sWUwpZoVvIiiulNLhMwgHDhDED2MEH8X3zCDL4HV/R8lRTOEWYS0KWzt8GEm/mNLihpHKOeqJY6yLqDnbO42F1r9eXCzitMOfkuqfvkXTId6h1phSi5/ncbgneAtnDCAxTAzIn+POhfDFOObzAEsNLu0HXO06a4BCwd89wEk1h2ezdwl0rObvS5nNreHurg/lxKwsNPoHjXrHVhI+lMK3xjvMH4YelYzCSzc8V3zrx9CWtu5MG67eWEdhBSmI+GT7eIZt+Nny7YJ+y8ON9/cF1tWVL7LzTdTi6sSMtw9AE432wwl7u6MzqotMNwcM7Glc/TafRyB4+aa4dhdcoV993EDlptphlt3zZ72TgM8N88MDe3vDQWE5V6tWGaKyAbwqaiA5+aZQeETkk6QFtxuvhlaOkVwwxfgdq/IvHKbocBj6ac5OzYCIASBKGo10n+HBgakMswbaYDgTmX3fzgafhD4G+Hhg1cGXnT4PMFHVayCdVcBXGBu7cKwACOOC2YwTsIQ7KI7LBywJrlyByupK9Kw/lto4VFLAqLdmRwJiBDWwjDOI0QPPhPXRn3yTlyrILND4w7oOw3h5AlTPk5U/ddrZSk4RWW+C9hp2rgru6GiP/678n2UFPV1AAAAAElFTkSuQmCC"};popup.parseTree=function(t){this.img=void 0,this.content=void 0,this.title=void 0,this.button=[],this.image_button=void 0,this.buttonStyle={},this.view={},this.parseView(t.template),this.properties={maskCloseEnabled:t.properties.maskCloseEnabled,maskActionId:t.properties.maskActionId,maskColor:_.getRgba(t.properties.maskColor)},popup.popupTree.properties=this.properties},popup.parseTree.prototype={parseView:function(t){switch(t.type){case"column":case"row":this.getViewProp(t);break;case"image":this.getImg(t);break;case"label":this.getLabel(t);break;case"button":this.getButton(t);break;case"link":this.getLink(t);break;case"image_button":this.getImgButton(t)}this.img&&!_.isEmptyObject(this.img)&&(popup.popupTree.img=this.img),this.title&&!_.isEmptyObject(this.title)&&(popup.popupTree.title=this.title,popup.popupTree.diverseModule=!0),this.content&&!_.isEmptyObject(this.content)&&(popup.popupTree.content=this.content,popup.popupTree.diverseModule=!0),this.image_button&&!_.isEmptyObject(this.image_button)&&(popup.popupTree.image_button=this.image_button),this.buttonStyle&&!_.isEmptyObject(this.buttonStyle)&&(popup.popupTree.buttonStyle=this.buttonStyle),this.boxStyle&&!_.isEmptyObject(this.boxStyle)&&(popup.popupTree.boxStyle=this.boxStyle),this.container&&!_.isEmptyObject(this.container)&&(popup.popupTree.container=this.container),this.button&&!_.isEmptyObject(this.button)&&this.button.length>0&&(popup.popupTree.button=this.button,popup.popupTree.diverseModule=!0),this.view&&!_.isEmptyObject(this.view)&&(popup.popupTree.view=this.view),t.GRADE||(t.GRADE=0,this.view.container=Object.assign({},this.getViewProp(t))),t.subviews&&t.subviews.length>0&&_.each(t.subviews,function(e){e.GRADE=t.GRADE+1,this.parseView(e)},this)},getViewProp:function(t){switch(t.GRADE){case 0:return{style:"width: "+_.getRpx(t.layout.width)+";"};case 1:if(t.subviews.length>0){var e=Object.assign({},{backgroundImage:t.properties.backgroundImage?t.properties.backgroundImage:"",style:this.getStyle(t)}),p='background: url("'+e.backgroundImage+'");background-size: 100% 100%;'+e.style;this.view.content=Object.assign({},{style:p})}break;case 2:t.subviews&&t.subviews.length>0?this.view.button=Object.assign({},{type:t.type}):this.view.padding=Object.assign({},{style:"margin-top: "+_.getRpx(t.layout.margin.top)+";",type:t.type})}},isButtonBranch:function(t){var e=!0,p={image_button:1,link:1,button:1};return _.each(t,function(t,n){p[n]||(e=!1)}),e},getImg:function(t){this.img=_.extend({},this.getAttr(t.properties),this.getAction(t.action)),this.img.style=this.getStyle(t)},getImgButton:function(t){var e={};"close"===t.properties.msgType?t.properties.isHidden||(this.image_button=_.extend({},this.getAction(t.action),this.getAttr(t.properties)),t.layout.align&&(this.image_button.aligin=t.layout.align),this.image_button.style=this.getStyle(t),this.image_button.type=t.type):((e=_.extend({},this.getAction(t.action),this.getAttr(t.properties))).style=this.getStyle(t),e.type=t.type),_.isEmptyObject(e)||this.button.push(e)},getLabel:function(t){"title"===t.properties.msgType?(this.title=_.extend({},this.getAttr(t.properties)),this.title.style=this.getStyle(t)):"content"===t.properties.msgType&&(this.content=_.extend({},this.getAttr(t.properties)),this.content.style=this.getStyle(t))},getButton:function(t){var e={};(e=_.extend({},this.getAction(t.action),this.getAttr(t.properties))).style=this.getStyle(t),e.type=t.type,_.isEmptyObject(e)||this.button.push(e)},getLink:function(t){var e={};(e=_.extend({},this.getAction(t.action),this.getAttr(t.properties))).style=this.getStyle(t),e.type=t.type,_.isEmptyObject(e)||this.button.push(e)},getAttr:function(t){var e={};return t.text?e.innerText=t.text:t.image&&(t.localImageName?(e.src=IMAGE_MAP[t.localImageName],e.useLocalImage=!0):e.src=t.image),e},getAction:function(t){var e={};return t&&t.MINIPROGRAM&&(t=t.MINIPROGRAM[0],e.id=t.id,e.closeable=t.closeable,e.action_type=t.type,e.$sf_close_type=t.$sf_close_type,t.value&&(e.value=t.value),t.path&&(e.path=t.path),t.appid&&(e.appid=t.appid)),e},getStyle:function(t){var e,p={textAlign:"text-align",font:"font-size",backgroundColor:"background-color",borderWidth:function(t){return"border-width: "+t+";border-style: solid;"},borderColor:"border-color",cornerRadius:"border-radius",backgroundImage:function(t){return""},margin:this.boxModel("margin"),padding:this.boxModel("padding"),maxHeight:"max-height",maxWidth:"max-width"},n=["msgType","text","image","name","isHidden","align","localImageName"],o="";return e=_.extend({},t.layout,t.properties),_.each(e,function(t,e){t=_.getRpx(t);var i=p[e];if(n.indexOf(e)>=0)return!1;_.isString(i)?o+=i+":"+_.getRgba(t)+";":_.isFunction(i)?o+=i(t)+";":o+=e+":"+_.getRgba(t)+";"}),o},boxModel:function(t){return function(e){if("object"!=typeof e)return e;var p="";for(var n in e)p+=t+"-"+n+":"+_.getRpx(e[n]);return p}}};var QRCode={1011:1,1012:1,1013:1,1017:1,1047:1,1048:1,1049:1};popup.testSend={getPopupId:function(t){var e=0,p=t.query.scene;if(p){var n=decodeURIComponent(p).split("=");e="sf_test_id"===n[0]&&n[1]?n[1]:0}return e},start:function(t){if(!QRCode[t.scene])return!1;var e=this.getPopupId(t);if(!e)return!1;var p=popup.info.project,n=popup.info.platform,o=popup.sa.store.getDistinctId();_.wxrequest({url:popup.info.api_base_url+"/sfo/popup_windows/"+e+"?distinct_id="+encodeURIComponent(o)+"&app_id="+encodeURIComponent(popup.info.app_id)+"&project="+encodeURIComponent(p)+"&platform="+encodeURIComponent(n)+"&sdk_version="+encodeURIComponent(popup.lib_version)+"&time="+(new Date).getTime(),type:"GET",success:function(t){var e,p=t.data,n={content:p.content,type:p.popup_type},o=!0,i=_.getUuid()();try{e=JSON.parse(p.content)}catch(t){o=!1}var r={props:{$sf_succeed:!0},plan:{}};if(r.uuid=i,popup.popupTree={},"CUSTOMIZED"===p.popup_type)r.popupTree={},popup.CAMPAIGN_ERROR.onStart?(r.props={$sf_fail_reason:"onStart \u65b9\u6cd5\u672a\u5b9a\u4e49",$sf_succeed:!1},popup.track.popupDisplay(r),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(n,"1004","onStart \u65b9\u6cd5\u672a\u5b9a\u4e49")):p.content?(popup.campaign_listener.onStart(n),popup.track.popupDisplay(r)):(r.props={$sf_fail_reason:"\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e",$sf_succeed:!1},popup.track.popupDisplay(r),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(n,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"));else{try{new popup.parseTree(e),r.popupTree=popup.popupTree,r.plan={popup_window_content:p}}catch(t){popup.log("--\u6d4b\u8bd5\u5f39\u7a97-\u89e3\u6790\u9519\u8bef",t),o=!1}o?(popup.track.popupDisplay(r),popup.CAMPAIGN_ERROR.onStart||popup.campaign_listener.onStart(n),popup.popupEmitter.notify(r)):(r.props={$sf_fail_reason:"\u5f39\u7a97\u5185\u5bb9\u5f02\u5e38",$sf_succeed:!1},popup.track.popupDisplay(r),popup.info.popup_listener.onLoadFailed(void 0,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"),popup.CAMPAIGN_ERROR.onFailed||popup.campaign_listener.onFailed(n,"1001","\u9884\u89c8\u4fe1\u606f\u89e3\u6790\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u8ba1\u5212\u914d\u7f6e"))}}})}},popup.track={getPublicProps:function(){return{$sf_lib_version:popup.lib_version,$sf_plan_type:"\u8fd0\u8425\u8ba1\u5212",$sf_channel_service_name:"SENSORS_FOCUS",$sf_channel_category:"POPUP",$sf_platform_tag:popup.info.platform}},removeEmpty:function(t){_.each(t,function(e,p){""!==e&&void 0!==e||delete t[p]})},popupDisplay:function(t){var e=popup.track.getPublicProps(),p=popup.track.getPlanProps(t);_.extend(e,t.props,p),this.removeEmpty(e),popup.sa.track("$PlanPopupDisplay",e)},popupClick:function(t){var e=popup.track.getPublicProps(),p=popup.track.getPlanProps(t),n={type:t.props.$sf_msg_element_action,value:t.props.action_value||"",extra:t.props.action_value||""};try{popup.info.popup_listener.onClick(t.plan.plan_id,n)}catch(t){popup.log("popup_listener.onClick error",t)}delete t.props.action_value,_.extend(e,t.props,p),e.$sf_plan_id||delete e.$sf_plan_id,this.removeEmpty(e),popup.sa.track("$PlanPopupClick",e)},getPlanProps(t){var e={},p=t.popupTree;return e.$sf_msg_id=t.uuid,e.$sf_msg_title=p.title?p.title.innerText:"",e.$sf_msg_content=p.content?p.content.innerText:"",e.$sf_msg_image_url=p.img?p.img.src:"",e.$sf_plan_id=t.plan&&t.plan.plan_id||"",e.$sf_audience_id=t.plan&&t.plan.audience_id||"",t.plan.strategy_id?e.$sf_plan_strategy_id=t.plan.strategy_id:_.isBoolean(t.plan.is_control_group)&&(t.plan.is_control_group?e.$sf_plan_strategy_id=-1:e.$sf_plan_strategy_id=0),e}};export default popup;
\ No newline at end of file
# 神策 uni-app JSSDK 使用文档
## 1. 使用说明
#### 本插件适用于 H5、APP、微信小程序、阿里小程序、百度小程序、头条小程序、小红书小程序进行数据采集。
注:
1. 对于 VUE3 的点击全埋点建议手动触发,默认不支持。
2. APP 需集成 Native 端插件,否则无法进行 APP 端数据采集,具体集成可参考 [神策 uni-app 原生插件](https://ext.dcloud.net.cn/plugin?id=4179)
## 2. 使用方式
### 2.1. 引入及配置方式
#### 2.1.1. 方案一: globalData 全局变量方式
App中设置:
```
// 在 App.vue 或者 main.js 中设置 globalData.sensors
<script> import sensors from '神策 uni-app JS SDK 路径/index.js';
//同意隐私协议后调用进行 SDK 初始化
sensors.init({
server_url:'数据接收地址',
show_log:false,//是否开启日志
name:"sensors",
global_properties:{ // 配置全局属性,所有上报事件属性中均会携带
// property1: 'value1'
},,
autoTrack:{//小程序全埋点配置
appLaunch: true, // 默认为 true,false 则关闭 $MPLaunch 事件采集
appShow: true, // 默认为 true,false 则关闭 $MPShow 事件采集
appHide: true, // 默认为 true,false 则关闭 $MPHide 事件采集
pageShow: true, // 默认为 true,false 则关闭 $MPViewScreen 事件采集
pageShare: true, // 默认为 true,false 则关闭 $MPShare 事件采集
mpClick: false, // 默认为 false,true 则开启 $MPClick 事件采集
mpFavorite: true, // 默认为 true,false 则关闭 $MPAddFavorites 事件采集
pageLeave: false // 默认为 false, true 则开启 $MPPageLeave事件采集
},
app:{// Android & iOS 初始化配置
remote_config_url:"",
flush_interval:15000,//两次数据发送的最小时间间隔,单位毫秒
flush_bulkSize:100,//设置本地缓存日志的最大条目数,最小 50 条, 默认 100 条
flush_network_policy:30, //设置 flush 时网络发送策略
auto_track:0, // 1 应用启动, 2 应用退出,3 应用启动和退出 默认 0
encrypt:false, //是否开启加密
add_channel_callback_event:false,//是否开启渠道事件
javascript_bridge:false, // WebView 打通功能
android:{//Android 特有配置
session_interval_time:30000,
request_network:true,
max_cache_size:32, // 默认 32MB,最小 16MB
mp_process_flush:false,//使用小程序 SDK 时,小程序进程是否可发送数据
},
ios:{//iOS 特有配置
max_cache_size: 10000, //最大缓存条数,默认 10000 条
}
}
});
//弹窗 SDK 初始化,需在 init 之后调用
sensors.popupInit({
// 是否打印 log 日志
show_log: true,
// SFO 地址,由 SF 后端提供,sfo 在线服务地址
api_base_url: '',
enable_popup:true,//初始化后是否允许弹窗,若禁止则在需要弹窗时调用 enablePopup @platform Android
app_id: 'wx16ce2f6e06acd4d5'
});
export default {
globalData:{
sensors:sensors
},
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}
</script>
```
Page中设置
```
// 在 Page 中通过 getApp().globalData.sensors 获取
<script>
var sensors = getApp().globalData.sensors;
</script>
```
#### 2.1.2 方案二: import 方式
App中设置:
```
// 在 App.vue 或者 main.js 中设置
<script> import sensors from '神策 uni-app JS SDK 路径/index.js';
sensors.init({
server_url:'数据接收地址',
show_log:false,//是否开启日志
name:"sensors",
global_properties:{ // 配置全局属性,所有上报事件属性中均会携带
// property1: 'value1'
},
autoTrack:{//小程序全埋点配置
appLaunch: true, // 默认为 true,false 则关闭 $MPLaunch 事件采集
appShow: true, // 默认为 true,false 则关闭 $MPShow 事件采集
appHide: true, // 默认为 true,false 则关闭 $MPHide 事件采集
pageShow: true, // 默认为 true,false 则关闭 $MPViewScreen 事件采集
pageShare: true, // 默认为 true,false 则关闭 $MPShare 事件采集
mpClick: false, // 默认为 false,true 则开启 $MPClick 事件采集
mpFavorite: true, // 默认为 true,false 则关闭 $MPAddFavorites 事件采集
pageLeave: false // 默认为 false, true 则开启 $MPPageLeave事件采集
},
app:{// Android & iOS 初始化配置
remote_config_url:"",
flush_interval:15000,//两次数据发送的最小时间间隔,单位毫秒
flush_bulkSize:100,//设置本地缓存日志的最大条目数,最小 50 条, 默认 100 条
flush_network_policy:30, //设置 flush 时网络发送策略
auto_track:0, // 1 应用启动, 2 应用退出,3 应用启动和退出 默认 0
encrypt:false, //是否开启加密
add_channel_callback_event:false,//是否开启渠道事件
javascript_bridge:false, // WebView 打通功能
android:{//Android 特有配置
session_interval_time:30000,
request_network:true,
max_cache_size:32, // 默认 32MB,最小 16MB
mp_process_flush:false,//使用小程序 SDK 时,小程序进程是否可发送数据
},
ios:{//iOS 特有配置
max_cache_size: 10000, //最大缓存条数,默认 10000 条
}
}
//弹窗 SDK 初始化,需在 init 之后调用
sensors.popupInit({
// 是否打印 log 日志
show_log: true,
// SFO 地址,由 SF 后端提供,sfo 在线服务地址
api_base_url: '',
enable_popup:true,//初始化后是否允许弹窗,若禁止则在需要弹窗时调用 enablePopup @platform Android
app_id: 'wx16ce2f6e06acd4d5'
});
</script>
```
Page中设置:
```
<script> import sensors from '神策 uni-app JS SDK 路径/index.js'; </script>
```
#### 2.1.3 其他方式
这里介绍了两种使用全局变量的方式,其他方式也可以参考 uni-app 的文档 https://ask.dcloud.net.cn/article/35021 。
## 2.2. API
### init
方法说明:设置和修改相关配置
适用平台:APP、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ---------- | -------- |
| init | object | 相关配置项 | 是 |
**代码示例**:
```
sensors.init({
server_url:'数据接收地址',
show_log:false,//是否开启日志
name:"sensors",
global_properties:{ // 配置全局属性,所有上报事件属性中均会携带
// property1: 'value1'
},
autoTrack:{//小程序全埋点配置
appLaunch: true, // 默认为 true,false 则关闭 $MPLaunch 事件采集
appShow: true, // 默认为 true,false 则关闭 $MPShow 事件采集
appHide: true, // 默认为 true,false 则关闭 $MPHide 事件采集
pageShow: true, // 默认为 true,false 则关闭 $MPViewScreen 事件采集
pageShare: true, // 默认为 true,false 则关闭 $MPShare 事件采集
mpClick: false, // 默认为 false,true 则开启 $MPClick 事件采集
mpFavorite: true, // 默认为 true,false 则关闭 $MPAddFavorites 事件采集
pageLeave: false // 默认为 false, true 则开启 $MPPageLeave事件采集
},
app:{//Android & iOS 特殊配置
remote_config_url:"",
flush_interval:1000,
flush_bulkSize:100,
flush_network_policy:30,设置 flush 时网络发送策略
auto_track:0, // 1 应用启动, 2 应用退出,3 应用启动和退出 默认 0
encrypt:false, //是否开启加密
add_channel_callback_event:false,//是否开启渠道事件
javascript_bridge:false, // WebView 打通功能
android:{
session_interval_time:30000,
request_network:true,
max_cache_size:32, // 默认 32MB,最小 16MB
mp_process_flush:false,//使用小程序 SDK 时,小程序进程是否可发送数据
},
ios:{
max_cache_size: 10000, //最大缓存条数,默认 10000 条
}
}
```
### track
方法说明:代码埋点方法,调用该接口采集自定义事件
适用平台:APP、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| --------- | -------- | -------------------------- | -------- |
| eventName | String | 事件名称 | 是 |
| para | Object | 自定义属性 | 否 |
| callback | Function | 事件发送成功回调 仅支持 H5 | 否 |
**代码示例**:
```
sensors.track("eventName",{key : "value"});
```
### getAppFlushInterval
方法说明:获取两次数据发送的最小时间间隔,单位毫秒
适用平台:Android、iOS
返回类型:number
### getAppFlushBulkSize
方法说明:获取本地缓存日志的最大条目数
适用平台:Android、iOS
返回类型:number
### getAppSessionIntervalTime
方法说明:获取 Session 时长
适用平台:Android
返回类型:number
### getDistinctID
方法说明:获取当前用户的 distinctId
适用平台:Andorid、iOS、H5、小程序
返回类型:string
### identify
方法说明:设置自定义匿名 ID
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ------- | -------- |
| id | String | 匿名 ID | 是 |
### getAnonymousID
方法说明:获取当前用户的匿名 ID
适用平台:Andorid、iOS、H5、小程序
返回类型:string
### login
方法说明:登录,设置当前用户的登录 ID,触发用户关联事件
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ------- | -------- |
| id | String | 登录 ID | 是 |
### logout
方法说明:注销,清空当前用户的登录 ID
适用平台:Andorid、iOS、H5、小程序
### bind
方法说明:用于多个用户 ID 关联时调用,第一个参数从[详细的预置 id key 列表](https://manual.sensorsdata.cn/sa/latest/id-key-87163331.html)中获取,第二个参数为对应的关联用户 ID。 调用接口后,对应的 key 和 value 会缓存在本地,后续采集的事件,均包含缓存的 ID 信息。
适用平台:Andorid、iOS、H5、微信小程序 、支付宝小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ----- | ------ | ------- | -------- |
| name | String | id 键名 | 是 |
| value | String | id 值 | 是 |
### unbind
方法说明:用于多个用户 ID 取消关联时调用,第一个参数为取消关联的 key,第二个参数为对应的取消关联用户 ID。 调用接口后,会发送相关的解绑事件,同时会将本地缓存的 ID 信息中,对应的 key-value 清除(若存在)。
适用平台:Andorid、iOS、H5、微信小程序 、支付宝小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ----- | ------ | ------- | -------- |
| name | String | id 键名 | 是 |
| value | String | id 值 | 是 |
### loginWithKey
方法说明:用户登录时调用,第一个参数从[详细的预置 id key 列表](https://manual.sensorsdata.cn/sa/latest/id-key-87163331.html)中获取,第二个参数为对应的具体用户 ID。 调用接口后,对应的 key 和 value 会缓存在本地,后续采集的事件,均包含缓存的 ID 信息。
适用平台:Andorid、iOS、H5、微信小程序 、支付宝小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---------- | ------ | ------- | -------- |
| loginIDKey | String | id 键名 | 是 |
| loginId | String | id 值 | 是 |
### resetAnonymousIdentity
方法说明:重置 ID-Mapping 3.0 匿名 id,只有在未登录情况下可以使用。
适用平台:Andorid、iOS、H5、微信小程序
| 参数 | 类型 | 说明 | 是否必选 |
| -------- | ------ | -------------- | -------- |
| identity | String | 新的匿名 Id 值 | 否 |
### getIdentities
方法说明:获取 ID-Mapping 3.0 功能下已绑定的业务 ID 列表。
适用平台:Andorid、iOS、H5、微信小程序
### bindOpenid
方法说明:多用户 ID 关联微信用户 Openid 时调用,参数为对应的关联用户 Openid。(v1.18.3 版本以上支持)。 调用接口后,对应的 key 和 value 会缓存在本地,后续采集的事件,均包含缓存的 ID 信息。 微信小程序 SDK 提供了 bindOpenid 接口将匿名 ID 设置为 OpenID。
> ⚠️此接口只有满足下面两个条件才能支持!不满足下面条件的可以使用 identify('openid', true) 接口; bindOpenid 仅在 ID-Mapping 3.0 支持,使用前请确认 SA 后端是否支持 ID-Mapping 3.0; bindOpenid 微信小程序 SDK 需要在 v1.18.3 版本上才支持!
适用平台:微信小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ------ | ------ | --------- | -------- |
| openid | String | openid 值 | 是 |
### unbindOpenid
方法说明:多用户 ID 取消关联微信用户 Openid 时调用,参数为对应的关联用户 Openid。( v1.18.3 版本以上支持)。 调用接口后,会发送相关的解绑事件,同时会将本地缓存的 ID 信息中,对应的 key-value 清除(若存在)。
适用平台:微信小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ------ | ------ | --------- | -------- |
| openid | String | openid 值 | 是 |
### bindUnionid
方法说明:多用户 ID 关联微信用户 Unionid 时调用,参数为对应的关联用户 Unionid。(v1.18.3 版本以上支持。 调用接口后,对应的 key 和 value 会缓存在本地,后续采集的事件,均包含缓存的 ID 信息。
适用平台:微信小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ------- | ------ | ---------- | -------- |
| unionid | String | unionid 值 | 是 |
### unbindUnionid
方法说明:多用户 ID 取消关联微信用户 Unionid 时调用,参数为对应的关联用户 Unionid。(v1.18.3 版本以上支持)。 调用接口后,会发送相关的解绑事件,同时会将本地缓存的 ID 信息中,对应的 key-value 清除(若存在)。
适用平台:微信小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ------- | ------ | ---------- | -------- |
| unionid | String | unionid 值 | 是 |
### trackAppInstall
方法说明:记录 $AppInstall 事件,用于在 App 首次启动时追踪渠道来源,并设置追踪渠道事件的属性
适用平台:Andorid、iOS
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ------------------ | -------- |
| para | Object | 激活事件自定义属性 | 否 |
### appFlush
方法说明:将所有本地缓存的日志发送到 SA
适用平台:Andorid、iOS
### register
方法说明:注册所有事件都有的公共属性
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ------------ | -------- |
| para | Object | 全局公共属性 | 是 |
**代码示例**:
```
sensors.register({key1:"value1",key2 : "value2",});
```
**注意:** H5 的在页面生命周期内 小程序是在 App 生命周期内 App 是永久的
### unRegister
方法说明:删除某些事件公共属性
适用平台:Andorid、iOS
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | ---------------- | -------- |
| name | string | 需删除的属性名称 | 是 |
**代码示例**:
```
sensors.unRegister("key1");
```
### clearRegister
方法说明:删除所有事件公共属性
适用平台:Andorid、iOS
### setProfile
方法说明:设置用户属性
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | -------- | -------- |
| para | Object | 用户属性 | 是 |
**代码示例**:
```
sensors.setProfile({key1:"value1",key2:"value2"});
```
### setOnceProfile
方法说明:首次设置用户属性,如果之前存在,则忽略,否则,新创建
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | -------- | -------- |
| para | Object | 用户属性 | 是 |
**代码示例**:
```
sensors.setOnceProfile({key1:"value1",key2:"value2"});
```
### incrementProfile
方法说明:给一个或多个数值类型的 Profile 增加一个数值。只能对数值型属性进行操作,若该属性未设置,则添加属性并设置默认值为 0
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | -------------------- | ------------ | -------- |
| para | Object[value:number] | 增加数值属性 | 是 |
**代码示例**:
```
sensors.incrementProfile({key1:2,key2:2});
```
### appendProfile
方法说明:给一个列表类型的用户属性增加一个元素
适用平台:Andorid、iOS、H5、小程序
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ----------------------------------------- | ------------ | -------- |
| para | Object{key:[value: array<string> string]} | 增加数值属性 | 是 |
**代码示例**:
```
appendProfile({fruit:["苹果","西瓜"]})
appendProfile({fruit:"西瓜"})
appendProfile({fruit1:["苹果","西瓜"],fruit2:["葡萄]})
```
### unsetProfile
方法说明:删除用户的一个用户属性
适用平台:Andorid、iOS、H5
| 参数 | 类型 | 说明 | 是否必选 |
| ---- | ------ | -------- | -------- |
| name | string | 属性名称 | 是 |
### deleteProfile
方法说明:删除用户所有用户属性
适用平台:Andorid、iOS、H5
### popupClose
方法说明:设置弹窗按钮关闭回调 适用平台:Andorid、iOS、H5
| 参数 | 类型 | 说明 | 是否必选 |
| -------- | ------ | ------------------------------------------------ | -------- |
| plan_id | string | plan_id 计划ID | 否 |
| valueObj | object | cvalueObj 弹窗内容对象(在 sf 中配置的弹窗内容) | 否 |
代码示例:
```
注意 sensors 需要在 main.js 设置全局
/** 对弹窗点击事件,绑定事件处理函数
* @param {string} plan_id 计划ID
* @param {object} valueObj 弹窗内容对象(在 sf 中配置的弹窗内容)
*/
sensors.popupClose(function (plan_id, valueObj) {
console.log('plan_id: ', plan_id, ' valueObj: ', valueObj);
});
```
### popupLoadSuccess
方法说明:设置弹窗加载成功回调 适用平台:Andorid、iOS、H5
代码示例:
```
注意 sensors 需要在 main.js 设置全局
/**
* @param {string} plan_id 计划ID
* @param {object} valueObj 弹窗内容对象(在 sf 中配置的弹窗内容)
*/
sensors.popupLoadSuccess(function (data) {
console.log('加载弹窗成功: ', data);
});
```
### popLoadFailed
方法说明:设置弹窗加载失败回调 适用平台:Andorid、iOS、H5
| 参数 | 类型 | 说明 | 是否必选 |
| -------- | ------ | -------------------------------------- | -------- |
| valueObj | object | 弹窗内容对象(在 sf 中配置的弹窗内容) | 否 |
| code | string | code 错误码 | 否 |
| message | string | 错误信息 | 否 |
代码示例:
```
注意 sensors 需要在 main.js 设置全局
/**
* @param {object} valueObj 弹窗内容对象(在 sf 中配置的弹窗内容)
* @param {string} code 错误码
* @param {message} 错误信息
*/
sensors.popLoadFailed(function (valueObj,code,message) {
console.log('失败回调: ');
});
```
### popupClick
方法说明:设置弹窗点击回调 适用平台:Andorid、iOS、H5
| 参数 | 类型 | 说明 | 是否必选 |
| -------- | ------ | -------------------------------------- | -------- |
| valueObj | object | 弹窗内容对象(在 sf 中配置的弹窗内容) | 否 |
代码示例:
```
注意 sensors 需要在 main.js 设置全局
/**
* @param {object} valueObj 弹窗内容对象(在 sf 中配置的弹窗内容)
*/
sensors.popupClick(function (valueObj) {
console.log('click:',valueObj);
});
```
注意:以上方法,可以直接调用,不支持的端调用后无效,控制台会打印日志。
export default function get_enableVue3MpClick(sensors) {
var sa = sensors.instance;
var _ = sa._;
return function enableVue3MpClick() {
// #ifdef VUE3
// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-JD || MP-KUAISHOU || MP-QQ || MP-LARK
var platform;
// #ifdef MP-WEIXIN
platform = wx
// #endif
// #ifdef MP-BAIDU
platform = swan
// #endif
// #ifdef MP-ALIPAY
platform = my
// #endif
// #ifdef MP-TOUTIAO
platform = tt
// #endif
// #ifdef MP-JD
platform = jd
// #endif
// #ifdef MP-KUAISHOU
platform = ks
// #endif
// #ifdef MP-QQ
platform = qq
// #endif
// #ifdef MP-LARK
platform = tt
// #endif
var oldCreatePage = platform.createPage;
if (_.isFunction(oldCreatePage)) {
platform.createPage = function (options) {
mutateOptions(options)
return oldCreatePage.call(platform, options);
}
}
var oldCreateComponent = platform.createComponent;
if (_.isFunction(oldCreateComponent)) {
platform.createComponent = function (options) {
mutateOptions(options)
return oldCreateComponent.call(platform, options);
}
}
function mutateOptions(options) {
if (!_.isObject(options)) return;
if (_.isFunction(options.render)) {
var oldRender = options.render;
options.render = function (_ctx, _cache, $props, $setup, $data, $options) {
var instance = _ctx && _ctx.$scope;
var bindingConfig = oldRender.call(options, _ctx, _cache, $props, $setup, $data, $options);
addMPClick(instance, bindingConfig);
return bindingConfig;
}
} else if (_.isFunction(options.setup)) {
var oldSetup = options.setup;
options.setup = function (_props, _defines) {
var oldRender = oldSetup.call(options, _props, _defines);
return function render(_ctx, _cache) {
var instance = _ctx && _ctx.$scope;
var bindingConfig = oldRender.call(options, _ctx, _cache);
addMPClick(instance, bindingConfig);
return bindingConfig;
}
}
}
}
function addMPClick(instance, bindingConfig) {
if (_.isObject(instance) && _.isObject(bindingConfig)) {
var propKeys = getPropKeys(bindingConfig, [], false);
propKeys.forEach(function (propKey) {
var invoker = instance[propKey];
if (_.isFunction(invoker) && _.isFunction(invoker.value) && !invoker.value.__MPClickFlag) {
var oldValue = invoker.value;
invoker.value = function (event) {
if (sa.para.autoTrack && sa.para.autoTrack.mpClick) {
clickTrack(event);
}
return oldValue.call(instance, event)
}
invoker.value.__MPClickFlag = true;
}
});
}
}
function getPropKeys(config, dest, inner = false) {
if (!_.isArray(dest)) dest = [];
if (_.isArray(config)) {
config.forEach(function (item) {
getPropKeys(item, dest, true);
});
} else if (_.isObject(config)) {
Object.values(config).forEach(function (item) {
if (!!item) {
if (_.isString(item) && item.startsWith('e') && (!inner || item.includes('_'))) {
dest.push(item);
} else if (_.isArray(item)) {
getPropKeys(item, dest, true);
}
}
});
}
return dest;
}
function clickTrack(events) {
if (_.isUndefined(events)) events = {};
var prop = {};
var event_prop = _.isObject(events.event_prop) ? events.event_prop : {};
var type = events['type'];
var current_target = events.currentTarget || {};
var dataset = current_target.dataset || {};
prop['$element_id'] = current_target.id;
prop['$element_type'] = dataset['type'];
prop['$element_content'] = dataset['content'];
prop['$element_name'] = dataset['name'];
prop['$url_path'] = _.getCurrentPath();
if (type && isClick(type)) {
if (sa.para.preset_events && sa.para.preset_events.collect_element && sa.para.preset_events.collect_element(events) === false) {
return false;
}
prop = _.extend(prop, event_prop);
sensors.track('$MPClick', prop);
}
}
function isClick(type) {
var mp_taps = {
tap: 1,
longpress: 1,
longtap: 1
};
return !!mp_taps[type];
}
// #endif
// #endif
}
}
\ No newline at end of file
var sensors=getApp().sensors;Component({options:{multipleSlots:!0},lifetimes:{attached:function(){sensors.popupEmitter.attached()}},properties:{},data:{flag:!0,isShow:!1,template:{},image_list:[],plan_obj:{}},methods:{loadImage:function(t){if(t&&t.length>0){var e=[].concat(this.image_list,t);this.setData({image_list:e})}},handle:function(t){return!!this.data.flag&&(t.popupTree||t.popupTree.properties?(this.setData({plan_obj:t}),this.setData({template:t.popupTree}),void(this.data.flag&&(this.setData({isShow:!0}),this.showPopup()))):(this.popupFail(1001),!1))},popupFail(t){var e={$sf_succeed:!1};e.fail_code=t,e.$sf_fail_reason={1000:"图片加载失败",1001:"预览信息解析失败,请检查计划配置",2000:"对照组"}[t];var a=this.data.plan_obj;a.props=e,2e3!==t&&sensors.events.emit("popup_load_fail",a),sensors.events.emit("popup_end",this.data.plan_obj)},clickMask:function(){if(this.data.template.properties.maskCloseEnabled){var t={};t.$sf_msg_action_id=this.data.template.properties.maskActionId,t.$sf_close_type="POPUP_CLOSE_MASK",t.$sf_msg_element_type="mask";var e=this.data.plan_obj;e.props=t,sensors.events.emit("popup_click",e),this.hidePopup()}},hidePopup:function(){this.setData({flag:!0}),this.setData({isShow:!1}),sensors.events.emit("popup_end",this.data.plan_obj)},showPopup(){this.setData({flag:!1});var t=this.data.plan_obj;sensors.events.emit("popup_display",t)},tapContent(){console.log("点击了弹窗窗体")},topCloseButton(){var t=this.data.template.image_button;t.$sf_close_type||(t.$sf_close_type="POPUP_CLOSE_TOPRIGHT"),this.popupCLick(t)},buttomCloseButton(){var t=this.data.template.image_button;t.$sf_close_type||(t.$sf_close_type="POPUP_CLOSE_BOTTOM"),this.popupCLick(t)},clickImage(){var t=this.data.template.img;t.$sf_close_type||(t.$sf_close_type="POPUP_CLOSE_BUTTON"),this.popupCLick(t)},buttonFirst(){var t=this.data.template.button[0];"close"!==t.action_type||t.$sf_close_type||(t.$sf_close_type="POPUP_CLOSE_BUTTON"),this.popupCLick(t)},buttonSecond(){var t=this.data.template.button[1];"close"!==t.action_type||t.$sf_close_type||(t.$sf_close_type="POPUP_CLOSE_BUTTON"),this.popupCLick(t)},popupCLick(t){var e={};switch(e.$sf_msg_element_type=t.type,e.$sf_msg_element_content=t.innerText,e.$sf_msg_action_id=t.id,e.action_value=t.value,e.$sf_msg_element_action=t.action_type,e.$sf_close_type=t.$sf_close_type,t.action_type){case"copy":wx.setClipboardData({data:t.value,success(t){console.log("复制文本成功")}});break;case"navigateTo":var a={path:t.path};this.navigatePage(a);break;case"navigateToMiniProgram":a={path:t.path,appid:t.appid};this.navigateMini(a)}var s=this.data.plan_obj;s.props=e,sensors.events.emit("popup_click",s),t.closeable&&this.hidePopup()},navigatePage(t){wx.navigateTo({url:t.path,success:function(){console.log("navigate success")},fail:function(t){console.log("navigate fail: ",t)}})},navigateMini(t){wx.navigateToMiniProgram({appId:t.appid,path:t.path,success(){console.log("navigate success")},fail(t){console.log("navigate fail: ",t)}})}}});
\ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
<view
catchtap="clickMask"
class="wx-popup"
hidden="{{flag}}"
style="background: {{template.properties.maskColor}}"
>
<view wx:if="{{isShow}}" class='popup-container' catchtap="tapContent">
<view
wx:if="{{template.image_button.aligin === 'right'}}" class="close_btn-right">
<image
class="close_btn"
catchtap="topCloseButton"
src="{{template.image_button.src}}">
</image>
</view>
<image wx:if="{{!template.diverseModule && template.img}}"
class ='content-image'
style="{{template.img.style}}"
catchtap="clickImage"
src="{{template.img.src?template.img.src:''}}"
>
</image>
<view
wx:if="{{template.diverseModule}}"
class="popup-content"
style="{{template.view.content.style}}"
>
<image
wx:if="{{template.img && template.img.src}}"
class ='content-image'
style="{{template.img.style}}"
src="{{template.img.src}}">
</image>
<view wx:if="{{template.view.padding}}" style="{{template.view.padding.style}}"></view>
<text wx:if="{{template.title}}"
class="content-title"
style="{{template.title.style}}">{{template.title.innerText}}
</text>
<text wx:if="{{template.content}}"
class="content-content"
style="{{template.content.style}}">{{template.content.innerText}}
</text>
<!-- 按钮模块 -->
<view
wx:if="{{template.button && template.button.length > 0}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn_column' : 'popup-btn_row'}} "
style="{{template.view.button.style}}">
<view wx:if="{{template.button[0].type === 'button'}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn-button_column' : 'popup-btn-button_row'}}"
style="{{template.button[0].style}}"
catchtap="buttonFirst">{{template.button[0].innerText}}
</view>
<image wx:if="{{template.button[0].type === 'image_button'}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn-img_column' : 'popup-btn-img_row'}}"
style="{{template.button[0].style}}"
src="{{template.button[0].src}}"
catchtap="buttonFirst">
</image>
<view wx:if="{{template.button[0].type === 'link'}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn-linker_column' : 'popup-btn-linker_row'}}"
style="{{template.button[0].style}}" catchtap="buttonFirst">{{template.button[0].innerText}}
</view>
<view wx:if="{{template.button[1].type === 'button'}}"
class="{{template.view.button.type === 'column' ? 'popup-btn-button_column popup-btn-second_column' : 'popup-btn-button_row popup-btn-second_row'}}"
style="{{template.button[1].style}}"
catchtap='buttonSecond'>{{template.button[1].innerText}}
</view>
<image wx:if="{{template.button[1].type === 'image_button'}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn-img_column popup-btn-second_column' : 'popup-btn-img_row popup-btn-second_row'}}"
style="{{template.button[1].style}}"
src="{{template.button[1].src}}"
catchtap='buttonSecond'>
</image>
<view wx:if="{{template.button[1].type === 'link'}}"
class="{{ template.view.button.type === 'column' ? 'popup-btn-linker_column' : 'popup-btn-linker_row'}}"
style="{{template.button[1].style}}"
catchtap='buttonSecond'>{{template.button[1].innerText}}
</view>
</view>
</view>
<view
wx:if="{{template.image_button.aligin === 'center'}}" class="close_btn-center">
<image
catchtap="buttomCloseButton"
class="close_btn"
src="{{template.image_button.src}}">
</image>
</view>
</view>
<view wx:for="{{image_list}}" wx:key="index" hidden="{{true}}">
<image src="{{image_list[index]}}"></image>
</view>
</view>
/* popup-component.wxss */
.wx-popup {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10000;
}
.close_btn {
width: 50rpx;
height: 50rpx;
}
.popup-container {
position: fixed;
left: 50%;
top: 46%;
transform: translate(-50%, -50%);
}
.popup-content {
margin-top: 20rpx;
box-sizing: border-box;
overflow: hidden;
}
.content-image {
width: 620rpx;
height: 440rpx;
}
.content-title {
display: block;
margin: 0 auto;
text-align: center;
font-size: 48rpx;
line-height: 150%;
color: rgba(0, 0, 0, 1);
word-break: break-all;
overflow: auto;
}
.content-content {
display: block;
width: 580rpx;
margin: 0 auto;
padding: 0;
font-size: 28rpx;
line-height: 150%;
text-align: center;
color: rgba(74, 74, 74, 1);
word-break: break-all;
overflow: auto;
}
.popup-btn {
display: flex;
width: 580rpx;
align-items: center;
margin: 32rpx auto 0;
flex-direction: column;
text-overflow: clip;
white-space: nowrap;
overflow: hidden;
}
.popup-btn_column {
display: flex;
width: 590rpx;
margin: 26rpx auto 0;
justify-content: center;
align-items: center;
flex-direction: column;
overflow: hidden;
}
.popup-btn_row {
display: flex;
justify-content: center;
width: 580rpx;
margin: 26rpx auto 0;
align-items: center;
flex-direction: row;
text-overflow: clip;
letter-spacing: 2rpx;
overflow: hidden;
}
.popup-btn-second_column {
margin-top: 20rpx;
}
.popup-btn-second_row {
margin-left: 20rpx;
}
.popup-btn-button_row {
width: 280rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
font-size: 36rpx;
border-width: 2rpx;
color: rgba(255, 255, 255, 1);
border-radius: 40rpx;
border-color: rgba(2, 203, 148, 1);
flex-grow: 1;
overflow: hidden;
}
.popup-btn-button_column {
width: 590rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
font-size: 36rpx;
border-width: 2rpx;
color: rgba(255, 255, 255, 1);
border-radius: 40rpx;
border-color: rgba(2, 203, 148, 1);
overflow: hidden;
}
.popup-btn-img_row {
width: 280rpx;
height: 80rpx;
}
.popup-btn-img_column {
width: 580rpx;
height: 80rpx;
}
.popup-btn-linker_row {
display: block;
width: 280rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
color: rgba(74, 144, 226, 1);
text-decoration: underline;
letter-spacing: 2rpx;
overflow: hidden;
}
.popup-btn-linker_column {
width: 580rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
color: rgba(74, 144, 226, 1);
text-decoration: underline;
letter-spacing: 2rpx;
overflow: hidden;
}
.close_btn-right {
display: flex;
justify-content: flex-end;
}
.close_btn-center {
margin-top: 20rpx;
display: flex;
justify-content: center;
}
......@@ -2,6 +2,35 @@ import App from "./App";
// import apiRequest from "@/api/request.js";
import * as Pinia from 'pinia';
import sensors, {
enableVue3MpClick,
} from "./js_sdk/Sensorsdata-UniPlugin-JS/index";
const SENSORS_URL = "https://sensors.feihe.com/sa?project=XMH_Content";
sensors.setPara({
name: "sensors",
server_url: SENSORS_URL,
show_log: true,
autoTrack: {
appLaunch: true, // 默认为 true,false 则关闭 $MPLaunch 事件采集
appShow: true, // 默认为 true,false 则关闭 $MPShow 事件采集
appHide: true, // 默认为 true,false 则关闭 $MPHide 事件采集
pageShow: true, // 默认为 true,false 则关闭 $MPViewScreen 事件采集
pageShare: true, // 默认为 true,false 则关闭 $MPShare 事件采集
mpClick: true, // 默认为 false,true 则开启 $MPClick 事件采集
mpFavorite: true, // 默认为 true,false 则关闭 $MPAddFavorites 事件采集
pageLeave: true, // 默认为 false, true 则开启 $MPPageLeave事件采集
},
});
enableVue3MpClick();
sensors.init();
// const BASE_URL = 'https://duiba.oss-cn-hangzhou.aliyuncs.com/fh/';
// const BASE_URL = 'https://firmus-member-test-1253290912.cos.ap-beijing.myqcloud.com/xmh-mini-program/';
const BASE_URL = 'https://course.feihe.com/momclub-picture/';
......@@ -12,9 +41,16 @@ import "./uni.promisify.adaptor";
// 全局挂载后使用
// Vue.prototype.$api = apiRequest.api;
Vue.prototype.$baseUrl = BASE_URL;
Vue.prototype.$sensors = sensors;
Vue.config.productionTip = false;
App.mpType = "app";
......@@ -32,6 +68,7 @@ export function createApp() {
app.use(Pinia.createPinia());
// app.config.globalProperties.$api = apiRequest.api;
app.config.globalProperties.$baseUrl = BASE_URL;
app.config.globalProperties.$sensors = sensors;
return {
app,
Pinia
......
......@@ -111,16 +111,14 @@
<!-- 普通弹窗 -->
<uni-popup :is-mask-click="false" :safe-area="false" ref="popup" background-color="#fff"
border-radius="48rpx">
<view v-if="this.popupIndex !== 3" class="popup-content">
<view v-if="this.popupIndex !== 3 && this.qrInfoList && this.qrInfoList[this.popupIndex]" class="popup-content">
<image class="btnclose" @tap="closePop" :src="$baseUrl + 'homepage/btnclose.png'"></image>
<view class="title">
{{ this.qrInfoList[this.popupIndex].title }}
{{ this.qrInfoList[this.popupIndex]?.title || '' }}
</view>
<rich-text class="desc" :nodes="this.qrInfoList[this.popupIndex].desc">
</rich-text>
<image :show-menu-by-longpress="true" class="qrcode" :src="$baseUrl + this.qrInfoList[this.popupIndex].qrUrl"></image>
<image @tap="downloadHandler($baseUrl + this.qrInfoList[this.popupIndex].qrUrl)" class="btndownload"
<rich-text class="desc" :nodes="this.qrInfoList[this.popupIndex]?.desc || ''"></rich-text>
<image :show-menu-by-longpress="true" class="qrcode" :src="$baseUrl + (this.qrInfoList[this.popupIndex]?.qrUrl || '')"></image>
<image @tap="downloadHandler($baseUrl + (this.qrInfoList[this.popupIndex]?.qrUrl || ''))" class="btndownload"
:src="$baseUrl + 'homepage/btn_download.png'"></image>
</view>
<view v-else class="popup-content" style="height: 977rpx;">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment