@datarangers/sdk-javascript 0.0.6 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/plugin/ab.js CHANGED
@@ -1 +1,930 @@
1
- "use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},e.apply(this,arguments)},t="__rangers_ab_style__";var n,i,r={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},o="https://lf3-data.volccdn.com/obj/data-static/log-sdk/collect/visual-ab-core.js",a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(e){var t=function(){try{return!!Symbol.iterator}catch(e){return!1}}(),n=function(e){var n={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t&&(n[Symbol.iterator]=function(){return n}),n},i=function(e){return encodeURIComponent(e).replace(/%20/g,"+")},r=function(e){return decodeURIComponent(String(e).replace(/\+/g," "))};(function(){try{var t=e.URLSearchParams;return"a=1"===new t("?a=1").toString()&&"function"==typeof t.prototype.set&&"function"==typeof t.prototype.entries}catch(t){return!1}})()||function(){var r=function e(t){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var n=typeof t;if("undefined"===n);else if("string"===n)""!==t&&this._fromString(t);else if(t instanceof e){var i=this;t.forEach((function(e,t){i.append(t,e)}))}else{if(null===t||"object"!==n)throw new TypeError("Unsupported input's type for URLSearchParams");if("[object Array]"===Object.prototype.toString.call(t))for(var r=0;r<t.length;r++){var o=t[r];if("[object Array]"!==Object.prototype.toString.call(o)&&2===o.length)throw new TypeError("Expected [string, any] as entry at index "+r+" of URLSearchParams's input");this.append(o[0],o[1])}else for(var a in t)t.hasOwnProperty(a)&&this.append(a,t[a])}},o=r.prototype;o.append=function(e,t){e in this._entries?this._entries[e].push(String(t)):this._entries[e]=[String(t)]},o.delete=function(e){delete this._entries[e]},o.get=function(e){return e in this._entries?this._entries[e][0]:null},o.getAll=function(e){return e in this._entries?this._entries[e].slice(0):[]},o.has=function(e){return e in this._entries},o.set=function(e,t){this._entries[e]=[String(t)]},o.forEach=function(e,t){var n;for(var i in this._entries)if(this._entries.hasOwnProperty(i)){n=this._entries[i];for(var r=0;r<n.length;r++)e.call(t,n[r],i,this)}},o.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),n(e)},o.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),n(e)},o.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),n(e)},t&&(o[Symbol.iterator]=o.entries),o.toString=function(){var e=[];return this.forEach((function(t,n){e.push(i(n)+"="+i(t))})),e.join("&")},e.URLSearchParams=r}();var o=e.URLSearchParams.prototype;"function"!=typeof o.sort&&(o.sort=function(){var e=this,t=[];this.forEach((function(n,i){t.push([i,n]),e._entries||e.delete(i)})),t.sort((function(e,t){return e[0]<t[0]?-1:e[0]>t[0]?1:0})),e._entries&&(e._entries={});for(var n=0;n<t.length;n++)this.append(t[n][0],t[n][1])}),"function"!=typeof o._fromString&&Object.defineProperty(o,"_fromString",{enumerable:!1,configurable:!1,writable:!1,value:function(e){if(this._entries)this._entries={};else{var t=[];this.forEach((function(e,n){t.push(n)}));for(var n=0;n<t.length;n++)this.delete(t[n])}var i,o=(e=e.replace(/^\?/,"")).split("&");for(n=0;n<o.length;n++)i=o[n].split("="),this.append(r(i[0]),i.length>1?r(i[1]):"")}})}(void 0!==a?a:"undefined"!=typeof window?window:"undefined"!=typeof self?self:a),function(e){if(function(){try{var t=new e.URL("b","http://a");return t.pathname="c d","http://a/c%20d"===t.href&&t.searchParams}catch(t){return!1}}()||function(){var t=e.URL,n=function t(n,i){"string"!=typeof n&&(n=String(n)),i&&"string"!=typeof i&&(i=String(i));var r,o=document;if(i&&(void 0===e.location||i!==e.location.href)){i=i.toLowerCase(),(r=(o=document.implementation.createHTMLDocument("")).createElement("base")).href=i,o.head.appendChild(r);try{if(0!==r.href.indexOf(i))throw new Error(r.href)}catch(t){throw new Error("URL unable to set base "+i+" due to "+t)}}var a=o.createElement("a");a.href=n,r&&(o.body.appendChild(a),a.href=a.href);var s=o.createElement("input");if(s.type="url",s.value=n,":"===a.protocol||!/:/.test(a.href)||!s.checkValidity()&&!i)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:a});var c=new e.URLSearchParams(this.search),l=!0,h=!0,u=this;["append","delete","set"].forEach((function(e){var t=c[e];c[e]=function(){t.apply(c,arguments),l&&(h=!1,u.search=c.toString(),h=!0)}})),Object.defineProperty(this,"searchParams",{value:c,enumerable:!0});var f=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==f&&(f=this.search,h&&(l=!1,this.searchParams._fromString(this.search),l=!0))}})},i=n.prototype;["hash","host","hostname","port","protocol"].forEach((function(e){!function(e){Object.defineProperty(i,e,{get:function(){return this._anchorElement[e]},set:function(t){this._anchorElement[e]=t},enumerable:!0})}(e)})),Object.defineProperty(i,"search",{get:function(){return this._anchorElement.search},set:function(e){this._anchorElement.search=e,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(i,{toString:{get:function(){var e=this;return function(){return e.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(e){this._anchorElement.href=e,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(e){this._anchorElement.pathname=e},enumerable:!0},origin:{get:function(){var e={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],t=this._anchorElement.port!=e&&""!==this._anchorElement.port;return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(t?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(e){},enumerable:!0},username:{get:function(){return""},set:function(e){},enumerable:!0}}),n.createObjectURL=function(e){return t.createObjectURL.apply(t,arguments)},n.revokeObjectURL=function(e){return t.revokeObjectURL.apply(t,arguments)},e.URL=n}(),void 0!==e.location&&!("origin"in e.location)){var t=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:t,enumerable:!0})}catch(n){setInterval((function(){e.location.origin=t()}),100)}}}(void 0!==a?a:"undefined"!=typeof window?window:"undefined"!=typeof self?self:a),function(e){e.Init="init",e.Config="config",e.Start="start",e.Ready="ready",e.TokenComplete="token-complete",e.TokenStorage="token-storage",e.TokenFetch="token-fetch",e.TokenError="token-error",e.ConfigUuid="config-uuid",e.ConfigWebId="config-webid",e.ConfigDomain="config-domain",e.CustomWebId="custom-webid",e.AnonymousId="anonymous-id",e.TokenChange="token-change",e.TokenReset="token-reset",e.ConfigTransform="config-transform",e.EnvTransform="env-transform",e.SessionReset="session-reset",e.SessionResetTime="session-reset-time",e.Event="event",e.Events="events",e.EventNow="event-now",e.CleanEvents="clean-events",e.BeconEvent="becon-event",e.SubmitBefore="submit-before",e.SubmitScuess="submit-scuess",e.SubmitAfter="submit-after",e.SubmitError="submit-error",e.SubmitVerifyH="submit-verify-h5",e.Stay="stay",e.ResetStay="reset-stay",e.StayReady="stay-ready",e.SetStay="set-stay",e.RouteChange="route-change",e.RouteReady="route-ready",e.Ab="ab",e.AbVar="ab-var",e.AbAllVars="ab-all-vars",e.AbConfig="ab-config",e.AbExternalVersion="ab-external-version",e.AbVersionChangeOn="ab-version-change-on",e.AbVersionChangeOff="ab-version-change-off",e.AbOpenLayer="ab-open-layer",e.AbCloseLayer="ab-close-layer",e.AbReady="ab-ready",e.AbComplete="ab-complete",e.AbTimeout="ab-timeout",e.Profile="profile",e.ProfileSet="profile-set",e.ProfileSetOnce="profile-set-once",e.ProfileUnset="profile-unset",e.ProfileIncrement="profile-increment",e.ProfileAppend="profile-append",e.ProfileClear="profile-clear",e.TrackDuration="track-duration",e.TrackDurationStart="track-duration-start",e.TrackDurationEnd="track-duration-end",e.TrackDurationPause="track-duration-pause",e.TrackDurationResume="tracl-duration-resume",e.Autotrack="autotrack",e.AutotrackReady="autotrack-ready",e.CepReady="cep-ready",e.TracerReady="tracer-ready"}(n||(n={})),function(e){e.DEBUGGER_MESSAGE="debugger-message",e.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",e.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",e.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",e.DEBUGGER_MESSAGE_EVENT="debugger-message-event",e.DEVTOOL_WEB_READY="devtool-web-ready"}(i||(i={}));Date.now(),Number((""+Math.random()).slice(2,8));var s=function(e){return function(e,t,n){if("string"==typeof e&&"number"==typeof t&&"number"==typeof n){var i,r=[];n=n<=25?n:n%25;var o=String.fromCharCode(n+97);i=e.split(o);for(var a=0;a<i.length;a++){var s=parseInt(i[a],n);s=1*s^t;var c=String.fromCharCode(s);r.push(c)}return r.join("")}}(e,64,25)},c=function(e,t,n){var i=document.createElement("script");i.src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i)},l=function(e){var t=document.createElement("a");return t.href=e,t},h={},u=[];function f(e,t,n,i){var r=e&&e.source||window.opener||window.parent,o=e&&e.origin||i||"*",a={type:t,payload:n};r.postMessage(JSON.stringify(a),o)}function p(e,t){h[e]=h[e]||[],h[e].push(t)}function d(e){if(u.some((function(e){return"*"===e}))||u.some((function(t){return e.origin===t}))){var t=e.data;if("string"==typeof e.data)try{t=JSON.parse(e.data)}catch(e){t=void 0}if(!t)return;var n=t.type,i=t.payload;h[n]&&h[n].forEach((function(t){"function"==typeof t&&t(e,i)}))}}var m="",v=!1;function b(e){var t=e.event,n=e.editorUrl;e.collectInstance,e.fromSession,v||(v=!0,c(n,(function(){f(t,"abEditorScriptloadSuccess")}),(function(){t&&f(t,"abEditorScriptloadError"),v=!1})))}function g(t,n){var i;window.TEAVisualEditor=window.TEAVisualEditor||{},(i=["*"]).length&&i.forEach((function(e){u.push(e)}));var r,a="";!function(t,n){var i=e({},t);i.filter&&delete i.filter,"object"==typeof i.autotrack&&i.autotrack.collect_url&&delete i.autotrack.collect_url,(window.opener||window.parent).postMessage({type:"tea:sdk:info",config:i,version:n},"*"),window.addEventListener("message",d,!1)}(n,"0.0.6");var s="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach((function(e){"script"===e.initiatorType&&e.name&&-1!==e.name.indexOf("collect")&&(s=e.name)})),s||document.currentScript&&(s=document.currentScript.src),s&&(r=s.split("/"))&&r.length)){a="https:/";for(var l=2;l<r.length&&l!==r.length-1;l++)a=a+"/"+r[l];a+="/visual-ab-core"}}catch(e){}p("tea:openVisualABEditor",(function(e){var i=e.data;if("string"==typeof e.data)try{i=JSON.parse(e.data)}catch(e){i=void 0}if(i){var r=i.lang;if(i.appId!==n.app_id)return f(e,"appIdError"),void console.error("abtest appid is not belong the page appid please check");var s=i.version;if(s)m=a?""+a+(s?"."+s:".1.0.1")+".js?query="+Date.now():o+"?query="+Date.now();else m=o+"?query="+Date.now();window.TEAVisualEditor.lang=r,window.TEAVisualEditor.__ab_domin=n.channel_domain||"",b({event:e,editorUrl:m,collectInstance:t})}}))}var y;!function(e){e[e.Var=0]="Var",e[e.All=1]="All"}(y||(y={}));var _=function(){function n(){this.fetchStatus="no",this.refreshFetchStatus="complete",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data=null,this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[]}return n.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=t.enable_multilink,o=t.ab_channel_domain,a=t.enable_ab_visual,c=t.ab_cross,l=t.ab_cookie_domain,h=t.disable_ab_reset,u=o||s(r[t.channel||"cn"]),f=e.adapters,p=f.storage,d=f.fetch;this.cacheStorgae=new p(!1),this.fetch=d,this.enable_multilink=i,this.enable_ab_visual=a,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=c,this.ab_cookie_domain=l||"",this.fetchUrl=u+"/service/2/abtest_config/",this.reportUrl=""+e.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500;var m=this.collect.Types;this.types=m,this.collect.on(m.TokenChange,(function(e){h||"uuid"===e.type&&n.readyStatus&&(n.clearCache(),n.fetchAB())})),this.collect.on(m.TokenReset,(function(){h||n.readyStatus&&(n.clearCache(),n.fetchAB())})),this.collect.on(m.AbVar,(function(e){var t=e.name,i=e.defaultValue,r=e.callback;n.getVar(t,i,r)})),this.collect.on(m.AbAllVars,(function(e){n.getAllVars(e)})),this.collect.on(m.AbConfig,(function(e){var t=e.params,i=e.callback;n.getABconfig(t,i)})),this.collect.on(m.AbExternalVersion,(function(e){n.setExternalAbVersion(e)})),this.collect.on(m.AbOpenLayer,(function(){n.openOverlayer()})),this.collect.on(m.AbCloseLayer,(function(){n.closeOverlayer()})),this.collect.on(m.AbVersionChangeOn,(function(e){n.changeListener.set(e,e)})),this.collect.on(m.AbVersionChangeOff,(function(e){n.changeListener.get(e)&&n.changeListener.delete(e)})),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(this.fetchAB(),this.readyStatus=!0),this.collect.emit(m.AbReady)}},n.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(e){n[e].length&&n[e].forEach((function(n){t.collect.hook.emit(e,n)}))};for(var r in n)i(r)}},n.prototype.loadMode=function(){var e,t,n=function(){try{return JSON.parse(atob(window.name))||void 0}catch(e){return}}(),i="";if(n){var r=n.scenario,o=n.href;r?(this.editMode=!0,i=r):!o||-1===o.indexOf("datatester")&&-1===o.indexOf("visual-editor")||(this.editMode=!0,i="visual-editor")}this.enable_ab_visual&&(g(this.collect,this.config),"visual-editor"===i)?this.collect.destoryInstace():this.enable_multilink&&(e=this.collect,t=this.config,window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=t.app_id,p("tea:openTesterEventInspector",(function(t){var n=t.data;if("string"==typeof t.data)try{n=JSON.parse(t.data)}catch(e){n=void 0}if(n){var i=n.referrer,r=n.lang,o=n.appId;window.TEAVisualEditor.__editor_ajax_domain=i||"",window.TEAVisualEditor.__ab_appId=o||"",window.TEAVisualEditor.lang=r||"",b({event:t,editorUrl:"https://lf3-data.volccdn.com/obj/data-static/log-sdk/collect/tester-event-inspector.js?query="+Date.now(),collectInstance:e})}})))},n.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,n=e.ab_ext_version,i=e.ab_version_multilink,r=e.data,o=this.checkFromUrl();o?this.mulilinkVersions.push(o):this.mulilinkVersions=i||[],this.extVersions=n||[],this.versions=t||[],this.data=r;var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions)),this.configVersions(a.join(","))},n.prototype.checkFromUrl=function(){var e=function(e){var t={};try{var n=l(e).search;(n=n.slice(1)).split("&").forEach((function(e){var n,i,r=e.split("=");r.length&&(n=r[0],i=r[1]);try{t[n]=decodeURIComponent(void 0===i?"":i)}catch(e){t[n]=i}}))}catch(e){}return t}(window.location.href);return e&&e.vid?e.vid:""},n.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach((function(t){"function"==typeof t&&t(e)}))},n.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},n.prototype.getVar=function(e,t,n){if(!e)throw new Error("variable must not be empty");if(void 0===t)throw new Error("variable no default value");if("function"!=typeof n)throw new Error("callback must be a function");var i={name:e,defaultValue:t,callback:n,type:y.Var};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealVar(i,e):this.callbacks.push(i)},n.prototype.getRealVar=function(e,t){var n=e.name,r=e.defaultValue,o=e.callback,a=this.data;if(a){if(null!=(c=a[n])&&"[object Object]"==Object.prototype.toString.call(c)){var s=a[n].vid;return"$ab_url"===t?this.mulilinkVersions.includes(s)||this.mulilinkVersions.push(s):this.versions.includes(s)||this.versions.push(s),this.updateVersions(),this.fechEvent(s,t,r),o(a[n].val),void this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 曝光了实验"+n,level:"info",time:Date.now(),data:a[n]})}var c;this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getVar",level:"info",time:Date.now(),data:r}),o(r)}else o(r)},n.prototype.getAllVars=function(e){if("function"!=typeof e)throw new Error("callback must be a function");var t={callback:e,type:y.All};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealAllVars(t):this.callbacks.push(t)},n.prototype.getRealAllVars=function(e){(0,e.callback)(this.data?JSON.parse(JSON.stringify(this.data)):{}),this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getAllVars",level:"info",time:Date.now(),data:this.data})},n.prototype.fechEvent=function(e,t,n){try{if(this.config.disable_track_event)return;if(!e)return;var r=this.collect.configManager.get(),o=r.header,a=r.user,s=this.getABCache();if(s&&s.uuid&&s.uuid!==a.user_unique_id)return;var c={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:"$ab_url"===t?n:window.location.href}),local_time_ms:Date.now()};o.custom=JSON.stringify(o.custom);var l={events:[c],user:a,header:o};"$ab_url"===t&&window.navigator.sendBeacon?window.navigator.sendBeacon(this.reportUrl,JSON.stringify([l])):this.reportExposure(l)}catch(e){this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:e.message})}},n.prototype.reportExposure=function(e){var t=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report():this.reportTimeout=setTimeout((function(){t.report(),clearTimeout(t.reportTimeout)}),this.ab_batch_time)},n.prototype.report=function(){var e=this,t=this.collect.cryptoData(this.exposureCache);this.fetch(this.reportUrl,t,1e5,!1,(function(){}),(function(){}),"","POST",this.config.enable_encryption,this.config.encryption_header),this.exposureCache.forEach((function(t){e.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:[t],code:200,status:"success"})})),this.exposureCache=[]},n.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},n.prototype.getABconfig=function(e,t){var n=Object.keys(e);n&&n.length&&this.collect.configManager.set(e),this.fetchAB(t)},n.prototype.get=function(e){if(this.ab_cross){var t=this.cacheStorgae.getCookie(e,this.ab_cookie_domain);return t?JSON.parse(t):null}return this.cacheStorgae.getItem(e)},n.prototype.set=function(e,t){this.ab_cross?this.cacheStorgae.setCookie(e,t,2592e6,this.ab_cookie_domain):this.cacheStorgae.setItem(e,t),this.collect.configManager.setAbCache(t)},n.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,Date.now()-t.timestamp>=2592e6?(this.cacheStorgae.removeItem(this.abKey),null):e?t[e]:t},n.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},n.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},n.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},n.prototype.openOverlayer=function(e){var n=this;if(function(){if(!document.getElementById(t)){var e="body { opacity: 0 !important; }",n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.id=t,i.type="text/css",i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),n.appendChild(i)}}(),e)var i=setTimeout((function(){n.closeOverlayer(),clearTimeout(i)}),e)},n.prototype.closeOverlayer=function(){var e;(e=document.getElementById(t))&&e.parentElement.removeChild(e)},n.prototype.fetchComplete=function(e,t){var n=this;if(e&&"[object Object]"==Object.prototype.toString.call(e)){this.data=e,this.setAbCache(t);var i=[];Object.keys(e).forEach((function(t){var n=e[t].vid;n&&i.push(n)})),this.versions=this.versions.filter((function(e){return i.includes(e)}));var r=e.$ab_url,o=e.$ab_modification;if(o&&o.val&&this.enable_ab_visual){if(this.collect.destroyInstance)return;this.getVar("$ab_modification",window.location.href,(function(){var e;e=o.val,window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.__ab_config=e,c("https://lf3-data.volccdn.com/obj/data-static/log-sdk/collect/visual-ab-loader.js?query="+Date.now(),(function(){console.log("load visual render success")}),(function(){console.log("load visual render fail")})),n.closeOverlayer()}))}else if(r&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter((function(e){return i.includes(e)}));var a=r.val,s=r.vid;a&&s&&this.getVar("$ab_url",a,(function(){n.editMode||(a!==window.location.href?setTimeout((function(){if(!n.collect.destroyInstance){var e=""+a;e=-1===e.indexOf("http")?"https://"+e:e;var t=l(e).host;try{var i=new URL(e);t!==location.host?i.searchParams.append("vid",s):window.history.replaceState("","",e),window.location.href=i.href}catch(t){window.location.href=e}}}),100):n.closeOverlayer())}))}this.updateVersions()}else this.closeOverlayer();this.callbacks.forEach((function(e){return n[e.type===y.Var?"getRealVar":"getRealAllVars"](e,"")})),this.callbacks=[]},n.prototype.fetchAB=function(t){var n=this,r=this.collect.configManager.get(),o=r.header,a=r.user;this.config.enable_anonymousid&&delete a.web_id;var s=a.user_unique_id,c={header:e({aid:this.config.app_id},a||{},o||{},{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"SDK 发起AB实验请求",level:"info",logType:"fetch",time:Date.now(),data:c});var l=this.collect.cryptoData(c);this.fetch(this.fetchUrl,l,this.config.ab_timeout||3e3,!1,(function(e){n.fetchStatus="complete",n.refreshFetchStatus="complete";var r=e.data;"success"===e.message?(n.fetchComplete(r,s),t&&t(r)):(n.fetchComplete(null,s),t&&t(null)),n.collect.emit(n.types.AbComplete,r),n.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求成功",level:"info",logType:"fetch",time:Date.now(),data:r})}),(function(){n.fetchStatus="complete",n.refreshFetchStatus="complete",n.fetchComplete(null,s),t&&t(null),n.collect.emit(n.types.AbTimeout),n.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求网络异常",level:"error",logType:"fetch",time:Date.now()})}),"","",this.config.enable_encryption,this.config.encryption_header)},n.prototype.filterUrl=function(e){try{var t="";-1!==e.indexOf("&multilink=true")?t="&multilink=true[\0-ÿ]*":-1!==e.indexOf("?multilink=true")&&(t="\\?multilink=true[\0-ÿ]*");var n=new RegExp(t,"g");e=e.replace(n,"")}catch(e){}return e},n}();module.exports=_;
1
+ 'use strict';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+
18
+ var __assign = function() {
19
+ __assign = Object.assign || function __assign(t) {
20
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
21
+ s = arguments[i];
22
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+
29
+ // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
30
+ var STYLE_ID = '__rangers_ab_style__';
31
+
32
+ function openOverlayer() {
33
+ if (document.getElementById(STYLE_ID)) {
34
+ return;
35
+ }
36
+
37
+ var css = 'body { opacity: 0 !important; }';
38
+ var head = document.head || document.getElementsByTagName('head')[0];
39
+ var style = document.createElement('style');
40
+ style.id = STYLE_ID;
41
+ style.type = 'text/css';
42
+
43
+ if (style.styleSheet) {
44
+ style.styleSheet.cssText = css;
45
+ } else {
46
+ style.appendChild(document.createTextNode(css));
47
+ }
48
+
49
+ head.appendChild(style);
50
+ }
51
+
52
+ function closeOverlayer() {
53
+ var style = document.getElementById(STYLE_ID);
54
+
55
+ if (style) {
56
+ style.parentElement.removeChild(style);
57
+ }
58
+ }
59
+
60
+ // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
61
+ var AB_DOMAINS = {
62
+ cn: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
63
+ va: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
64
+ sg: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k'
65
+ };
66
+
67
+ // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
68
+ var Types;
69
+
70
+ (function (Types) {
71
+ Types["Init"] = "init";
72
+ Types["Config"] = "config";
73
+ Types["Start"] = "start";
74
+ Types["Ready"] = "ready";
75
+ Types["TokenComplete"] = "token-complete";
76
+ Types["TokenStorage"] = "token-storage";
77
+ Types["TokenFetch"] = "token-fetch";
78
+ Types["TokenError"] = "token-error";
79
+ Types["ConfigUuid"] = "config-uuid";
80
+ Types["ConfigWebId"] = "config-webid";
81
+ Types["ConfigDomain"] = "config-domain";
82
+ Types["CustomWebId"] = "custom-webid";
83
+ Types["AnonymousId"] = "anonymous-id";
84
+ Types["TokenChange"] = "token-change";
85
+ Types["TokenReset"] = "token-reset";
86
+ Types["ConfigTransform"] = "config-transform";
87
+ Types["EnvTransform"] = "env-transform";
88
+ Types["SessionReset"] = "session-reset";
89
+ Types["SessionResetTime"] = "session-reset-time";
90
+ Types["Event"] = "event";
91
+ Types["Events"] = "events";
92
+ Types["EventNow"] = "event-now";
93
+ Types["CleanEvents"] = "clean-events";
94
+ Types["BeconEvent"] = "becon-event";
95
+ Types["SubmitBefore"] = "submit-before";
96
+ Types["SubmitScuess"] = "submit-scuess";
97
+ Types["SubmitAfter"] = "submit-after";
98
+ Types["SubmitError"] = "submit-error";
99
+ Types["SubmitVerifyH"] = "submit-verify-h5";
100
+ Types["Stay"] = "stay";
101
+ Types["ResetStay"] = "reset-stay";
102
+ Types["StayReady"] = "stay-ready";
103
+ Types["SetStay"] = "set-stay";
104
+ Types["RouteChange"] = "route-change";
105
+ Types["RouteReady"] = "route-ready";
106
+ Types["Ab"] = "ab";
107
+ Types["AbVar"] = "ab-var";
108
+ Types["AbAllVars"] = "ab-all-vars";
109
+ Types["AbConfig"] = "ab-config";
110
+ Types["AbExternalVersion"] = "ab-external-version";
111
+ Types["AbVersionChangeOn"] = "ab-version-change-on";
112
+ Types["AbVersionChangeOff"] = "ab-version-change-off";
113
+ Types["AbOpenLayer"] = "ab-open-layer";
114
+ Types["AbCloseLayer"] = "ab-close-layer";
115
+ Types["AbReady"] = "ab-ready";
116
+ Types["AbComplete"] = "ab-complete";
117
+ Types["AbTimeout"] = "ab-timeout";
118
+ Types["Profile"] = "profile";
119
+ Types["ProfileSet"] = "profile-set";
120
+ Types["ProfileSetOnce"] = "profile-set-once";
121
+ Types["ProfileUnset"] = "profile-unset";
122
+ Types["ProfileIncrement"] = "profile-increment";
123
+ Types["ProfileAppend"] = "profile-append";
124
+ Types["ProfileClear"] = "profile-clear";
125
+ Types["TrackDuration"] = "track-duration";
126
+ Types["TrackDurationStart"] = "track-duration-start";
127
+ Types["TrackDurationEnd"] = "track-duration-end";
128
+ Types["TrackDurationPause"] = "track-duration-pause";
129
+ Types["TrackDurationResume"] = "tracl-duration-resume";
130
+ Types["Autotrack"] = "autotrack";
131
+ Types["AutotrackReady"] = "autotrack-ready";
132
+ Types["CepReady"] = "cep-ready";
133
+ Types["TracerReady"] = "tracer-ready";
134
+ })(Types || (Types = {}));
135
+
136
+ var DebuggerMesssge;
137
+
138
+ (function (DebuggerMesssge) {
139
+ DebuggerMesssge["DEBUGGER_MESSAGE"] = "debugger-message";
140
+ DebuggerMesssge["DEBUGGER_MESSAGE_SDK"] = "debugger-message-sdk";
141
+ DebuggerMesssge["DEBUGGER_MESSAGE_FETCH"] = "debugger-message-fetch";
142
+ DebuggerMesssge["DEBUGGER_MESSAGE_FETCH_RESULT"] = "debugger-message-fetch-result";
143
+ DebuggerMesssge["DEBUGGER_MESSAGE_EVENT"] = "debugger-message-event";
144
+ DebuggerMesssge["DEVTOOL_WEB_READY"] = "devtool-web-ready";
145
+ })(DebuggerMesssge || (DebuggerMesssge = {}));
146
+
147
+ // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
148
+ // @ts-nocheck
149
+ // @ts-nocheck
150
+ var isObject = function isObject(obj) {
151
+ return obj != null && Object.prototype.toString.call(obj) == '[object Object]';
152
+ };
153
+ (function () {
154
+ var lastEventId = +Date.now() + Number(("" + Math.random()).slice(2, 8));
155
+ return function () {
156
+ lastEventId += 1;
157
+ return lastEventId;
158
+ };
159
+ })();
160
+ /* eslint-disable no-param-reassign */
161
+
162
+ var decrypto = function decrypto(str, xor, hex) {
163
+ if (typeof str !== 'string' || typeof xor !== 'number' || typeof hex !== 'number') {
164
+ return;
165
+ }
166
+
167
+ var strCharList = [];
168
+ var resultList = [];
169
+ hex = hex <= 25 ? hex : hex % 25;
170
+ var splitStr = String.fromCharCode(hex + 97);
171
+ strCharList = str.split(splitStr);
172
+
173
+ for (var i = 0; i < strCharList.length; i++) {
174
+ var charCode = parseInt(strCharList[i], hex);
175
+ charCode = charCode * 1 ^ xor;
176
+ var strChar = String.fromCharCode(charCode);
177
+ resultList.push(strChar);
178
+ }
179
+
180
+ var resultStr = resultList.join('');
181
+ return resultStr;
182
+ };
183
+ var decodeUrl = function decodeUrl(string) {
184
+ return decrypto(string, 64, 25);
185
+ };
186
+ var parseURL = function parseURL(url) {
187
+ var a = document.createElement('a');
188
+ a.href = url;
189
+ return a;
190
+ };
191
+ var parseUrlQuery = function parseUrlQuery(url) {
192
+ var queryObj = {};
193
+
194
+ try {
195
+ var queryString = parseURL(url).search;
196
+ queryString = queryString.slice(1);
197
+ queryString.split('&').forEach(function (keyValue) {
198
+ var _keyValue = keyValue.split('=');
199
+
200
+ var key;
201
+ var value;
202
+
203
+ if (_keyValue.length) {
204
+ key = _keyValue[0];
205
+ value = _keyValue[1];
206
+ }
207
+
208
+ try {
209
+ queryObj[key] = decodeURIComponent(typeof value === 'undefined' ? '' : value);
210
+ } catch (e) {
211
+ queryObj[key] = value;
212
+ }
213
+ });
214
+ } catch (e) {}
215
+
216
+ return queryObj;
217
+ };
218
+
219
+ var CallbackType;
220
+
221
+ (function (CallbackType) {
222
+ CallbackType[CallbackType["Var"] = 0] = "Var";
223
+ CallbackType[CallbackType["All"] = 1] = "All";
224
+ })(CallbackType || (CallbackType = {}));
225
+
226
+ var STORAGE_EXPRIRE = 1 * 30 * 24 * 60 * 60 * 1000;
227
+ var API = '/service/2/abtest_config/';
228
+
229
+ var Ab =
230
+ /** @class */
231
+ function () {
232
+ function Ab() {
233
+ this.fetchStatus = 'no';
234
+ this.refreshFetchStatus = 'complete';
235
+ this.versions = [];
236
+ this.extVersions = [];
237
+ this.mulilinkVersions = [];
238
+ this.enable_multilink = false;
239
+ this.enable_ab_visual = false;
240
+ this.editMode = false;
241
+ this.callbacks = [];
242
+ this.data = null;
243
+ this.changeListener = new Map();
244
+ this.readyStatus = false;
245
+ this.exposureCache = [];
246
+ }
247
+
248
+ Ab.prototype.apply = function (collect, config) {
249
+ var _this = this;
250
+
251
+ this.collect = collect;
252
+ this.config = config;
253
+ if (!this.config.enable_ab_test) return;
254
+ var enable_multilink = config.enable_multilink,
255
+ ab_channel_domain = config.ab_channel_domain,
256
+ enable_ab_visual = config.enable_ab_visual,
257
+ ab_cross = config.ab_cross,
258
+ ab_cookie_domain = config.ab_cookie_domain,
259
+ disable_ab_reset = config.disable_ab_reset;
260
+ var abDomain = ab_channel_domain || decodeUrl(AB_DOMAINS[config.channel || 'cn']);
261
+ var _a = collect.adapters,
262
+ storage = _a.storage,
263
+ fetch = _a.fetch;
264
+ this.cacheStorgae = new storage(false);
265
+ this.fetch = fetch;
266
+ this.enable_multilink = enable_multilink;
267
+ this.enable_ab_visual = enable_ab_visual;
268
+ this.abKey = "__tea_sdk_ab_version_" + config.app_id;
269
+ this.ab_cross = ab_cross;
270
+ this.ab_cookie_domain = ab_cookie_domain || '';
271
+ this.fetchUrl = "" + abDomain + API;
272
+ this.reportUrl = "" + collect.configManager.getUrl('event');
273
+ this.exposureLimit = config.exposure_limit || 20;
274
+ this.ab_batch_time = config.ab_batch_time || 500;
275
+ var Types = this.collect.Types;
276
+ this.types = Types;
277
+ this.collect.on(Types.TokenChange, function (tokenInfo) {
278
+ if (disable_ab_reset) return;
279
+ if (tokenInfo.type !== 'uuid') return;
280
+ if (!_this.readyStatus) return;
281
+
282
+ _this.clearCache();
283
+
284
+ _this.fetchAB();
285
+ });
286
+ this.collect.on(Types.TokenReset, function () {
287
+ if (disable_ab_reset) return;
288
+ if (!_this.readyStatus) return;
289
+
290
+ _this.clearCache();
291
+
292
+ _this.fetchAB();
293
+ });
294
+ this.collect.on(Types.AbVar, function (_a) {
295
+ var name = _a.name,
296
+ defaultValue = _a.defaultValue,
297
+ callback = _a.callback;
298
+
299
+ _this.getVar(name, defaultValue, callback);
300
+ });
301
+ this.collect.on(Types.AbAllVars, function (callback) {
302
+ _this.getAllVars(callback);
303
+ });
304
+ this.collect.on(Types.AbConfig, function (_a) {
305
+ var params = _a.params,
306
+ callback = _a.callback;
307
+
308
+ _this.getABconfig(params, callback);
309
+ });
310
+ this.collect.on(Types.AbExternalVersion, function (vids) {
311
+ _this.setExternalAbVersion(vids);
312
+ });
313
+ this.collect.on(Types.AbOpenLayer, function () {
314
+ _this.openOverlayer();
315
+ });
316
+ this.collect.on(Types.AbCloseLayer, function () {
317
+ _this.closeOverlayer();
318
+ });
319
+ this.collect.on(Types.AbVersionChangeOn, function (cb) {
320
+ _this.changeListener.set(cb, cb);
321
+ });
322
+ this.collect.on(Types.AbVersionChangeOff, function (cb) {
323
+ if (_this.changeListener.get(cb)) {
324
+ _this.changeListener["delete"](cb);
325
+ }
326
+ });
327
+ this.loadMode();
328
+ (this.enable_ab_visual || this.enable_multilink) && this.openOverlayer(this.config.multilink_timeout_ms || 500);
329
+ this.checkLocal();
330
+ this.ready('ab');
331
+
332
+ if (!this.readyStatus) {
333
+ this.fetchAB();
334
+ this.readyStatus = true;
335
+ }
336
+
337
+ this.collect.emit(Types.AbReady);
338
+ };
339
+
340
+ Ab.prototype.ready = function (name) {
341
+ var _this = this;
342
+
343
+ this.collect.set(name);
344
+
345
+ if (this.collect.hook._hooksCache.hasOwnProperty(name)) {
346
+ var emits = this.collect.hook._hooksCache[name];
347
+ if (!Object.keys(emits).length) return;
348
+
349
+ var _loop_1 = function _loop_1(key) {
350
+ if (emits[key].length) {
351
+ emits[key].forEach(function (item) {
352
+ _this.collect.hook.emit(key, item);
353
+ });
354
+ }
355
+ };
356
+
357
+ for (var key in emits) {
358
+ _loop_1(key);
359
+ }
360
+ }
361
+ };
362
+
363
+ Ab.prototype.loadMode = function () {// const name = getIframeUrl();
364
+ // let editMode = '';
365
+ // if (name) {
366
+ // const { scenario, href } = name;
367
+ // if (scenario) {
368
+ // this.editMode = true;
369
+ // editMode = scenario;
370
+ // } else if (
371
+ // href &&
372
+ // (href.indexOf('datatester') !== -1 ||
373
+ // href.indexOf('visual-editor') !== -1)
374
+ // ) {
375
+ // this.editMode = true;
376
+ // editMode = 'visual-editor';
377
+ // }
378
+ // }
379
+ // if (this.enable_ab_visual) {
380
+ // readyToLoadEditor(this.collect, this.config);
381
+ // if (editMode === 'visual-editor') {
382
+ // this.collect.destoryInstace();
383
+ // return;
384
+ // }
385
+ // }
386
+ // if (this.enable_multilink) {
387
+ // loadMuiltlink(this.collect, this.config);
388
+ // }
389
+ };
390
+
391
+ Ab.prototype.checkLocal = function () {
392
+ var _a = this.getABCache(),
393
+ ab_version = _a.ab_version,
394
+ ab_ext_version = _a.ab_ext_version,
395
+ ab_version_multilink = _a.ab_version_multilink,
396
+ data = _a.data;
397
+
398
+ var mulilinkUrlVid = this.checkFromUrl();
399
+
400
+ if (mulilinkUrlVid) {
401
+ this.mulilinkVersions.push(mulilinkUrlVid);
402
+ } else {
403
+ this.mulilinkVersions = ab_version_multilink || [];
404
+ }
405
+
406
+ this.extVersions = ab_ext_version || [];
407
+ this.versions = ab_version || [];
408
+ this.data = data;
409
+ var vids = this.versions.concat(this.extVersions);
410
+
411
+ if (this.enable_multilink) {
412
+ vids = vids.concat(this.mulilinkVersions);
413
+ }
414
+
415
+ this.configVersions(vids.join(','));
416
+ };
417
+
418
+ Ab.prototype.checkFromUrl = function () {
419
+ var urlQueryObj = parseUrlQuery(window.location.href);
420
+
421
+ if (urlQueryObj && urlQueryObj['vid']) {
422
+ return urlQueryObj['vid'];
423
+ }
424
+
425
+ return '';
426
+ };
427
+
428
+ Ab.prototype.updateVersions = function () {
429
+ var versions = this.extVersions.length ? this.versions.concat(this.extVersions) : this.versions;
430
+
431
+ if (this.enable_multilink) {
432
+ versions = versions.concat(this.mulilinkVersions);
433
+ }
434
+
435
+ this.configVersions(versions.join(','));
436
+ this.updateABCache();
437
+ this.changeListener.size > 0 && this.changeListener.forEach(function (listener) {
438
+ if (typeof listener === 'function') {
439
+ listener(versions);
440
+ }
441
+ });
442
+ };
443
+
444
+ Ab.prototype.configVersions = function (vids) {
445
+ this.collect.configManager.setAbVersion(vids);
446
+ };
447
+
448
+ Ab.prototype.getVar = function (name, defaultValue, callback) {
449
+ if (!name) {
450
+ throw new Error('variable must not be empty');
451
+ }
452
+
453
+ if (defaultValue === undefined) {
454
+ throw new Error('variable no default value');
455
+ }
456
+
457
+ if (typeof callback !== 'function') {
458
+ throw new Error('callback must be a function');
459
+ }
460
+
461
+ var callbackObj = {
462
+ name: name,
463
+ defaultValue: defaultValue,
464
+ callback: callback,
465
+ type: CallbackType.Var
466
+ };
467
+
468
+ if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
469
+ this.getRealVar(callbackObj, name);
470
+ } else {
471
+ this.callbacks.push(callbackObj);
472
+ }
473
+ };
474
+
475
+ Ab.prototype.getRealVar = function (item, key) {
476
+ var name = item.name,
477
+ defaultValue = item.defaultValue,
478
+ callback = item.callback;
479
+ var data = this.data;
480
+
481
+ if (!data) {
482
+ callback(defaultValue);
483
+ return;
484
+ }
485
+
486
+ if (isObject(data[name])) {
487
+ var vid = data[name].vid;
488
+
489
+ if (key === '$ab_url') {
490
+ if (!this.mulilinkVersions.includes(vid)) {
491
+ this.mulilinkVersions.push(vid);
492
+ }
493
+ } else {
494
+ if (!this.versions.includes(vid)) {
495
+ this.versions.push(vid);
496
+ }
497
+ }
498
+
499
+ this.updateVersions();
500
+ this.fechEvent(vid, key, defaultValue);
501
+ callback(data[name].val);
502
+ this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
503
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
504
+ secType: 'AB',
505
+ info: "SDK \u66DD\u5149\u4E86\u5B9E\u9A8C" + name,
506
+ level: 'info',
507
+ time: Date.now(),
508
+ data: data[name]
509
+ });
510
+ return;
511
+ }
512
+
513
+ this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
514
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
515
+ secType: 'AB',
516
+ info: 'SDK 调用getVar',
517
+ level: 'info',
518
+ time: Date.now(),
519
+ data: defaultValue
520
+ });
521
+ callback(defaultValue);
522
+ };
523
+
524
+ Ab.prototype.getAllVars = function (callback) {
525
+ if (typeof callback !== 'function') {
526
+ throw new Error('callback must be a function');
527
+ }
528
+
529
+ var callbackObj = {
530
+ callback: callback,
531
+ type: CallbackType.All
532
+ };
533
+
534
+ if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
535
+ this.getRealAllVars(callbackObj);
536
+ } else {
537
+ this.callbacks.push(callbackObj);
538
+ }
539
+ };
540
+
541
+ Ab.prototype.getRealAllVars = function (item) {
542
+ var callback = item.callback;
543
+ callback(this.data ? JSON.parse(JSON.stringify(this.data)) : {});
544
+ this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
545
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
546
+ secType: 'AB',
547
+ info: 'SDK 调用getAllVars',
548
+ level: 'info',
549
+ time: Date.now(),
550
+ data: this.data
551
+ });
552
+ };
553
+
554
+ Ab.prototype.fechEvent = function (vid, key, ab_url) {
555
+ try {
556
+ if (this.config.disable_track_event) return;
557
+ if (!vid) return;
558
+
559
+ var _a = this.collect.configManager.get(),
560
+ header = _a.header,
561
+ user = _a.user;
562
+
563
+ var cache = this.getABCache();
564
+ if (cache && cache.uuid && cache.uuid !== user.user_unique_id) return;
565
+ var event_1 = {
566
+ event: 'abtest_exposure',
567
+ ab_sdk_version: "" + vid,
568
+ params: JSON.stringify({
569
+ app_id: this.config.appId,
570
+ ab_url: key === '$ab_url' ? ab_url : window.location.href
571
+ }),
572
+ local_time_ms: Date.now()
573
+ };
574
+ header['custom'] = JSON.stringify(header['custom']);
575
+ var abData = {
576
+ events: [event_1],
577
+ user: user,
578
+ header: header
579
+ };
580
+
581
+ if (key === '$ab_url') {
582
+ if (window.navigator.sendBeacon) {
583
+ window.navigator.sendBeacon(this.reportUrl, JSON.stringify([abData]));
584
+ } else {
585
+ this.reportExposure(abData);
586
+ }
587
+ } else {
588
+ this.reportExposure(abData);
589
+ }
590
+ } catch (e) {
591
+ this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
592
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
593
+ info: '发生了异常',
594
+ level: 'error',
595
+ time: Date.now(),
596
+ data: e.message
597
+ });
598
+ }
599
+ };
600
+
601
+ Ab.prototype.reportExposure = function (abData) {
602
+ var _this = this;
603
+
604
+ this.exposureCache.push(abData);
605
+
606
+ if (this.reportTimeout) {
607
+ clearTimeout(this.reportTimeout);
608
+ }
609
+
610
+ if (this.exposureCache.length >= this.exposureLimit) {
611
+ this.report();
612
+ } else {
613
+ this.reportTimeout = setTimeout(function () {
614
+ _this.report();
615
+
616
+ clearTimeout(_this.reportTimeout);
617
+ }, this.ab_batch_time);
618
+ }
619
+ };
620
+
621
+ Ab.prototype.report = function () {
622
+ var _this = this;
623
+
624
+ var encodeData = this.collect.cryptoData(this.exposureCache);
625
+ this.fetch(this.reportUrl, encodeData, 100000, false, function () {}, function () {}, '', 'POST', this.config.enable_encryption, this.config.encryption_header);
626
+ this.exposureCache.forEach(function (item) {
627
+ _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
628
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,
629
+ info: '埋点上报成功',
630
+ time: Date.now(),
631
+ data: [item],
632
+ code: 200,
633
+ status: 'success'
634
+ });
635
+ });
636
+ this.exposureCache = [];
637
+ };
638
+
639
+ Ab.prototype.setExternalAbVersion = function (vid) {
640
+ this.extVersions = [vid];
641
+ this.updateVersions();
642
+ };
643
+
644
+ Ab.prototype.getABconfig = function (params, callback) {
645
+ var keys = Object.keys(params);
646
+
647
+ if (keys && keys.length) {
648
+ this.collect.configManager.set(params);
649
+ }
650
+
651
+ this.fetchAB(callback);
652
+ };
653
+
654
+ Ab.prototype.get = function (key) {
655
+ if (this.ab_cross) {
656
+ var ab_cookie = this.cacheStorgae.getCookie(key, this.ab_cookie_domain);
657
+ return ab_cookie ? JSON.parse(ab_cookie) : null;
658
+ } else {
659
+ return this.cacheStorgae.getItem(key);
660
+ }
661
+ };
662
+
663
+ Ab.prototype.set = function (key, data) {
664
+ if (this.ab_cross) {
665
+ this.cacheStorgae.setCookie(key, data, STORAGE_EXPRIRE, this.ab_cookie_domain);
666
+ } else {
667
+ this.cacheStorgae.setItem(key, data);
668
+ }
669
+
670
+ this.collect.configManager.setAbCache(data);
671
+ };
672
+
673
+ Ab.prototype.getABCache = function (key) {
674
+ var data = {
675
+ ab_version: [],
676
+ ab_ext_version: [],
677
+ ab_version_multilink: [],
678
+ data: null,
679
+ timestamp: +new Date(),
680
+ uuid: ''
681
+ };
682
+ data = this.get(this.abKey) || data;
683
+
684
+ if (Date.now() - data.timestamp >= STORAGE_EXPRIRE) {
685
+ this.cacheStorgae.removeItem(this.abKey);
686
+ return null;
687
+ }
688
+
689
+ if (key) {
690
+ return data[key];
691
+ }
692
+
693
+ return data;
694
+ };
695
+
696
+ Ab.prototype.updateABCache = function () {
697
+ var cache = this.getABCache();
698
+ cache.ab_version_multilink = this.mulilinkVersions;
699
+ cache.ab_ext_version = this.extVersions;
700
+ cache.ab_version = this.versions;
701
+ cache.timestamp = Date.now();
702
+ this.set(this.abKey, cache);
703
+ };
704
+
705
+ Ab.prototype.setAbCache = function (uuid) {
706
+ var cache = this.getABCache();
707
+ cache.data = this.data;
708
+ cache.uuid = uuid;
709
+ cache.timestamp = Date.now();
710
+ this.set(this.abKey, cache);
711
+ };
712
+
713
+ Ab.prototype.clearCache = function () {
714
+ this.refreshFetchStatus = 'ing';
715
+ this.data = {};
716
+ this.extVersions = [];
717
+ this.mulilinkVersions = [];
718
+ this.versions = [];
719
+ this.collect.configManager.clearAbCache();
720
+ };
721
+
722
+ Ab.prototype.openOverlayer = function (timeout) {
723
+ var _this = this;
724
+
725
+ openOverlayer();
726
+
727
+ if (timeout) {
728
+ var layer_1 = setTimeout(function () {
729
+ _this.closeOverlayer();
730
+
731
+ clearTimeout(layer_1);
732
+ }, timeout);
733
+ }
734
+ };
735
+
736
+ Ab.prototype.closeOverlayer = function () {
737
+ closeOverlayer();
738
+ };
739
+
740
+ Ab.prototype.fetchComplete = function (abData, uuid) {
741
+ var _this = this;
742
+
743
+ if (abData && Object.prototype.toString.call(abData) == '[object Object]') {
744
+ this.data = abData;
745
+ this.setAbCache(uuid);
746
+ var versions_1 = [];
747
+ Object.keys(abData).forEach(function (key) {
748
+ var vid = abData[key].vid;
749
+
750
+ if (vid) {
751
+ versions_1.push(vid);
752
+ }
753
+ });
754
+ this.versions = this.versions.filter(function (vid) {
755
+ return versions_1.includes(vid);
756
+ });
757
+ var $ab_url = abData.$ab_url,
758
+ $ab_modification = abData.$ab_modification;
759
+
760
+ if ($ab_modification && $ab_modification.val && this.enable_ab_visual) {
761
+ if (this.collect.destroyInstance) return;
762
+ this.getVar('$ab_modification', window.location.href, function () {
763
+ // loadVisual($ab_modification.val);
764
+ _this.closeOverlayer();
765
+ });
766
+ } else if ($ab_url && this.enable_multilink) {
767
+ this.mulilinkVersions = this.mulilinkVersions.filter(function (vid) {
768
+ return versions_1.includes(vid);
769
+ });
770
+ var val_1 = $ab_url.val,
771
+ vid_1 = $ab_url.vid;
772
+
773
+ if (val_1 && vid_1) {
774
+ this.getVar('$ab_url', val_1, function () {
775
+ if (_this.editMode) return;
776
+
777
+ if (val_1 !== window.location.href) {
778
+ setTimeout(function () {
779
+ if (_this.collect.destroyInstance) return;
780
+ var jump = "" + val_1;
781
+ jump = jump.indexOf('http') === -1 ? "https://" + jump : jump;
782
+ var newhost = parseURL(jump).host;
783
+
784
+ try {
785
+ var urlObj = new URL(jump);
786
+
787
+ if (newhost !== location.host) {
788
+ // 跳转的是一个新域名
789
+ urlObj.searchParams.append('vid', vid_1);
790
+ } else {
791
+ // 不同的域名不能replace
792
+ window.history.replaceState('', '', jump);
793
+ }
794
+
795
+ window.location.href = urlObj.href;
796
+ } catch (e) {
797
+ window.location.href = jump;
798
+ }
799
+ }, 100);
800
+ } else {
801
+ _this.closeOverlayer();
802
+ }
803
+ });
804
+ }
805
+ }
806
+
807
+ this.updateVersions();
808
+ } else {
809
+ this.closeOverlayer();
810
+ }
811
+
812
+ this.callbacks.forEach(function (item) {
813
+ return _this[item.type === CallbackType.Var ? 'getRealVar' : 'getRealAllVars'](item, '');
814
+ });
815
+ this.callbacks = [];
816
+ };
817
+
818
+ Ab.prototype.fetchAB = function (callback) {
819
+ var _this = this;
820
+
821
+ var env = this.collect.configManager.get();
822
+ var header = env.header,
823
+ user = env.user;
824
+
825
+ if (this.config.enable_anonymousid) {
826
+ delete user.web_id;
827
+ }
828
+
829
+ var fetchUuid = user.user_unique_id;
830
+ var requestBody = {
831
+ header: __assign({
832
+ aid: this.config.app_id
833
+ }, user || {}, header || {}, {
834
+ ab_sdk_version: this.collect.configManager.getAbVersion(),
835
+ ab_url: window.location.href
836
+ })
837
+ };
838
+ this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
839
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
840
+ info: 'SDK 发起AB实验请求',
841
+ level: 'info',
842
+ logType: 'fetch',
843
+ time: Date.now(),
844
+ data: requestBody
845
+ });
846
+ var cryptoData = this.collect.cryptoData(requestBody);
847
+ this.fetch(this.fetchUrl, cryptoData, this.config.ab_timeout || 3000, false, function (response) {
848
+ _this.fetchStatus = 'complete';
849
+ _this.refreshFetchStatus = 'complete'; // let aa = {
850
+ // message: "success",
851
+ // data: {
852
+ // abcdefg: { val: "gss", vid: "11407" },
853
+ // erf: { val: 'name', vid: "22" },
854
+ // hhhhh: { val: 'age', vid: "33" },
855
+ // juuioh: { val: 'sex', vid: "44" },
856
+ // $ab_url: { val: 'http://0.0.0.0:8898/index_cdn_5.html?s=2', vid: '0000' }
857
+ // }
858
+ // }
859
+ // if (env.user.user_unique_id === 'bbbb') {
860
+ // aa.data.abcdefg.vid = '11408'
861
+ // } else if (env.user.user_unique_id === 'cccc') {
862
+ // aa.data.abcdefg.vid = '11409'
863
+ // }
864
+
865
+ var data = response.data,
866
+ message = response.message; // 解析出code
867
+
868
+ if (message === 'success') {
869
+ _this.fetchComplete(data, fetchUuid);
870
+
871
+ callback && callback(data);
872
+ } else {
873
+ _this.fetchComplete(null, fetchUuid);
874
+
875
+ callback && callback(null);
876
+ }
877
+
878
+ _this.collect.emit(_this.types.AbComplete, data);
879
+
880
+ _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
881
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
882
+ secType: 'AB',
883
+ info: 'AB实验请求成功',
884
+ level: 'info',
885
+ logType: 'fetch',
886
+ time: Date.now(),
887
+ data: data
888
+ });
889
+ }, function () {
890
+ _this.fetchStatus = 'complete';
891
+ _this.refreshFetchStatus = 'complete';
892
+
893
+ _this.fetchComplete(null, fetchUuid);
894
+
895
+ callback && callback(null);
896
+
897
+ _this.collect.emit(_this.types.AbTimeout);
898
+
899
+ _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
900
+ type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
901
+ secType: 'AB',
902
+ info: 'AB实验请求网络异常',
903
+ level: 'error',
904
+ logType: 'fetch',
905
+ time: Date.now()
906
+ });
907
+ }, '', '', this.config.enable_encryption, this.config.encryption_header);
908
+ };
909
+
910
+ Ab.prototype.filterUrl = function (url) {
911
+ try {
912
+ var _reg = '';
913
+
914
+ if (url.indexOf('&multilink=true') !== -1) {
915
+ _reg = '&multilink=true[\x00-\xff]*';
916
+ } else if (url.indexOf('?multilink=true') !== -1) {
917
+ _reg = '\\?multilink=true[\x00-\xff]*';
918
+ }
919
+
920
+ var reg = new RegExp(_reg, 'g');
921
+ url = url.replace(reg, '');
922
+ } catch (e) {}
923
+
924
+ return url;
925
+ };
926
+
927
+ return Ab;
928
+ }();
929
+
930
+ module.exports = Ab;