-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrackingplan.min.js
1 lines (1 loc) · 14 KB
/
trackingplan.min.js
1
(function(){function a(a){var b={method:"POST",endpoint:"TRACKINGPLAN",payload:JSON.stringify(a)};r(b)}function b(a){if(ma.includes("img"))try{j(a)}catch(a){P(a)}if(ma.includes("xhr"))try{l(a)}catch(a){P(a)}if(ma.includes("beacon"))try{n(a)}catch(a){P(a)}if(ma.includes("form"))try{q(a)}catch(a){P(a)}if(ma.includes("ws"))try{p(a)}catch(a){P(a)}if(ma.includes("fetch"))try{o(a)}catch(a){P(a)}}function c(){var a=d();if(null!==a&&!ka)return!1;var b={landing:document.location.href,referrer:document.referrer};return U.setItem("_trackingplan_initial",JSON.stringify(b)),!0}function d(){return JSON.parse(U.getItem("_trackingplan_initial"))}function e(){try{if(U.setItem("_tp_t","a"),"a"!==U.getItem("_tp_t"))return!1;if(U.removeItem("_tp_t"),"function"!=typeof navigator.sendBeacon)return!1}catch(a){return!1}return!0}function f(a){return"string"==typeof a||a instanceof String}function g(a){return JSON.stringify(a,function(a,b){return b instanceof HTMLElement?b.nodeType:b})}function h(a,b){if(0===b.length)return!0;for(var c=0;c<b.length;c++){if(X.call(a,"payload")&&"string"==typeof a.payload&&0<=a.payload.indexOf(b[c]))return!0;if(X.call(a,"endpoint")&&"string"==typeof a.endpoint&&0<=a.endpoint.indexOf(b[c]))return!0}return!1}function i(a){return!(null!==ua)||0<=ua.indexOf(a)}function j(a){var b=a.Object.getOwnPropertyDescriptor(a.HTMLImageElement.prototype,"src").set;a.Object.defineProperty(a.HTMLImageElement.prototype,"src",{set:function(a){return!f(a)||2048<a.length?b.apply(this,arguments):(r({method:"GET",endpoint:a,protocol:"img"}),b.apply(this,arguments))}});var c=a.HTMLImageElement.prototype.setAttribute;a.HTMLImageElement.prototype.setAttribute=function(a,b){if("src"==a.toLowerCase()){if(!f(b)||b.length>2048)return c.apply(this,arguments);r({method:"GET",endpoint:b,protocol:"img"})}return c.apply(this,arguments)}}function k(a){var b=a;try{b instanceof FormData&&(b=JSON.stringify(Object.fromEntries(b)))}catch(a){}return b}function l(a){var b=a.XMLHttpRequest.prototype.open,c=a.XMLHttpRequest.prototype.send;a.XMLHttpRequest.prototype.open=function(a,c){return this._tpUrl=c,this._tpMethod=a,b.apply(this,arguments)},a.XMLHttpRequest.prototype.send=function(a){var b=k(a);return m(b,function(a){r({method:this._tpMethod,endpoint:this._tpUrl,payload:a,protocol:"xhr"})}.bind(this)),c.apply(this,arguments)}}function m(a,b){if(a instanceof Blob){var c=new FileReader;c.onload=function(){var a=c.result.split(",")[1];b(a)},c.readAsDataURL(a)}else b(a)}function n(a){var b=a.navigator.sendBeacon;a.navigator.sendBeacon=function(a,c){if(!f(a)||2048<a.length)return b.apply(this,arguments);var d=k(c);return m(d,function(b){r({method:"POST",endpoint:a,payload:b,protocol:"beacon"})}),b.apply(this,arguments)}}function o(a){var b=a.fetch;a.fetch=function(a,c){if(!f(a)||2048<a.length)return b.apply(this,arguments);var d="GET",e=null;return void 0!==c&&(void 0!==c.method&&(d=c.method.toUpperCase()),void 0!==c.body&&(e=k(c.body))),r({method:d,endpoint:a,payload:e,protocol:"fetch"}),b.apply(this,arguments)}}function p(a){var c=a.WebSocket;a.WebSocket=function(d,a){return a?new c(d,a):new c(d)};var b=c.prototype.send;c.prototype.send=function(a){return r({method:"WS",endpoint:this.url,payload:a,protocol:"ws"}),b.apply(this,arguments)},a.WebSocket.prototype=c.prototype}function q(a){function b(a){try{var b=a?a.target:this,c={method:b.method,endpoint:b.action,payload:JSON.stringify({location:V.location.href,form_id:b.id,method:b.method,form_data:Object.fromEntries(new FormData(b))}),protocol:"form"};r(c)}catch(a){}}a.addEventListener("submit",b,!0)}function r(a,b){var c=function(){try{var c=N(a);if("TRACKINGPLAN"==a.endpoint&&(c="trackingplan"),!c)return;if(!i(c))return void P({m:"Request ignored ("+c+" not in whitelist)",request:a});if(!h(a,ta))return void P({m:"Request ignored (content filter)",request:a});var d=L();return!1===d?(Ba.push(a),P({m:"Pre queued, queue length = "+Ba.length}),setTimeout(G,fa),!1):(Ea=C(),Fa=g(Ea).length,!x(ha,d))?(P({m:"Request ignored (sampling)",mode:ha,dict:d}),!0):(s(A(a,c)),"function"==typeof b&&b(),!0)}catch(b){Q({m:"Trackingplan process error",error:b,request:a})}};za?c():setTimeout(c,0)}function s(a){oa(a);var b=g(a);if(2e5<b.length&&P({m:"Track Too big, ignored: "+b.length}),va)return void u(a,ba);if(b.length+2+Fa>ia)return u(a,ba),void P({m:"Track > Batch Size: "+b.length});var c=Ca.length+b.length+Fa;c>ia&&(P({m:"Batch reaching limit: "+c}),t(ba)),c=Ca.length+b.length+Fa,P({m:"Queue len: "+c,rawTrack:a}),0!==Ca.length&&(Ca+=","),Ca+=b}function t(a){if(0!=Ca.length){var b=Ca;Ca="";var c={requests:JSON.parse("["+b+"]"),common:C()};w(c,a)}}function u(a,b){var c={requests:[a],common:C()};w(c,b)}function v(){var a=da+$,b=[];return qa&&b.push("debug=true"),null!=ya&&b.push("t="+ya),0<b.length&&(a+="?"+b.join("&")),a}function w(a,b){function c(a){var b=navigator.sendBeacon(v(),a),c=b?"accepted":"discarded";"accepted"==c&&na(a),P("SendBeacon: "+c)}function d(a){var b=new XMLHttpRequest;b.open("POST",v(),!0),b.onreadystatechange=function(){if(4===b.readyState)try{P({m:"Parsed",response:JSON.parse(b.response)}),na(a,b.response)}catch(a){}},b.send(a)}return("function"==typeof pa&&(a=pa(a)),P({m:"Sent",payload:a}),la)?void P("Not sending, is dry run"):void("xhr"===b?d(g(a)):"beacon"===b?c(g(a)):void 0)}function x(a,b){switch(a){case"user":return 1===b.isSampledUser;case"track":return Math.random()<1/b.sampleRate;case"all":return!0;case"none":default:return!1}}function y(){return z().length}function z(){if(!xa)return[];try{var a=wa();return"object"==typeof a[0]?a:[]}catch(a){return[]}}function A(a,b){return{provider:b,request:{endpoint:a.endpoint,method:a.method,post_payload:a.payload||null,protocol:a.protocol,href:V.location.href},ts:new Date().getTime(),dl_i:y()-1,last_click_path:Ja,last_click_text:Ka}}function B(){return O({hostname:V.location.hostname,user_agent:navigator.userAgent,load_url:Da},d())}function C(){return{context:B(),tp_id:$,source_alias:aa,environment:_,sdk:La.sdk,sdk_version:La.sdkVersion,sampling_rate:L().sampleRate,debug:ca,tags:ra,datalayer:z(),session_id:H()}}function D(){try{for(var a=window.performance.getEntriesByType("resource"),b={},c=[],d=0;d<a.length;d++){c.push(a[d].name);var e="",f=a[d].name.replace(/(^\w+:|^)\/\//,""),g=f.split("?"),h=g[0];g=h.split("/"),e=1<g.length?g[0]+"/"+g[1]:g[0];var j=e;X.call(b,j)||(b[j]=0),b[j]++}return b}catch(a){return null}}function E(){for(;Ba.length;){var a=Ba.shift();r(a)}}function F(a,b){return X.call(a,"environment_rates")&&X.call(a.environment_rates,b)?a.environment_rates[b]:a.sample_rate}function G(){if(!Aa){var b=new XMLHttpRequest,c=ea+"config-"+$+".json";b.onreadystatechange=function(){if(4==this.readyState)try{K(F(JSON.parse(this.responseText),_)),a({event_name:"new_dau"}),E()}catch(a){}Aa=!1},b.open("GET",c,!0),Aa=!0,b.send()}}function H(){if(!Ha)return null;var a=U.getItem("_trackingplan_session_id"),b=U.getItem("_trackingplan_session_ts");if(null===a||null===b)return P({m:"Session ID: Creating for the first time session "}),I();var c=Date.now(),d=parseInt(b,10),e=1e3*(60*Ga);return isNaN(d)||c>d+e?(P({m:"Session ID: Updating because timeout"}),I()):(U.setItem("_trackingplan_session_ts",c.toString()),a)}function I(){var b=J(),c=Date.now();return U.setItem("_trackingplan_session_id",b),U.setItem("_trackingplan_session_ts",c.toString()),a({event_name:"new_session"}),b}function J(){var a=new Date().getTime(),b="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c=Math.floor,d=0|(a+16*Math.random())%16;return a=c(a/16),("x"===b?d:8|3&d).toString(16)});return b}function K(a){if(!1===a)return U.removeItem("_trackingplan_sample_rate"),U.removeItem("_trackingplan_sample_rate_ts"),void U.removeItem("_trackingplan_is_sampled_user");var b=Math.random()<1/a?1:0;P({m:"Trackingplan sample rate = "+a+". isSampledUser "+b}),U.setItem("_trackingplan_sample_rate_ts",new Date().getTime()),U.setItem("_trackingplan_sample_rate",a),U.setItem("_trackingplan_is_sampled_user",b)}function L(){var a=U.getItem("_trackingplan_sample_rate_ts");return null!==a&&(parseInt(a)+1e3*ga<new Date().getTime()?(P({m:"Trackingplan sample rate expired"}),K(!1),!1):{sampleRate:parseInt(U.getItem("_trackingplan_sample_rate")),isSampledUser:parseInt(U.getItem("_trackingplan_is_sampled_user"))})}function M(a,b){if(null===a||null===b)return!0;if(b=b.toString(),"/"===a[0]){var c=new RegExp(a.slice(1,-1));return c.test(b)}return-1!==b.indexOf(a)}function N(a){var b=a.endpoint,c=a.payload;if(f(b)){for(var d in Z){var e=d.split("%"),g=e[0],h=2===e.length?e[1]:null;if(M(g,b)&&M(h,c))return Z[d]}return!1}}function O(b,c){for(var d in c)b[d]=c[d];return b}function P(a){ca&&W.log("TP "+$,a)}function Q(a){V.console&&W.warn&&W.warn(a)}function R(){function a(){for(var a=document.getElementsByTagName("IFRAME"),b=0;b<a.length;b++)d(a[b])}function c(a){try{return!!a.contentDocument}catch(a){return!1}}function d(a){try{c(a)&&(b(a.contentWindow),P("Intercepted frame "+a.id))}catch(a){}}function e(){var a=new MutationObserver(function(a){a.forEach(function(a){a.addedNodes.forEach(function(a){"IFRAME"==a.tagName&&d(a)})})});a.observe(document,{subtree:!0,childList:!0,attributes:!1,characterData:!1}),setTimeout(a.disconnect(),4e3)}"complete"===document.readyState?(a(),e()):document.onreadystatechange=function(){"complete"===document.readyState&&(a(),e())}}function S(a){try{if(!(a instanceof Element))return;for(var b=[];a.nodeType===Node.ELEMENT_NODE&&"html"!==a.nodeName.toLowerCase()&&"body"!==a.nodeName.toLowerCase();){var c=a.nodeName.toLowerCase();if(a.id){c+="#"+a.id,b.unshift(c);break}else{a.className&&(c+="."+a.className.split(" ").join(".").replace(/\s+/g,"."));for(var d=a,e=1;d=d.previousElementSibling;){var f=d.nodeName.toLowerCase();d.className&&(f+="."+d.className.split(" ").join(".").replace(/\s+/g,".")),f===c&&e++}1!=e&&(c+=":nth-of-type("+e+")")}b.unshift(c),a=a.parentNode}return b.join(" > ")}catch(a){return null}}function T(a){try{if(!(a instanceof Element))return null;var b=null;return"input"===a.tagName.toLowerCase()&&"password"!==a.type?b=a.value.trim():"input"!==a.tagName.toLowerCase()&&"script"!==a.tagName.toLowerCase()&&"style"!==a.tagName.toLowerCase()&&(b=a.textContent.trim()),b?b.slice(0,50):null}catch(a){return null}}var U=localStorage,V=window,W=console,X=Object.prototype.hasOwnProperty;if(V.Trackingplan)return void(V.Trackingplan.testing||Q("Trackingplan snippet included twice."));var Y={"google-analytics.com":"googleanalytics","analytics.google.com":"googleanalytics","/.*/pagead/(viewthroughconversion|conversion)/.*/":"google_ads","api.segment.io":"segment",segmentapi:"segment","seg-api":"segment","segment-api":"segment","/.*api-iam.intercom.io/messenger/web/(ping|events|metrics|open).*/":"intercom","api.amplitude.com":"amplitude","ping.chartbeat.net":"chartbeat","/.*api(-eu)?(-js)?.mixpanel.com.*/":"mixpanel","trk.kissmetrics.io":"kissmetrics","ct.pinterest.com":"pinterest","facebook.com/tr/":"facebook","track.hubspot.com/__":"hubspot","/.*.heapanalytics.com/(h|api).*/":"heap","/.*snowplow.*/":"snowplow","/.*ws.*.hotjar.com/api/v2/client/ws/%identify_user":"hotjar","/.*ws.*.hotjar.com/api/v2/client/ws/%tag_recording":"hotjar","klaviyo.com/api/track":"klaviyo","app.pendo.io/data":"pendo","matomo.php":"matomo","rs.fullstory.com/rec%8137":"fullstory","rs.fullstory.com/rec%8193":"fullstory","logx.optimizely.com/v1/events":"optimizely","track.customer.io/events/":"customerio","alb.reddit.com/rp.gif":"reddit","px.ads.linkedin.com":"linkedin","/i/adsct":"twitter","bat.bing.com":"bing","pdst.fm":"podsights","analytics.tiktok.com/api/v2":"tiktok","/.*AQB=1.*AQE=1/":"adobe","posthog.com/i/":"posthog","/.*tealiumiq.com/.*.gif/":"tealium",".connectif.cloud":"connectif","/ppms.php":"piwikpro"},Z={},$=null,_="PRODUCTION",aa=null,ba="xhr",ca=!1,da="https://tracks.trackingplan.com/v1/",ea="https://config.trackingplan.com/",fa=0,ga=86400,ha="user",ia=6e4,ja=20,ka=!1,la=!1,ma=["img","xhr","beacon","fetch"],na=function(){},oa=function(){},pa=function(a){return a},qa=!1,ra={},sa=null,ta=[],ua=null,va=!1,wa=function(){return window.dataLayer},xa=!0,ya=null,za=!1,Aa=!1,Ba=[],Ca="",Da="",Ea=null,Fa=0,Ga=30,Ha=!0,Ia=!0,Ja=null,Ka=null,La=V.Trackingplan={sdk:"js",sdkVersion:"1.18.5",options:null,tpId:null,testing:!1,setOptions:function(a,b){b=this.options=b||{},$=this.tpId=a,_=b.environment||_,aa=b.sourceAlias||aa,ba=b.sendMethod||ba,Z=O(Y,b.customDomains||{}),ca=b.debug||ca,da=b.tracksEndPoint||da,ea=b.configEndPoint||ea,fa=b.delayConfigDownload||fa,ga=b.sampleRateTTL||ga,ha=b.samplingMode||ha,ia=b.batchSize||ia,ja=b.batchInterval||ja,ka=b.alwaysSendNewUser||ka,la=b.dryRun||la,ma=b.intercept||ma,na=b.onSubmit||na,qa=b.parse||qa,oa=b.onQueue||oa,pa=b.onBeforeSubmit||pa,ra=b.tags||ra,sa=b.samplingRate||sa,ta=b.contentFilters||ta,ua=b.providersWhitelist||ua,va="undefined"==typeof b.realtime?va:b.realtime,wa=b.getDataLayer||wa,Ga=b.sessionDurationMinutes||Ga,Ia="undefined"==typeof b.intervalsOnInit?Ia:b.intervalsOnInit,xa="undefined"==typeof b.useDataLayer?xa:b.useDataLayer,Ha="undefined"==typeof b.useSessions?Ha:b.useSessions,ya=b.timestamp||ya,za=this.testing=b.testing||za,va&&(sa=1,ha="all",ia=1),P({m:"TP options updated",options:b})},init:function(d,f){try{if(za)return void Q("Trackingplan SDK is running in a test environment");if(!e())throw new Error("TP Not compatible browser");if(null!==$)throw new Error("TP Init already happened");La.setOptions(d,f),null!==sa&&K(sa),Da=V.location.href,b(window),ma.includes("frame")&&R(),document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&t("beacon")}),V.addEventListener("pagehide",function(){t("beacon")}),V.addEventListener("beforeunload",function(){a({event_name:"page_unload"}),t("beacon")}),V.document.addEventListener("click",function(a){Ja=S(a.target),Ka=T(a.target)},!1),c()&&a({event_name:"new_user"}),a({event_name:"page_load"}),!0===Ia&&La.initIntervals(),H(),P({m:"TP init finished",options:f})}catch(a){Q({m:"TP init error",error:a})}},flush:function(){t(ba)},queueSize:function(){return Ca.length},updateTags:function(a){t(ba),ra=O(ra,a)},initIntervals:function(){setTimeout(function(){a({event_name:"pixels",properties:{pixels:D()}})},1e4),setInterval(function(){t(ba)},1e3*ja)},getSessionId:function(){return U.getItem("_trackingplan_session_id")}}})();