UNPKG

@unifygtm/intent-client

Version:

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

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