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