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