UNPKG

@unifygtm/intent-client

Version:

JavaScript client for interacting with the Unify Intent API in the browser.

7 lines (5 loc) 16.3 kB
var _t=Object.defineProperty,Et=Object.defineProperties;var vt=Object.getOwnPropertyDescriptors;var $=Object.getOwnPropertySymbols;var xt=Object.prototype.hasOwnProperty,It=Object.prototype.propertyIsEnumerable;var Z=(t,e,n)=>e in t?_t(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,c=(t,e)=>{for(var n in e||(e={}))xt.call(e,n)&&Z(t,n,e[n]);if($)for(var n of $(e))It.call(e,n)&&Z(t,n,e[n]);return t},v=(t,e)=>Et(t,vt(e));var x="https://unifyintent.com/analytics/api/v1";var At=/^[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$/,St=["identify","page"];function V(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&St.every(e=>e in t)}function k(t,e){var n;return((n=e==null?void 0:e.getTime())!=null?n:new Date().getTime())+t*60*1e3}var I=t=>({path:t!=null?t:window.location.pathname,query:Ct(window.location.href),referrer:document.referrer,title:document.title,url:t!==void 0?Dt({location:window.location,pathname:t}):window.location.href});function Dt({location:t,pathname:e}){let n=new URL(t.href);return n.pathname=e,n.toString()}var A=()=>({userAgent:window.navigator.userAgent,userAgentData:window.navigator.userAgentData}),S=t=>{if(At.test(t))return t},Ct=t=>{let e=new URL(t).searchParams,n={};for(let[r,i]of e.entries())n[r]=i;return n};var W=()=>{var n,r,i,a,o;let t=new URL(location.href),e={source:(n=t.searchParams.get("utm_source"))!=null?n:void 0,medium:(r=t.searchParams.get("utm_medium"))!=null?r:void 0,campaign:(i=t.searchParams.get("utm_campaign"))!=null?i:void 0,term:(a=t.searchParams.get("utm_term"))!=null?a:void 0,content:(o=t.searchParams.get("utm_content"))!=null?o:void 0};return v(c({locale:navigator.language},A()),{utm:e})};var K=class{constructor(e){this.getBaseActivityPayload=()=>({type:this.getActivityType(),anonymousUserId:this._intentContext.identityManager.getOrCreateAnonymousUserId(),sessionId:this._intentContext.sessionManager.getOrCreateSession().sessionId,context:W(),timestamp:new Date().toISOString()});this._intentContext=e}track(){this._intentContext.apiClient.post(this.getActivityURL(),c(c({},this.getBaseActivityPayload()),this.getActivityData()))}},D=K;var Tt=`${x}/page`,f=class extends D{constructor(n,r){super(n);this.getActivityData=()=>{var n;return{type:"page",properties:I((n=this._options)==null?void 0:n.pathname)}};this._options=r}getActivityType(){return"page"}getActivityURL(){return Tt}};var bt=`${x}/identify`,p=class extends D{constructor(n,{email:r}){super(n);this.getActivityData=()=>({type:"identify",traits:{email:this._email}});this._email=r}getActivityType(){return"identify"}getActivityURL(){return bt}};var C,Ut=new Uint8Array(16);function H(){if(!C&&(C=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!C))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return C(Ut)}var s=[];for(let t=0;t<256;++t)s.push((t+256).toString(16).slice(1));function Q(t,e=0){return s[t[e+0]]+s[t[e+1]]+s[t[e+2]]+s[t[e+3]]+"-"+s[t[e+4]]+s[t[e+5]]+"-"+s[t[e+6]]+s[t[e+7]]+"-"+s[t[e+8]]+s[t[e+9]]+"-"+s[t[e+10]]+s[t[e+11]]+s[t[e+12]]+s[t[e+13]]+s[t[e+14]]+s[t[e+15]]}var wt=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Y={randomUUID:wt};function Pt(t,e,n){if(Y.randomUUID&&!e&&!t)return Y.randomUUID();t=t||{};let r=t.random||(t.rng||H)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=r[i];return e}return Q(r)}var y=Pt;function T(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var Rt={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function G(t,e){function n(i,a,o){if(typeof document!="undefined"){o=T({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var d="";for(var l in o)o[l]&&(d+="; "+l,o[l]!==!0&&(d+="="+o[l].split(";")[0]));return document.cookie=i+"="+t.write(a,i)+d}}function r(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var a=document.cookie?document.cookie.split("; "):[],o={},d=0;d<a.length;d++){var l=a[d].split("="),ht=l.slice(1).join("=");try{var B=decodeURIComponent(l[0]);if(o[B]=t.read(ht,B),i===B)break}catch(Jt){}}return i?o[i]:o}}return Object.create({set:n,get:r,remove:function(i,a){n(i,"",T({},a,{expires:-1}))},withAttributes:function(i){return G(this.converter,T({},this.attributes,i))},withConverter:function(i){return G(T({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var b=G(Rt,{path:"/"});var g=typeof Buffer=="function",J=typeof TextDecoder=="function"?new TextDecoder:void 0,X=typeof TextEncoder=="function"?new TextEncoder:void 0,Ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h=Array.prototype.slice.call(Ft),U=(t=>{let e={};return t.forEach((n,r)=>e[n]=r),e})(h),Mt=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,u=String.fromCharCode.bind(String),tt=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),Nt=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),nt=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Ot=t=>{let e,n,r,i,a="",o=t.length%3;for(let d=0;d<t.length;){if((n=t.charCodeAt(d++))>255||(r=t.charCodeAt(d++))>255||(i=t.charCodeAt(d++))>255)throw new TypeError("invalid character found");e=n<<16|r<<8|i,a+=h[e>>18&63]+h[e>>12&63]+h[e>>6&63]+h[e&63]}return o?a.slice(0,o-3)+"===".substring(o):a},rt=typeof btoa=="function"?t=>btoa(t):g?t=>Buffer.from(t,"binary").toString("base64"):Ot,Lt=g?t=>Buffer.from(t).toString("base64"):t=>{let n=[];for(let r=0,i=t.length;r<i;r+=4096)n.push(u.apply(null,t.subarray(r,r+4096)));return rt(n.join(""))};var Bt=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?u(192|e>>>6)+u(128|e&63):u(224|e>>>12&15)+u(128|e>>>6&63)+u(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return u(240|e>>>18&7)+u(128|e>>>12&63)+u(128|e>>>6&63)+u(128|e&63)}},Vt=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,kt=t=>t.replace(Vt,Bt),et=g?t=>Buffer.from(t,"utf8").toString("base64"):X?t=>Lt(X.encode(t)):t=>rt(kt(t)),w=(t,e=!1)=>e?Nt(et(t)):et(t);var Kt=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,Ht=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),n=e-65536;return u((n>>>10)+55296)+u((n&1023)+56320);case 3:return u((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return u((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Yt=t=>t.replace(Kt,Ht),Gt=t=>{if(t=t.replace(/\s+/g,""),!Mt.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,n="",r,i;for(let a=0;a<t.length;)e=U[t.charAt(a++)]<<18|U[t.charAt(a++)]<<12|(r=U[t.charAt(a++)])<<6|(i=U[t.charAt(a++)]),n+=r===64?u(e>>16&255):i===64?u(e>>16&255,e>>8&255):u(e>>16&255,e>>8&255,e&255);return n},it=typeof atob=="function"?t=>atob(nt(t)):g?t=>Buffer.from(t,"base64").toString("binary"):Gt,jt=g?t=>tt(Buffer.from(t,"base64")):t=>tt(it(t).split("").map(e=>e.charCodeAt(0)));var zt=g?t=>Buffer.from(t,"base64").toString("utf8"):J?t=>J.decode(jt(t)):t=>Yt(it(t)),qt=t=>nt(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),ot=t=>zt(qt(t));var j="test";function z(t){return w(JSON.stringify(t))}function at(t){return JSON.parse(ot(t))}function st(){try{return localStorage.setItem(j,j),localStorage.removeItem(j),!0}catch(t){return!1}}function ut(t){return(t!=null?t:window.location.hostname).split(".").slice(-2).join(".")}var q=class{constructor(e){this.get=e=>{let n=this.retrieveValue(this.buildKey(e));return n?at(n):null};this.set=(e,n)=>{this.storeValue(this.buildKey(e),z(n))};this.buildKey=e=>z(`${this._writeKey}_${e}`);this._writeKey=e}},P=q;var R=class extends P{retrieveValue(e){var r;let n=(r=b.get(e))!=null?r:null;return n&&(b.remove(e),this.storeValue(e,n)),n}storeValue(e,n){b.set(e,n,{domain:`.${ut()}`,expires:365})}};var F=class extends P{constructor(n){super(n);this.retrieveValue=n=>this._localStorageAvailable?localStorage.getItem(n):null;this.storeValue=(n,r)=>{this._localStorageAvailable&&localStorage.setItem(n,r)};this._localStorageAvailable=st()}};var dt="anonymousUserId",M=class{constructor(e){this.getOrCreateAnonymousUserId=()=>{if(this._anonymousUserId)return this._anonymousUserId;let e=this.getAnonymousUserId()||this.createAnonymousUserId();return this._anonymousUserId=e,e};this.getAnonymousUserId=()=>this._storageService.get(dt);this.createAnonymousUserId=()=>{let e=y();return this._storageService.set(dt,e),e};this._storageService=new R(e),this._anonymousUserId=null}};var ct="clientSession",lt=30,N=class{constructor(e){this.getOrCreateSession=()=>this.getAndUpdateSession()||this.createSession();this.getAndUpdateSession=()=>{let e=this._currentSession||this.getStoredSession();if(!e)return;if(e.expiration>new Date().getTime())return this.updateSessionExpiration(e)};this.createSession=(e=lt)=>{let n=c({sessionId:y(),startTime:new Date,expiration:k(e),initial:I()},A());return this._currentSession=n,this.setStoredSession(n),n};this.updateSessionExpiration=(e,n=lt)=>{let r=v(c({},e),{expiration:k(n)});return this._currentSession=r,this.setStoredSession(r),r};this.getStoredSession=()=>this._storageService.get(ct);this.setStoredSession=e=>{this._storageService.set(ct,e)};this._writeKey=e,this._storageService=new F(this._writeKey),this._currentSession=null}};var _=class{constructor(e){this.post=(e,n)=>{let r=JSON.stringify(n),i=this.getAuthString(this._writeKey);if(fetch)fetch(e,{method:"POST",body:r,credentials:"include",headers:{"Content-type":"application/json; charset=UTF-8",Authorization:this.getAuthString(this._writeKey)},keepalive:!0}).catch(()=>{});else{let a=new XMLHttpRequest;a.open("POST",e,!0),a.setRequestHeader("Content-type","application/json; charset=UTF-8"),a.setRequestHeader("Authorization",i),a.send(r)}};this._writeKey=e}getAuthString(e){return`Basic ${w(e+":")}`}};function E({message:t}){console.debug(`%c[Unify]: %c${t}`,"font-weight: bold;","")}var ft="https://forms.default.com",pt="https://capture.navattic.com",gt=["default.form_completed","deafult.form_page_submitted","default.form_page_submitted"],O="user.email",mt="email";function yt(t){return gt.includes(t.event)}var m=class{constructor(e){this.startAutoPage=()=>{this._historyMonitored||this.monitorHistory(),this._autoPage=!0};this.stopAutoPage=()=>{this._historyMonitored&&window.removeEventListener("popstate",this.maybeTrackPage),this._autoPage=!1};this.startAutoIdentify=()=>{this._autoIdentify=!0,this.refreshMonitoredInputs(),setInterval(this.refreshMonitoredInputs,2e3),this.subscribeToThirdPartyMessages()};this.stopAutoIdentify=()=>{this._monitoredInputs.forEach(e=>{e.isConnected&&(e.removeEventListener("blur",this.handleInputBlur),e.removeEventListener("keydown",this.handleInputKeydown))}),this._monitoredInputs.clear(),this.unsubscribeFromThirdPartyMessages(),this._autoIdentify=!1};this.monitorHistory=()=>{let e=history.pushState;history.pushState=(...r)=>{e.apply(history,r),this.maybeTrackPage()};let n=history.replaceState;history.replaceState=(...r)=>{n.apply(history,r),this.maybeTrackPage()},window.addEventListener("popstate",this.maybeTrackPage),this._historyMonitored=!0};this.maybeTrackPage=()=>{this._autoPage&&(!this._lastLocation||$t(this._lastLocation,window.location))&&(new f(this._intentContext).track(),this._lastLocation=c({},window.location))};this.refreshMonitoredInputs=()=>{if(!this._autoIdentify)return;this._monitoredInputs.forEach(n=>{n.isConnected||this._monitoredInputs.delete(n)}),Array.from(document.getElementsByTagName("input")).filter(n=>!this._monitoredInputs.has(n)&&Zt(n)).forEach(n=>{n.addEventListener("blur",this.handleInputBlur),n.addEventListener("keydown",this.handleInputKeydown),this._monitoredInputs.add(n)})};this.subscribeToThirdPartyMessages=()=>{window.addEventListener("message",this.handleThirdPartyMessage)};this.unsubscribeFromThirdPartyMessages=()=>{window.removeEventListener("message",this.handleThirdPartyMessage)};this.handleThirdPartyMessage=e=>{if(!this._autoIdentify)return;let n;try{switch(e.origin){case ft:{n="Default",this.handleDefaultFormMessage(e);break}case pt:{n="Navattic",this.handleNavatticDemoMessage(e);break}}}catch(r){E({message:`Error occurred while handling message from third-party (${n}): ${r.message}`})}};this.handleDefaultFormMessage=e=>{if(this._autoIdentify&&yt(e.data)){let n=e.data.payload.email;n&&this.maybeIdentifyInputEmail(n)}};this.handleNavatticDemoMessage=e=>{var n,r,i;if(this._autoIdentify)if(e.data.type==="IDENTIFY_USER"){let a=(n=e.data.eventAttributes.FORM)==null?void 0:n[O];if(a)this.maybeIdentifyInputEmail(a);else{let o=(r=Object.values(e.data.eventAttributes).find(d=>O in d))==null?void 0:r[O];o&&this.maybeIdentifyInputEmail(o)}}else{let o=((i=e.data.properties)!=null?i:[]).find(({object:d,name:l})=>d==="END_USER"&&l===mt);o&&this.maybeIdentifyInputEmail(o.value)}};this.handleInputBlur=e=>{this._autoIdentify&&e.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(e.target.value)};this.handleInputKeydown=e=>{this._autoIdentify&&e.key==="Enter"&&e.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(e.target.value)};this.maybeIdentifyInputEmail=e=>{if(this._autoIdentify&&e){if(!S(e)||this._submittedEmails.has(e))return;new p(this._intentContext,{email:e}).track(),this._submittedEmails.add(e)}};this.__getMonitoredInputs=()=>this._monitoredInputs;this.__getSubmittedEmails=()=>this._submittedEmails;var n,r;this._intentContext=e,this._monitoredInputs=new Set,this._submittedEmails=new Set,this._autoPage=(n=e.clientConfig.autoPage)!=null?n:!1,this._autoIdentify=(r=e.clientConfig.autoIdentify)!=null?r:!1,this._historyMonitored=!1,this._autoPage&&(this.startAutoPage(),this.maybeTrackPage()),this._autoIdentify&&this.startAutoIdentify()}};function $t(t,e){return t.hostname!==e.hostname||t.pathname!==e.pathname}function Zt(t){return t.type==="email"||t.type==="text"}var Wt={autoPage:!1,autoIdentify:!1},L=class{constructor(e,n=Wt){this._mounted=!1;this.mount=()=>{if(typeof window=="undefined")return;if(V(window.unify)||V(window.unifyBrowser)){E({message:"UnifyIntentClient already exists on window, a new one will not be created."});return}let e=new _(this._writeKey),n=new N(this._writeKey);n.getOrCreateSession();let r=new M(this._writeKey);r.getOrCreateAnonymousUserId(),this._context={writeKey:this._writeKey,clientConfig:this._config,apiClient:e,sessionManager:n,identityManager:r},(this._config.autoPage||this._config.autoIdentify)&&(this._intentAgent=new m(this._context)),this._mounted=!0,Qt(this),window.unify=this,window.unifyBrowser=this};this.unmount=()=>{typeof window!="undefined"&&(this._config.autoPage&&this.stopAutoPage(),this._config.autoIdentify&&this.stopAutoIdentify(),this._mounted=!1,window.unify=void 0,window.unifyBrowser=void 0)};this.page=e=>{if(!this._mounted)return;new f(this._context,e).track()};this.identify=e=>{if(!this._mounted)return!1;let n=S(e);return n?(new p(this._context,{email:n}).track(),!0):!1};this.startAutoPage=()=>{this._mounted&&(this._intentAgent||(this._intentAgent=new m(this._context)),this._intentAgent.startAutoPage())};this.stopAutoPage=()=>{var e;this._mounted&&((e=this._intentAgent)==null||e.stopAutoPage())};this.startAutoIdentify=()=>{this._mounted&&(this._intentAgent||(this._intentAgent=new m(this._context)),this._intentAgent.startAutoIdentify())};this.stopAutoIdentify=()=>{var e;this._mounted&&((e=this._intentAgent)==null||e.stopAutoIdentify())};this._writeKey=e,this._config=n}};function Qt(t){(Array.isArray(window.unify)?[...window.unify]:Array.isArray(window.unifyBrowser)?[...window.unifyBrowser]:[]).forEach(([n,r])=>{if(typeof t[n]=="function")try{Array.isArray(r)?t[n].call(t,...r):t[n].call(t)}catch(i){E({message:i==null?void 0:i.message})}})}export{L as UnifyIntentClient}; /*! Bundled license information: js-cookie/dist/js.cookie.mjs: (*! js-cookie v3.0.5 | MIT *) */