UNPKG

@unifygtm/intent-client

Version:

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

7 lines (5 loc) 30.1 kB
var re=Object.defineProperty,ie=Object.defineProperties;var oe=Object.getOwnPropertyDescriptors;var ht=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,ae=Object.prototype.propertyIsEnumerable;var Tt=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,c=(e,t)=>{for(var n in t||(t={}))se.call(t,n)&&Tt(e,n,t[n]);if(ht)for(var n of ht(t))ae.call(t,n)&&Tt(e,n,t[n]);return e},g=(e,t)=>ie(e,oe(t));var I="https://api.unifyintent.com/analytics/v1",U=30,At={clickTrackingSelectors:[],navatticProductDemos:{["Navattic Demo Completed"]:!0,["Navattic Demo Started"]:!0,["Navattic Demo Step Viewed"]:!0},defaultForms:{["Default Form Completed"]:!0,["Default Form Page Submitted"]:!0,["Default Meeting Booked"]:!0,["Default Scheduler Closed"]:!0,["Default Scheduler Displayed"]:!0}};var pe=/^[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$/,le=["identify","page"];function Z(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&le.every(t=>t in e)}function J(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:fe(window.location.href),referrer:document.referrer,title:document.title,url:e!==void 0?de({location:window.location,pathname:e}):window.location.href});function de({location:e,pathname:t}){let n=new URL(e.href);return n.pathname=t,n.toString()}var B=()=>({userAgent:window.navigator.userAgent,userAgentData:typeof navigator.userAgentData!="undefined"?navigator.userAgentData:void 0}),P=e=>{if(pe.test(e))return e},fe=e=>{let t=new URL(e).searchParams,n={};for(let[r,i]of t.entries())n[r]=i;return n};function x(e){try{return new URL(e.startsWith("http")?e:`https://${e}`).hostname}catch(t){return null}}function b(e){var t;return(t=e.split("@").at(1))!=null?t:null}var vt=()=>{var n,r,i,o,s;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:(o=e.searchParams.get("utm_term"))!=null?o:void 0,content:(s=e.searchParams.get("utm_content"))!=null?s:void 0};return g(c({locale:navigator.language},B()),{utm:t})};var Q=class{constructor(t){this.getBaseActivityPayload=()=>({type:this.getActivityType(),visitorId:this._intentContext.identityManager.getOrCreateVisitorId(),sessionId:this._intentContext.sessionManager.getOrCreateSession().sessionId,context:vt(),timestamp:new Date().toISOString()});this._intentContext=t}track(){this._intentContext.apiClient.post(this.getActivityURL(),this.getTrackPayload())}getTrackPayload(){return c(c({},this.getBaseActivityPayload()),this.getActivityData())}},k=Q;var me=`${I}/page`,v=class extends k{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 me}};var Ee=`${I}/identify`,C=class extends k{constructor(n,{email:r,person:i,company:o}){super(n);this.getActivityData=()=>{var o;let n=this._company&&x((o=this._company)==null?void 0:o.domain),r=b(this._email),i=n&&n===r?this._company:void 0;return c({type:"identify",person:g(c({},this._person),{email:this._email})},i&&{company:this._company})};this._email=r,this._person=i,this._company=o}getActivityType(){return"identify"}getActivityURL(){return Ee}};var ye=`${I}/track`,d=class extends k{constructor(n,{name:r,properties:i}){super(n);this.getActivityData=()=>({type:"track",name:this._name,properties:c(c({},S()),this._properties)});this._name=r,this._properties=i}getActivityType(){return"track"}getActivityURL(){return ye}};var j,ge=new Uint8Array(16);function tt(){if(!j&&(j=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!j))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return j(ge)}var f=[];for(let e=0;e<256;++e)f.push((e+256).toString(16).slice(1));function Ct(e,t=0){return f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]}var _e=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),et={randomUUID:_e};function he(e,t,n){if(et.randomUUID&&!t&&!e)return et.randomUUID();e=e||{};let r=e.random||(e.rng||tt)();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 Ct(r)}var R=he;function K(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 Te={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 nt(e,t){function n(i,o,s){if(typeof document!="undefined"){s=K({},t,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var u in s)s[u]&&(a+="; "+u,s[u]!==!0&&(a+="="+s[u].split(";")[0]));return document.cookie=i+"="+e.write(o,i)+a}}function r(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},a=0;a<o.length;a++){var u=o[a].split("="),p=u.slice(1).join("=");try{var E=decodeURIComponent(u[0]);if(s[E]=e.read(p,E),i===E)break}catch(A){}}return i?s[i]:s}}return Object.create({set:n,get:r,remove:function(i,o){n(i,"",K({},o,{expires:-1}))},withAttributes:function(i){return nt(this.converter,K({},this.attributes,i))},withConverter:function(i){return nt(K({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var rt=nt(Te,{path:"/"});var L=typeof Buffer=="function",Dt=typeof TextDecoder=="function"?new TextDecoder:void 0,It=typeof TextEncoder=="function"?new TextEncoder:void 0,Ae="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",F=Array.prototype.slice.call(Ae),Y=(e=>{let t={};return e.forEach((n,r)=>t[n]=r),t})(F),ve=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,m=String.fromCharCode.bind(String),Ut=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),Ce=e=>e.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),xt=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),De=e=>{let t,n,r,i,o="",s=e.length%3;for(let a=0;a<e.length;){if((n=e.charCodeAt(a++))>255||(r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255)throw new TypeError("invalid character found");t=n<<16|r<<8|i,o+=F[t>>18&63]+F[t>>12&63]+F[t>>6&63]+F[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},bt=typeof btoa=="function"?e=>btoa(e):L?e=>Buffer.from(e,"binary").toString("base64"):De,Ie=L?e=>Buffer.from(e).toString("base64"):e=>{let n=[];for(let r=0,i=e.length;r<i;r+=4096)n.push(m.apply(null,e.subarray(r,r+4096)));return bt(n.join(""))};var Ue=e=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?m(192|t>>>6)+m(128|t&63):m(224|t>>>12&15)+m(128|t>>>6&63)+m(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return m(240|t>>>18&7)+m(128|t>>>12&63)+m(128|t>>>6&63)+m(128|t&63)}},Se=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,xe=e=>e.replace(Se,Ue),St=L?e=>Buffer.from(e,"utf8").toString("base64"):It?e=>Ie(It.encode(e)):e=>bt(xe(e)),kt=(e,t=!1)=>t?Ce(St(e)):St(e);var be=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,ke=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 m((n>>>10)+55296)+m((n&1023)+56320);case 3:return m((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return m((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Le=e=>e.replace(be,ke),we=e=>{if(e=e.replace(/\s+/g,""),!ve.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,n="",r,i;for(let o=0;o<e.length;)t=Y[e.charAt(o++)]<<18|Y[e.charAt(o++)]<<12|(r=Y[e.charAt(o++)])<<6|(i=Y[e.charAt(o++)]),n+=r===64?m(t>>16&255):i===64?m(t>>16&255,t>>8&255):m(t>>16&255,t>>8&255,t&255);return n},Lt=typeof atob=="function"?e=>atob(xt(e)):L?e=>Buffer.from(e,"base64").toString("binary"):we,Oe=L?e=>Ut(Buffer.from(e,"base64")):e=>Ut(Lt(e).split("").map(t=>t.charCodeAt(0)));var Me=L?e=>Buffer.from(e,"base64").toString("utf8"):Dt?e=>Dt.decode(Oe(e)):e=>Le(Lt(e)),Pe=e=>xt(e.replace(/[-_]/g,t=>t=="-"?"+":"/")),wt=e=>Me(Pe(e));var it="test";function ot(e){try{return JSON.parse(e)}catch(t){return e}}function st(e){return kt(JSON.stringify(e))}function Ot(e){return ot(wt(e))}function Mt(){try{return localStorage.setItem(it,it),localStorage.removeItem(it),!0}catch(e){return!1}}function Pt(e){return(e!=null?e:window.location.hostname).split(".").slice(-2).join(".")}var at=class{constructor(t){this.get=t=>{let n=this.retrieveValue(t);return n?ot(n):this.legacyGet(t)};this.legacyGet=t=>{let n=this.retrieveValue(this.buildKey(t));return n?Ot(n):null};this.set=(t,n)=>{this.storeValue(t,typeof n=="string"?n:JSON.stringify(n)),this.legacySet(t,n)};this.legacySet=(t,n)=>{this.storeValue(this.buildKey(t),st(n))};this.buildKey=t=>st(`${this._writeKey}_${t}`);this._writeKey=t}},H=at;var w=class extends H{retrieveValue(t){var r;let n=(r=rt.get(t))!=null?r:null;return n&&this.storeValue(t,n),n}storeValue(t,n){rt.set(t,n,{domain:`.${Pt()}`,expires:400})}};var G=class extends H{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=Mt()}};var Re="anonymousUserId",ct="unify_visitor_id",$=class{constructor(t){this.getOrCreateVisitorId=()=>{if(this._visitorId)return this._visitorId;let t=this.getVisitorId()||this.createVisitorId();return this._visitorId=t,t};this.getVisitorId=()=>{let t=this._storageService.get(ct);if(t)return t;let n=this._storageService.get(Re);return n&&this._storageService.set(ct,n),n};this.createVisitorId=()=>{let t=R();return this._storageService.set(ct,t),t};this._storageService=new w(t),this._visitorId=null}};var Fe={durationMinutes:U},Ne="clientSession",Rt="unify_session",Ve="unify_session_id",W=class{constructor(t,n){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=()=>{var n;let t=c({sessionId:R(),startTime:new Date,expiration:J((n=this._options.durationMinutes)!=null?n:U),initial:S()},B());return this._currentSession=t,this.setStoredSession(t),t};this.updateSessionExpiration=t=>{var r;let n=g(c({},t),{expiration:J((r=this._options.durationMinutes)!=null?r:U)});return this._currentSession=n,this.setStoredSession(n),n};this.getStoredSession=()=>{let t=this._storageService.get(Rt);if(t)return t;let n=this._storageService.get(Ne);return n&&this.setStoredSession(n),n};this.setStoredSession=t=>{this._storageService.set(Rt,t),this._cookieStorageService.set(Ve,t.sessionId)};this._writeKey=t,this._options=n!=null?n:Fe,this._storageService=new G(this._writeKey),this._cookieStorageService=new w(this._writeKey),this._currentSession=null}};var N=class{constructor(t){this.post=(t,n)=>{let r=JSON.stringify(n);if(fetch)fetch(t,{method:"POST",body:r,headers:{"Content-type":"application/json; charset=UTF-8","X-Write-Key":this._writeKey},keepalive:!0}).catch(()=>{});else{let i=new XMLHttpRequest;i.open("POST",t,!0),i.setRequestHeader("Content-type","application/json; charset=UTF-8"),i.setRequestHeader("X-Write-Key",this._writeKey),i.send(r)}};this._writeKey=t}};var Ft="1.9.5";var je="https://api.unifyintent.com/analytics/v1/_internal/logs";function _({message:e,error:t,attrs:n,apiClient:r}){console.debug(`%c[Unify]: %c${e}${t?`: ${t.message}`:""}${n?`, data: ${JSON.stringify(n)}`:""}`,"font-weight: bold;","");let i=n&&Object.entries(n).reduce((o,[s,a])=>g(c({},o),{[s]:typeof a=="string"?a:JSON.stringify(a)}),{});r==null||r.post(je,{status:"error",message:e,attrs:i,name:t==null?void 0:t.name,stack:t==null?void 0:t.stack,version:Ft})}var Nt="data-unify-track-clicks",Vt="unifyTrackClicks",Bt="data-unify-click-event-name",jt="unifyClickEventName",Kt="unifyLabel",Ye="unifyAttr",He="unifyEventProp",Yt=[Ye,He],Ht="unifyExclude",O="https://forms.default.com",q="https://scheduler.default.com",Gt={["default.form_completed"]:O,["deafult.form_page_submitted"]:O,["default.form_page_submitted"]:O,["default.meeting_booked"]:q,["default.scheduler_closed"]:O,["default.scheduler_displayed"]:q},$t="https://capture.navattic.com",Wt=["default.form_completed","deafult.form_page_submitted","default.form_page_submitted"];function qt(e){return!(!(e instanceof HTMLElement)||Ge(e)||e.matches(":disabled")||e.getAttribute("aria-disabled")==="true"||e.classList.contains("disabled")||ut(e,Ht))}function zt(e){let t=pt(e,Kt);if(t)return t;let n=Zt(e);if(n)return z(n);let r=e.getAttribute("aria-label");if(r)return z(r);let i=$e(e);if(i)return z(i);let o=We(e);return o?z(o):null}function Xt(e){if(!(e instanceof HTMLElement))return{};let t={};return Object.entries(e.dataset).forEach(([n,r])=>{Yt.forEach(i=>{if(n.startsWith(i)&&r){let o=n.slice(i.length);o&&(t[`${o.charAt(0).toLowerCase()}${o.slice(1)}`]=r)}})}),t}function Ge(e){if(!(e instanceof HTMLElement))return!1;if(e.hidden||e.getAttribute("aria-hidden")==="true")return!0;let t=getComputedStyle(e);return t.display==="none"||t.visibility==="hidden"}function z(e,t=80){if(!e)return null;let n=e.replace(/\s+/g," ").trim();return n?n.length>t?n.slice(0,t-1)+"...":n:null}function Zt(e){return e.innerText||e.textContent||""}function $e(e){let t=e.getAttribute("aria-labelledby");return t?t.split(/\s+/).map(n=>{let r=document.getElementById(n);return r?Zt(r):null}).filter(n=>!!n).join(" "):null}function We(e){let t=e.querySelector("img[alt]");return(t==null?void 0:t.alt)||null}function ut(e,t){if(!(e instanceof HTMLElement))return!1;let{dataset:n}=e;return n[t]!==void 0}function pt(e,t){if(!(e instanceof HTMLElement))return null;let{dataset:n}=e;return n[t]!==void 0?String(n[t]):null}function Jt(e,t){var n,r,i,o,s;try{let a=(n=e.properties)!=null?n:[],u=y("email","END_USER",a);if(!u)return;let p=y("fullName","END_USER",a),E=p?p.split(" ")[0]:y("firstName","END_USER",a),A=p?p.split(" ")[1]:y("lastName","END_USER",a),h=y("phone","END_USER",a),l=c(c(c({email:u},E&&{first_name:E}),A&&{last_name:A}),h&&{mobile_phone:h}),T=y("domain","COMPANY_ACCOUNT",a),M=T?x(T):null,V;if(M&&M===b(u)){let dt=(r=y("name","COMPANY_ACCOUNT",a))!=null?r:void 0,ft=(i=y("description","COMPANY_ACCOUNT",a))!=null?i:void 0,mt=(o=y("linkedin","COMPANY_ACCOUNT",a))!=null?o:void 0,Et=y("industry","COMPANY_ACCOUNT",a),yt=y("foundedYear","COMPANY_ACCOUNT",a),gt=(s=y("employeeCount","COMPANY_ACCOUNT",a))!=null?s:void 0,_t=isNaN(Number(gt))?void 0:Number(gt);V=c(c(c(c(c(c({domain:M},dt&&{name:dt}),ft&&{description:ft}),mt&&{linkedin_url:mt}),Et&&{industry:Et}),yt&&{founded:yt}),_t&&{employee_count:_t})}return c({person:l},V&&{company:V})}catch(a){_({message:`Error occurred while parsing attributes from Navattic event payload: ${a}`,error:a,apiClient:t});return}}function y(e,t,n){var r,i;return(i=(r=n.find(({object:o,name:s})=>o===t&&s===e))==null?void 0:r.value)!=null?i:null}function Qt({data:e,autoTrackOptions:t,intentContext:n}){var s,a,u,p;if(!t.navatticProductDemos)return;let{["Navattic Demo Started"]:r,["Navattic Demo Step Viewed"]:i,["Navattic Demo Completed"]:o}=t.navatticProductDemos===!0?{["Navattic Demo Started"]:!0,["Navattic Demo Step Viewed"]:!0,["Navattic Demo Completed"]:!0}:t.navatticProductDemos;switch(e.type){case"START_FLOW":{if(!r)return;new d(n,{name:"Navattic Demo Started",properties:{demo:(s=e.flow)==null?void 0:s.name,wasAutoTracked:!0}}).track();return}case"VIEW_STEP":{if(!i)return;new d(n,{name:"Navattic Demo Step Viewed",properties:{demo:(a=e.flow)==null?void 0:a.name,step:(u=e.step)==null?void 0:u.name,wasAutoTracked:!0}}).track();return}case"COMPLETE_FLOW":{if(!o)return;new d(n,{name:"Navattic Demo Completed",properties:{demo:(p=e.flow)==null?void 0:p.name,wasAutoTracked:!0}}).track();return}}}function lt(e){return typeof e!="string"&&Wt.includes(e.event)}function te(e,t){if(lt(e))try{let{email:n,attributes:r}=e.payload;if(!n)return;let i=c({email:n},r&&c(c(c(c({},r.first_name&&{first_name:r.first_name}),r.last_name&&{last_name:r.last_name}),r.phone&&{mobile_phone:r.phone}),r.title&&{title:r.title})),o=r!=null&&r.website?x(r.website):null,s;if(o&&o===b(n)){let a=r&&!isNaN(Number(r.head_count))?Number(r.head_count):void 0;s=c({domain:o},r&&c(c(c({},r.company&&{name:r.company}),r.industry_group&&{industry:r.industry_group}),a&&{employee_count:a}))}return c({person:i},s&&{company:s})}catch(n){_({message:`Error occurred while parsing attributes from Default event payload: ${n}`,error:n,apiClient:t});return}}function ee({data:e,autoTrackOptions:t,intentContext:n}){var u,p,E,A;if(!t.defaultForms||typeof e=="string")return null;let{["Default Form Completed"]:r,["Default Form Page Submitted"]:i,["Default Meeting Booked"]:o,["Default Scheduler Closed"]:s,["Default Scheduler Displayed"]:a}=t.defaultForms===!0?{["Default Form Completed"]:!0,["Default Form Page Submitted"]:!0,["Default Meeting Booked"]:!0,["Default Scheduler Closed"]:!0,["Default Scheduler Displayed"]:!0}:t.defaultForms;switch(e.event){case"default.form_completed":return r?(new d(n,{name:"Default Form Completed",properties:{form:e.payload.formName,formId:(u=e.payload.formId)==null?void 0:u.toString(),wasAutoTracked:!0}}).track(),"Default Form Completed"):null;case"deafult.form_page_submitted":case"default.form_page_submitted":return i?(new d(n,{name:"Default Form Page Submitted",properties:{form:e.payload.formName,formId:(p=e.payload.formId)==null?void 0:p.toString(),pageNumber:(E=e.payload.pageNumber)==null?void 0:E.toString(),wasAutoTracked:!0}}).track(),"Default Form Page Submitted"):null;case"default.meeting_booked":{if(!o)return null;let{memberName:h,memberEmail:l,durationInMinutes:T,startDateTime:M}=e.payload;return new d(n,{name:"Default Meeting Booked",properties:{memberName:h,memberEmail:l,durationInMinutes:T==null?void 0:T.toString(),startDateTime:M,wasAutoTracked:!0}}).track(),"Default Meeting Booked"}case"default.scheduler_closed":return s?(new d(n,{name:"Default Scheduler Closed",properties:{wasAutoTracked:!0}}).track(),"Default Scheduler Closed"):null;case"default.scheduler_displayed":return a?(new d(n,{name:"Default Scheduler Displayed",properties:{formId:(A=e.payload.formId)==null?void 0:A.toString(),wasAutoTracked:!0}}).track(),"Default Scheduler Displayed"):null}return null}var D=class{constructor(t){this._monitoredInputs=new Set;this._submittedEmails=new Set;this._historyMonitored=!1;this._isTrackingClicks=!1;this._isSubscribedToThirdPartyMessages=!1;this._justTrackedDefaultEventType=null;this.unmount=()=>{this.stopAutoIdentify(),this.stopAutoPage(),this.stopAutoTrack(),this.unsubscribeFromThirdPartyMessages()};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.stopAutoIdentify=()=>{this._monitoredInputs.forEach(t=>{t.isConnected&&(t.removeEventListener("blur",this.handleInputBlur),t.removeEventListener("keydown",this.handleInputKeydown))}),this._monitoredInputs.clear(),this._autoIdentify=!1};this.startAutoTrack=t=>{t&&(this._autoTrackOptions=t),this.startTrackingClicks()};this.stopAutoTrack=()=>{this.stopTrackingClicks()};this.monitorHistory=()=>{try{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}catch(t){this.logError("Error occurred in monitorHistory",t)}};this.maybeTrackPage=()=>{if(this._autoPage)try{(!this._lastLocation||Xe(this._lastLocation,window.location))&&(new v(this._intentContext).track(),this._lastLocation=c({},window.location))}catch(t){this.logError("Error occurred in maybeTrackPage",t)}};this.startTrackingClicks=()=>{this._isTrackingClicks||(document.addEventListener("click",this.handleDocumentClick),this._isTrackingClicks=!0)};this.stopTrackingClicks=()=>{this._isTrackingClicks&&(document.removeEventListener("click",this.handleDocumentClick),this._isTrackingClicks=!1)};this.handleDocumentClick=t=>{var n;try{let r=t.target;if(!r||typeof r.closest!="function")return;let i=`[${Nt}]`,o=`[${Bt}]`,s=(n=this._autoTrackOptions.clickTrackingSelectors)!=null?n:[],a=[i,o,...s.map(l=>typeof l=="string"?l:l.selector)],u=r.closest(a.join(", "));if(!u||!(u instanceof HTMLElement)||!qt(u))return;let p=ut(u,Vt)?"Element Clicked":null,E=pt(u,jt),A=s.map(l=>{var T;return typeof l=="string"?p||E?null:u.matches(l)?"Element Clicked":null:u.matches(l.selector)?(p||E)&&!l.eventName?null:(T=l.eventName)!=null?T:"Element Clicked":null});[E,...A].filter(l=>!!l).forEach(l=>{this.maybeTrackClick({element:u,eventName:l})}),p&&this.maybeTrackClick({element:u,eventName:p,isLegacy:!0})}catch(r){this.logError("Error occurred in handleDocumentClick",r)}};this.refreshMonitoredInputs=()=>{if(this._autoIdentify)try{this._monitoredInputs.forEach(n=>{n.isConnected||this._monitoredInputs.delete(n)}),Array.from(document.getElementsByTagName("input")).filter(n=>!this._monitoredInputs.has(n)&&Ze(n)).forEach(n=>{n.addEventListener("blur",this.handleInputBlur),n.addEventListener("keydown",this.handleInputKeydown),this._monitoredInputs.add(n)})}catch(t){this.logError("Error occurred in refreshMonitoredInputs",t)}};this.subscribeToThirdPartyMessages=()=>{this._isSubscribedToThirdPartyMessages||window.addEventListener("message",this.handleThirdPartyMessage),this._isSubscribedToThirdPartyMessages=!0};this.unsubscribeFromThirdPartyMessages=()=>{this._isSubscribedToThirdPartyMessages&&window.removeEventListener("message",this.handleThirdPartyMessage),this._isSubscribedToThirdPartyMessages=!1};this.handleThirdPartyMessage=t=>{let n;try{switch(t.origin){case O:case q:{n="Default",this.handleDefaultFormMessage(t);break}case $t:{n="Navattic",this.handleNavatticDemoMessage(t);break}}}catch(r){this.logError(`Error occurred in handleThirdPartyMessage for third-party ${n}`,r)}};this.handleDefaultFormMessage=t=>{try{if(typeof t.data=="string"||t.origin!==Gt[t.data.event])return;if(this._autoIdentify&&lt(t.data)){let n=t.data.payload.email;n&&this.maybeIdentifyInputEmail(n,te(t.data,this._intentContext.apiClient))}if(this._autoTrackOptions.defaultForms){if(t.data.event===this._justTrackedDefaultEventType)return;ee({data:t.data,autoTrackOptions:this._autoTrackOptions,intentContext:this._intentContext})&&(this._justTrackedDefaultEventType=t.data.event,setTimeout(()=>{this._justTrackedDefaultEventType=null},500))}}catch(n){this.logError("Error occurred in handleDefaultFormMessage",n)}};this.handleNavatticDemoMessage=t=>{var n,r;try{if(this._autoIdentify){let o=((r=(n=t.data)==null?void 0:n.properties)!=null?r:[]).find(({object:s,name:a})=>s==="END_USER"&&a==="email");o!=null&&o.value&&this.maybeIdentifyInputEmail(o.value,Jt(t.data,this._intentContext.apiClient))}this._autoTrackOptions.navatticProductDemos&&Qt({data:t.data,autoTrackOptions:this._autoTrackOptions,intentContext:this._intentContext})}catch(i){this.logError("Error occurred in handleNavatticDemoMessage",i)}};this.handleInputBlur=t=>{if(this._autoIdentify)try{t.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(t.target.value)}catch(n){this.logError("Error occurred in handleInputBlur",n)}};this.handleInputKeydown=t=>{if(this._autoIdentify)try{t.key==="Enter"&&t.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(t.target.value)}catch(n){this.logError("Error occurred in handleInputKeyDown",n)}};this.maybeIdentifyInputEmail=(t,n)=>{if(this._autoIdentify)try{if(t){if(!P(t)||this._submittedEmails.has(t))return;new C(this._intentContext,{email:t,person:n==null?void 0:n.person,company:n==null?void 0:n.company}).track(),this._submittedEmails.add(t)}}catch(r){this.logError("Error occurred in maybeIdentifyInputEmail",r)}};this.maybeTrackClick=({element:t,eventName:n,isLegacy:r=!1})=>{try{let i=zt(t);if(!i)return;let o=Xt(t);new d(this._intentContext,{name:n,properties:g(c(g(c({},o),{label:i}),r&&{elementName:i}),{wasAutoTracked:!0})}).track()}catch(i){this.logError("Error occurred in maybeTrackClick",i)}};this.logError=(t,n)=>{_({message:`UnifyIntentAgent: ${t}`,error:n,apiClient:this._intentContext.apiClient})};this.__getMonitoredInputs=()=>this._monitoredInputs;this.__getSubmittedEmails=()=>this._submittedEmails;var n,r;this._intentContext=t,this._autoPage=(n=t.clientConfig.autoPage)!=null?n:!1,this._autoIdentify=(r=t.clientConfig.autoIdentify)!=null?r:!1,this._autoTrackOptions=c({},t.clientConfig.autoTrackOptions),this._autoPage&&(this.startAutoPage(),this.maybeTrackPage()),this._autoIdentify&&this.startAutoIdentify(),this.startAutoTrack(),this.subscribeToThirdPartyMessages()}};function Xe(e,t){return e.hostname!==t.hostname||e.pathname!==t.pathname}function Ze(e){return e.type==="email"||e.type==="text"}var Je={autoPage:!1,autoIdentify:!1,sessionDurationMinutes:U,autoTrackOptions:At};function ne(){return{identify:[],page:[],track:[]}}var X=class{constructor(t,n=Je){this._mounted=!1;this._eventBuffers=ne();this.isMounted=()=>this._mounted;this.mount=()=>{if(typeof window!="undefined")try{if(Z(window.unify)||Z(window.unifyBrowser)){_({message:"UnifyIntentClient already exists on window, a new one will not be created."});return}let t=new N(this._writeKey),n=new W(this._writeKey,{durationMinutes:this._config.sessionDurationMinutes});n.getOrCreateSession();let r=new $(this._writeKey);r.getOrCreateVisitorId(),this._context={writeKey:this._writeKey,clientConfig:this._config,apiClient:t,sessionManager:n,identityManager:r},this._intentAgent=new D(this._context),this._mounted=!0,Qe(this,t),this._eventBuffers.identify.forEach(i=>this.identify(...i)),this._eventBuffers.page.forEach(i=>this.page(...i)),this._eventBuffers.track.forEach(i=>this.track(...i)),this._eventBuffers=ne(),window.unify=this,window.unifyBrowser=this}catch(t){this.logError("Error occurred in mount",t)}};this.unmount=()=>{var t;if(typeof window!="undefined")try{this._config.autoPage&&this.stopAutoPage(),this._config.autoIdentify&&this.stopAutoIdentify(),this.stopAutoTrack(),(t=this._intentAgent)==null||t.unmount(),this._mounted=!1,window.unify=void 0,window.unifyBrowser=void 0}catch(n){this.logError("Error occurred in unmount",n)}};this.page=t=>{if(!this._mounted){this._eventBuffers.page.push([t]);return}try{new v(this._context,t).track()}catch(n){this.logError("Error occurred in page",n)}};this.getPagePayload=t=>{if(this._mounted)try{return new v(this._context,t).getTrackPayload()}catch(n){this.logError("Error occurred in getPagePayload",n)}};this.identify=(t,n)=>{try{let r=P(t);if(r)return this._mounted?(new C(this._context,{email:r,person:n==null?void 0:n.person,company:n==null?void 0:n.company}).track(),!0):(this._eventBuffers.identify.push([t,n]),!0)}catch(r){this.logError("Error occurred in identify",r)}return!1};this.getIdentifyPayload=(t,n)=>{if(!this._mounted)return!1;try{let r=P(t);if(r)return new C(this._context,{email:r,person:n==null?void 0:n.person,company:n==null?void 0:n.company}).getTrackPayload()}catch(r){this.logError("Error occurred in getIdentifyPayload",r)}};this.track=(t,n)=>{if(!this._mounted){this._eventBuffers.track.push([t,n]);return}try{new d(this._context,{name:t,properties:n}).track()}catch(r){this.logError("Error occurred in track",r)}};this.getTrackPayload=(t,n)=>{if(this._mounted)try{return new d(this._context,{name:t,properties:n}).getTrackPayload()}catch(r){this.logError("Error occurred in getTrackPayload",r)}};this.startAutoPage=()=>{if(this._mounted)try{this._intentAgent||(this._intentAgent=new D(this._context)),this._intentAgent.startAutoPage()}catch(t){this.logError("Error occurred in startAutoPage",t)}};this.stopAutoPage=()=>{var t;if(this._mounted)try{(t=this._intentAgent)==null||t.stopAutoPage()}catch(n){this.logError("Error occurred in stopAutoPage",n)}};this.startAutoIdentify=()=>{if(this._mounted)try{this._intentAgent||(this._intentAgent=new D(this._context)),this._intentAgent.startAutoIdentify()}catch(t){this.logError("Error occurred in startAutoIdentify",t)}};this.stopAutoIdentify=()=>{var t;if(this._mounted)try{(t=this._intentAgent)==null||t.stopAutoIdentify()}catch(n){this.logError("Error occurred in stopAutoIdentify",n)}};this.startAutoTrack=t=>{if(this._mounted)try{t&&(this._config.autoTrackOptions=t),this._intentAgent||(this._intentAgent=new D(this._context)),this._intentAgent.startAutoTrack(t)}catch(n){this.logError("Error occurred in startAutoTrack",n)}};this.stopAutoTrack=()=>{var t;if(this._mounted)try{(t=this._intentAgent)==null||t.stopAutoTrack()}catch(n){this.logError("Error occurred in stopAutoTrack",n)}};this.logError=(t,n)=>{_({message:`UnifyIntentClient: ${t}`,error:n,apiClient:this._context.apiClient})};this.__getEventBuffers=()=>this._eventBuffers;this._writeKey=t,this._config=n}};function Qe(e,t){(Array.isArray(window.unify)?[...window.unify]:Array.isArray(window.unifyBrowser)?[...window.unifyBrowser]:[]).forEach(([r,i])=>{if(typeof e[r]=="function")try{Array.isArray(i)?e[r].call(e,...i):e[r].call(e)}catch(o){_({message:`Error occurred while flushing queue: ${o==null?void 0:o.message}`,error:o,apiClient:t})}})}export{X as UnifyIntentClient}; /*! Bundled license information: js-cookie/dist/js.cookie.mjs: (*! js-cookie v3.0.5 | MIT *) */