coveo.analytics
Advanced tools
Comparing version 2.4.1 to 2.4.2
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).coveoua=t()}(this,function(){"use strict";var o,e,h=function(){return(h=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function s(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function n(e,s,a,c){return new(a=a||Promise)(function(n,t){function o(e){try{i(c.next(e))}catch(e){t(e)}}function r(e){try{i(c.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?n(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(o,r)}i((c=c.apply(e,s||[])).next())})}function v(n,o){var r,i,s,e,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return e={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,i&&(s=2&t[0]?i.return:t[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,t[1])).done)return s;switch(i=0,s&&(t=[2&t[0],s.value]),t[0]){case 0:case 1:s=t;break;case 4:return a.label++,{value:t[1],done:!1};case 5:a.label++,i=t[1],t=[0];continue;case 7:t=a.ops.pop(),a.trys.pop();continue;default:if(!(s=0<(s=a.trys).length&&s[s.length-1])&&(6===t[0]||2===t[0])){a=0;continue}if(3===t[0]&&(!s||t[1]>s[0]&&t[1]<s[3])){a.label=t[1];break}if(6===t[0]&&a.label<s[1]){a.label=s[1],s=t;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(t);break}s[2]&&a.ops.pop(),a.trys.pop();continue}t=o.call(n,a)}catch(e){t=[6,e],i=0}finally{r=s=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function a(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var o=Array(e),r=0;for(t=0;t<n;t++)for(var i=arguments[t],s=0,a=i.length;s<a;s++,r++)o[r]=i[s];return o}(e=o=o||{}).search="search",e.click="click",e.custom="custom",e.view="view",e.collect="collect";var r=(t.prototype.sendEvent=function(a,c){return n(this,void 0,void 0,function(){var t,n,o,r,i,s;return v(this,function(e){switch(e.label){case 0:return t=this.opts,n=t.baseUrl,o=t.visitorIdProvider,r=this.shouldAppendVisitorId(a)?this.visitorIdParam:"",[4,fetch(n+"/analytics/"+a+r,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(c),credentials:"include"})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return(s=e.sent()).visitorId&&(o.currentVisitorId=s.visitorId),[2,s];case 3:try{i.json()}catch(e){}throw console.error('An error has occured when sending the "'+a+'" event.',i,c),new Error('An error has occurred when sending the "'+a+'" event. Check the console logs for more details.')}})})},t.prototype.shouldAppendVisitorId=function(e){return-1!==[o.click,o.custom,o.search,o.view].indexOf(e)},Object.defineProperty(t.prototype,"visitorIdParam",{get:function(){var e=this.opts.visitorIdProvider.currentVisitorId;return e?"?visitor="+e:""},enumerable:!0,configurable:!0}),t.prototype.getHeaders=function(){var e=this.opts.token;return h(h({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})},t);function t(e){this.opts=e}function i(){return"undefined"!=typeof navigator}function c(){return"undefined"!=typeof localStorage}function u(){return i()&&navigator.cookieEnabled}function l(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}function p(e,t){return-1!==f.indexOf(e)?h({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t}var f=[o.click,o.custom,o.search,o.view],d=(g.set=function(e,t,n){var o,r,i,s,a;s=n?((i=new Date).setTime(i.getTime()+n),"; expires="+i.toGMTString()):"",-1===(a=location.hostname).indexOf(".")?document.cookie=e+"="+t+s+"; path=/":((r=a.split(".")).shift(),o="."+r.join("."),document.cookie=e+"="+t+s+"; path=/; domain="+o,null!=g.get(e)&&g.get(e)==t||(o="."+a,document.cookie=e+"="+t+s+"; path=/; domain="+o))},g.get=function(e){for(var t=e+"=",n=document.cookie.split(";"),o=0;o<n.length;o++){var r=n[o];if(0==(r=r.replace(/^\s+/,"")).indexOf(t))return r.substring(t.length,r.length)}return null},g.erase=function(e){g.set(e,"",-1)},g);function g(){}function y(){return c()?localStorage:u()?new m:"undefined"!=typeof sessionStorage?sessionStorage:new S}var m=(w.prototype.getItem=function(e){return d.get(""+w.prefix+e)},w.prototype.removeItem=function(e){d.erase(""+w.prefix+e)},w.prototype.setItem=function(e,t){d.set(""+w.prefix+e,t)},w.prefix="coveo_",w);function w(){}var b=(E.prototype.getItem=function(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)},E.prototype.removeItem=function(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)},E.prototype.setItem=function(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)},E);function E(){this.cookieStorage=new m}var S=(I.prototype.getItem=function(e){return null},I.prototype.removeItem=function(e){},I.prototype.setItem=function(e,t){},I);function I(){}var C=Object.freeze({__proto__:null,preferredStorage:null,getAvailableStorage:y,CookieStorage:m,CookieAndLocalStorage:b,NullStorage:S}),x="__coveo.analytics.history",P=(k.prototype.addElement=function(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);var t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])},k.prototype.getHistory=function(){var e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)},k.prototype.getHistoryWithInternalTime=function(){try{var e=this.store.getItem(x);return e?JSON.parse(e):[]}catch(e){return[]}},k.prototype.setHistory=function(e){try{this.store.setItem(x,JSON.stringify(e.slice(0,20)))}catch(e){}},k.prototype.clear=function(){try{this.store.removeItem(x)}catch(e){}},k.prototype.getMostRecentElement=function(){var e=this.getHistoryWithInternalTime();return null==e?null:e.sort(function(e,t){return(t.internalTime||0)-(e.internalTime||0)})[0]},k.prototype.cropQueryElement=function(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))},k.prototype.isValidEntry=function(e){var t=this.getMostRecentElement();return!t||t.value!=e.value||6e4<(e.internalTime||0)-(t.internalTime||0)},k.prototype.stripInternalTime=function(e){return e.map(function(e){return{name:e.name,time:e.time,value:e.value}})},k);function k(e){this.store=e||y(),this.store instanceof m||!u()||(new m).removeItem(x)}function T(e,t){return e===o.view?(R(t.contentIdValue),h({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t}function A(t){return[function(e){return Y.test(e)},function(e){return W.test(e)},function(e){return-1!==M.indexOf(e)},function(e){return"custom"===e}].some(function(e){return e(t)})}var O=Object.freeze({__proto__:null,STORE_KEY:x,MAX_NUMBER_OF_HISTORY_ELEMENTS:20,MIN_THRESHOLD_FOR_DUPLICATE_VALUE:6e4,MAX_VALUE_SIZE:75,HistoryStore:P,default:P}),R=function(e){var t=new P,n={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(n)},F=function(e){return e?(Number(e)^L(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):(""+1e7+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,F)},L=function(e){if(l())return crypto.getRandomValues(e);for(var t=0,n=0;t<e.length;t++)0==(3&t)&&(n=4294967296*Math.random()),e[t]=n>>>((3&t)<<3)&255;return e},V={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},j={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},N=h(h(h(h(h({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),_=Object.keys,U=function(r,i,s){return _(r).reduce(function(e,t){var n,o="il"+(i+1)+"pi"+(s+1)+(j[t]||t);return h(h({},e),((n={})[o]=r[t],n))},{})},M=_(N).map(function(e){return N[e]}),D=_(V).map(function(e){return V[e]}),q=_(j).map(function(e){return j[e]}),H=a(D,["custom"]).join("|"),B=a(q,["custom"]).join("|"),z="(pr[0-9]+)",Q="(il[0-9]+pi[0-9]+)",Y=new RegExp("^"+z+"("+H+")$"),W=new RegExp("^("+Q+"("+B+"))|(il[0-9]+nm)$"),J=new RegExp("^"+z+"custom$"),$=new RegExp("^"+Q+"custom$"),G=function(o,r){return _(r).reduce(function(e,t){var n;return h(h({},e),((n={})[""+o+t]=r[t],n))},{})},K=(X.prototype.sendEvent=function(i,s){return n(this,void 0,void 0,function(){var t,n,o,r;return v(this,function(e){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');return t=this.opts.baseUrl,n=this.encodeForEventType(i,s),o=this.getQueryParamsForEventType(i),r=t+"/analytics/"+i+"?"+o,console.log('Sending beacon for "'+i+'" with: ',JSON.stringify(s)),navigator.sendBeacon(r,new Blob([n],{type:"application/x-www-form-urlencoded"})),[2]})})},X.prototype.encodeForEventType=function(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(h({access_token:this.opts.token},t))},X.prototype.getQueryParamsForEventType=function(e){var t=this.opts,n=t.token,o=t.visitorIdProvider.currentVisitorId;return[n&&this.isEventTypeLegacy(e)?"access_token="+n:"",o?"visitorId="+o:""].filter(function(e){return!!e}).join("&")},X.prototype.isEventTypeLegacy=function(e){return-1!==[o.click,o.custom,o.search,o.view].indexOf(e)},X.prototype.encodeForLegacyType=function(e,t){return e+"Event="+encodeURIComponent(JSON.stringify(t))},X.prototype.encodeForFormUrlEncoded=function(t){var n=this;return Object.keys(t).filter(function(e){return!!t[e]}).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(n.encodeValue(t[e]))}).join("&")},X.prototype.encodeValue=function(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)},X);function X(e){this.opts=e}var Z=(ee.prototype.sendEvent=function(e,t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,Promise.resolve()]})})},ee);function ee(){}var te=function(e,t){c()&&u()?this.storage=new b:c()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new S),this.beaconClient=new K(e),window.addEventListener("beforeunload",function(){return t()})},ne=function(){this.storage=new S,this.beaconClient=new Z},oe=function(){this.storage=new S,this.beaconClient=new Z},re={default:"https://platform.cloud.coveo.com/rest/ua",production:"https://platform.cloud.coveo.com/rest/ua",hipaa:"https://platformhipaa.cloud.coveo.com/rest/ua"},ie=(Object.defineProperty(se.prototype,"defaultOptions",{get:function(){return{endpoint:re.default,token:"",version:"v15"}},enumerable:!0,configurable:!0}),se.prototype.initRuntime=function(e){var t=this;return"undefined"!=typeof window&&"undefined"!=typeof document?new te(e,function(){return t.flushBufferWithBeacon()}):new ne},Object.defineProperty(se.prototype,"analyticsBeaconClient",{get:function(){return this.runtime.beaconClient},enumerable:!0,configurable:!0}),Object.defineProperty(se.prototype,"storage",{get:function(){return this.runtime.storage},enumerable:!0,configurable:!0}),se.prototype.initVisitorId=function(){var e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||F()},Object.defineProperty(se.prototype,"currentVisitorId",{get:function(){return this.visitorId},set:function(e){this.visitorId=e,this.storage.setItem("visitorId",e)},enumerable:!0,configurable:!0}),se.prototype.sendEvent=function(f){for(var d=[],e=1;e<arguments.length;e++)d[e-1]=arguments[e];return n(this,void 0,void 0,function(){var t,n,o,r,i,s,a,c,u,l,p=this;return v(this,function(e){switch(e.label){case 0:return t=this.eventTypeMapping[f]||{},o=void 0===(n=t.newEventType)?f:n,i=void 0===(r=t.variableLengthArgumentsNames)?[]:r,a=void 0!==(s=t.addVisitorIdParameter)&&s,u=void 0!==(c=t.usesMeasurementProtocol)&&c,l=[function(e){return 0<i.length?p.parseVariableArgumentsPayload(i,e):e[0]},function(e){return h({visitorId:a?p.visitorId:""},e)},function(e){return p.beforeSendHooks.reduce(function(e,t){return t(f,e)},e)},function(e){return p.removeEmptyPayloadValues(e,f)},function(e){return p.validateParams(e)},function(e){return u?_(r=e).reduce(function(e,t){var n,o=N[t]||t;return h(h({},e),((n={})[o]=r[t],n))},{}):e;var r},function(e){return u?p.removeUnknownParameters(e):e},function(e){return u?p.processCustomParameters(e):e}].reduce(function(e,t){return t(e)},d),this.bufferedRequests.push({eventType:o,payload:l,handled:!1}),[4,this.deferExecution()];case 1:return e.sent(),[4,this.sendFromBufferWithFetch()];case 2:return[2,e.sent()]}})})},se.prototype.deferExecution=function(){return new Promise(function(e){return setTimeout(e,0)})},se.prototype.flushBufferWithBeacon=function(){for(;this.hasPendingRequests();){var e=this.bufferedRequests.pop(),t=e.eventType,n=e.payload;this.analyticsBeaconClient.sendEvent(t,n)}},se.prototype.sendFromBufferWithFetch=function(){return n(this,void 0,void 0,function(){var t,n,o;return v(this,function(e){return(t=this.bufferedRequests.shift())?(n=t.eventType,o=t.payload,[2,this.analyticsFetchClient.sendEvent(n,o)]):[2]})})},se.prototype.hasPendingRequests=function(){return 0<this.bufferedRequests.length},se.prototype.clear=function(){this.storage.removeItem("visitorId"),(new P).clear()},se.prototype.sendSearchEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.search,t)]})})},se.prototype.sendClickEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.click,t)]})})},se.prototype.sendCustomEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.custom,t)]})})},se.prototype.sendViewEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.view,t)]})})},se.prototype.getVisit=function(){return n(this,void 0,void 0,function(){var t;return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/visit")];case 1:return[4,e.sent().json()];case 2:return t=e.sent(),this.visitorId=t.visitorId,[2,t]}})})},se.prototype.getHealth=function(){return n(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/monitoring/health")];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}})})},se.prototype.registerBeforeSendEventHook=function(e){this.beforeSendHooks.push(e)},se.prototype.addEventTypeMapping=function(e,t){this.eventTypeMapping[e]=t},se.prototype.parseVariableArgumentsPayload=function(e,t){for(var n={},o=0,r=t.length;o<r;o++){var i=t[o];if("string"==typeof i)n[e[o]]=i;else if("object"==typeof i)return h(h({},n),i)}return n},se.prototype.isKeyAllowedEmpty=function(e,t){var n;return-1!==((n={})[o.search]=["queryText"],(n[e]||[]).indexOf(t))},se.prototype.removeEmptyPayloadValues=function(o,n){var r=this;return Object.keys(o).filter(function(e){return r.isKeyAllowedEmpty(n,e)||null!=(t=o[e])&&""!==t;var t}).reduce(function(e,t){var n;return h(h({},e),((n={})[t]=o[t],n))},{})},se.prototype.removeUnknownParameters=function(o){return Object.keys(o).filter(function(e){if(A(e))return!0;console.log(e,"is not processed by coveoua")}).reduce(function(e,t){var n;return h(h({},e),((n={})[t]=o[t],n))},{})},se.prototype.processCustomParameters=function(e){var i,t=e.custom,n=s(e,["custom"]),o=_(i=n).reduce(function(e,t){var n,o=J.exec(t)||$.exec(t);if(o){var r=o[1];return h(h({},e),G(r,i[t]))}return h(h({},e),((n={})[t]=i[t],n))},{});return h(h({},t||{}),o)},se.prototype.validateParams=function(e){var t=e.anonymizeIp,n=s(e,["anonymizeIp"]);return void 0!==t&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+t).toLowerCase())&&(n.anonymizeIp=1),n},Object.defineProperty(se.prototype,"baseUrl",{get:function(){var e=this.options,t=e.version,n=e.endpoint,o=-1!==n.indexOf(".cloud.coveo.com");return n+(o?"":"/rest")+"/"+t},enumerable:!0,configurable:!0}),se);function se(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=h(h({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[T,p],this.eventTypeMapping={};var t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new r(t),this.initVisitorId()}var ae=Object.freeze({__proto__:null,Version:"v15",Endpoints:re,CoveoAnalyticsClient:ie,default:ie}),ce=i()?[!0,"yes","1"].indexOf(navigator.doNotTrack||navigator.msDoNotTrack||window.doNotTrack):0,ue=Object.freeze({__proto__:null,doNotTrack:ce,default:ce}),le=(pe.prototype.register=function(e,t){this.plugins[e]=t},pe.prototype.execute=function(e,t){for(var n=[],o=2;o<arguments.length;o++)n[o-2]=arguments[o];var r=this.plugins[e];return r[t].apply(r,n)},pe);function pe(){this.plugins={}}function fe(e){return e.protocol+"//"+e.hostname+(0===e.pathname.indexOf("/")?e.pathname:"/"+e.pathname)+e.search}var de={pageview:"pageview",event:"event"},he=Object.keys(de).map(function(e){return de[e]}),ve=(ge.prototype.addProduct=function(e){this.products.push(e)},ge.prototype.addImpression=function(e){this.impressions.push(e)},ge.prototype.setAction=function(e,t){this.action=e,this.actionData=t},ge.prototype.clearData=function(){this.products=[],this.impressions=[],this.action=void 0,this.actionData={}},ge.prototype.addHooksForECEvents=function(){var r=this;this.client.registerBeforeSendEventHook(function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var o=t[0];return-1!==he.indexOf(e)?r.addECDataToPayload(e,o):o})},ge.prototype.addHooksForPageView=function(){this.client.addEventTypeMapping(de.pageview,{newEventType:o.collect,variableLengthArgumentsNames:["page"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ge.prototype.addHooksForEvent=function(){this.client.addEventTypeMapping(de.event,{newEventType:o.collect,variableLengthArgumentsNames:["eventCategory","eventAction","eventLabel","eventValue"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ge.prototype.addECDataToPayload=function(e,t){var n=h(h(h(h({},this.getLocationInformation(e,t)),this.getDefaultContextInformation(e)),this.action?{action:this.action}:{}),this.actionData||{}),o=this.products.reduce(function(e,t,n){return h(h({},e),(i=n,_(r=t).reduce(function(e,t){var n,o="pr"+(i+1)+(V[t]||t);return h(h({},e),((n={})[o]=r[t],n))},{})));var r,i},{}),r=this.getImpressionsByList().reduce(function(e,t,n){return h(h({},e),function(e,o){var t=e.impressions.reduce(function(e,t,n){return h(h({},e),U(t,o,n))},{});return e.listName&&(t["il"+(o+1)+"nm"]=e.listName),t}(t,n))},{});return this.clearData(),h(h(h(h({},r),o),n),t)},ge.prototype.getImpressionsByList=function(){return this.impressions.reduce(function(e,t){var n=t.list,o=s(t,["list"]),r=e.find(function(e){return e.listName===n});return r?r.impressions.push(o):e.push({listName:n,impressions:[o]}),e},[])},ge.prototype.updateStateForNewPageView=function(e){this.hasSentFirstPageView&&(this.pageViewId=this.uuidGenerator(),this.lastReferrer=this.lastLocation),e.page?this.lastLocation=""+this.lastLocation.split("/").slice(0,3).join("/")+e.page.replace(/^\/?(.*)$/,"/$1"):this.lastLocation=fe(window.location),this.hasSentFirstPageView=!0},ge.prototype.getLocationInformation=function(e,t){return e===de.pageview&&this.updateStateForNewPageView(t),{referrer:this.lastReferrer,location:this.lastLocation}},ge.prototype.getDefaultContextInformation=function(e){var t={hitType:e,pageViewId:this.pageViewId},n={title:document.title,encoding:document.characterSet},o={screenResolution:screen.width+"x"+screen.height,screenColor:screen.colorDepth+"-bit"},r={language:navigator.language,userAgent:navigator.userAgent},i={time:Date.now().toString(),eventId:this.uuidGenerator()};return h(h(h(h(h({},t),i),o),r),n)},ge);function ge(e){var t=e.client,n=e.uuidGenerator,o=void 0===n?F:n;this.products=[],this.impressions=[],this.actionData={},this.client=t,this.uuidGenerator=o,this.pageViewId=o(),this.lastLocation=fe(window.location),this.lastReferrer=document.referrer,this.addHooksForPageView(),this.addHooksForEvent(),this.addHooksForECEvents()}var ye=(me.prototype.init=function(e,t){var n=this;if(!e)throw new Error("You must pass your token when you call 'init'");if("string"==typeof e?(t=t||re.default,this.client=new ie({token:e,endpoint:t})):"object"==typeof e&&void 0!==e.sendEvent&&(this.client=e),!this.client)throw new Error("You must pass either your token or a valid object when you call 'init'");this.plugins.register("ec",new ve({client:this.client})),this.client.registerBeforeSendEventHook(function(e,t){return h(h({},t),n.params)})},me.prototype.initForProxy=function(e){if(!e)throw new Error("You must pass your endpoint when you call 'initForProxy'");if("string"!=typeof e)throw new Error("You must pass a string as the endpoint parameter when you call 'initForProxy'");this.client=new ie({endpoint:e})},me.prototype.set=function(t,e){var n=this;"string"==typeof t?this.params[t]=e:Object.keys(t).map(function(e){n.params[e]=t[e]})},me.prototype.send=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var o=t[0],r=t.slice(1);if(void 0===this.client)throw new Error("You must call init before sending an event");if(!o)throw new Error('You must provide an event type when calling "send".');return(e=this.client).sendEvent.apply(e,a([o.toLowerCase()],r))},me.prototype.onLoad=function(e){if(void 0===e)throw new Error("You must pass a function when you call 'onLoad'");e()},me.prototype.callPlugin=function(e,t){for(var n,o=[],r=2;r<arguments.length;r++)o[r-2]=arguments[r];(n=this.plugins).execute.apply(n,a([e,t],o))},me.prototype.reset=function(){this.client=void 0,this.plugins=new le,this.params={}},me);function me(){this.plugins=new le,this.params={}}function we(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var o=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/.exec(e),r=(o[1],o[2]),i=o[3],s=Ie[i];if(r&&i)return Ie.callPlugin.apply(Ie,a([r,i],t));if(s)return s.apply(Ie,t);throw new Error('The action "'+e+'" does not exist. Available actions: '+["init","set","send","onLoad","callPlugin"].join(", ")+".")}var be,Ee,Se,Ie=new ye,Ce=Object.freeze({__proto__:null,CoveoUA:ye,coveoua:Ie,handleOneAnalyticsEvent:we,default:we});(Se=Ee=Ee||{}).interfaceLoad="interfaceLoad",Se.interfaceChange="interfaceChange",Se.didyoumeanAutomatic="didyoumeanAutomatic",Se.didyoumeanClick="didyoumeanClick",Se.resultsSort="resultsSort",Se.searchboxSubmit="searchboxSubmit",Se.searchboxClear="searchboxClear",Se.searchboxAsYouType="searchboxAsYouType",Se.breadcrumbFacet="breadcrumbFacet",Se.breadcrumbResetAll="breadcrumbResetAll",Se.documentQuickview="documentQuickview",Se.documentOpen="documentOpen",Se.omniboxAnalytics="omniboxAnalytics",Se.omniboxFromLink="omniboxFromLink",Se.triggerNotify="notify",Se.triggerExecute="execute",Se.triggerQuery="query",Se.triggerRedirect="redirect",Se.pagerResize="pagerResize",Se.pagerNumber="pagerNumber",Se.pagerNext="pagerNext",Se.pagerPrevious="pagerPrevious",Se.pagerScrolling="pagerScrolling",Se.facetClearAll="facetClearAll",Se.facetSearch="facetSearch",Se.facetSelect="facetSelect",Se.facetSelectAll="facetSelectAll",Se.facetDeselect="facetDeselect",Se.facetExclude="facetExclude",Se.facetUnexclude="facetUnexclude",Se.facetUpdateSort="facetUpdateSort",Se.facetShowMore="showMoreFacetResults",Se.facetShowLess="showLessFacetResults",Se.queryError="query";var xe=((be={})[Ee.triggerNotify]="queryPipelineTriggers",be[Ee.triggerExecute]="queryPipelineTriggers",be[Ee.triggerQuery]="queryPipelineTriggers",be[Ee.triggerRedirect]="queryPipelineTriggers",be[Ee.queryError]="errors",be[Ee.pagerNext]="getMoreResults",be[Ee.pagerPrevious]="getMoreResults",be[Ee.pagerNumber]="getMoreResults",be[Ee.pagerResize]="getMoreResults",be[Ee.pagerScrolling]="getMoreResults",be[Ee.facetSearch]="facet",be[Ee.facetShowLess]="facet",be[Ee.facetShowMore]="facet",be),Pe=(ke.prototype.sendEvent=function(){return Promise.resolve()},ke.prototype.sendSearchEvent=function(){return Promise.resolve()},ke.prototype.sendClickEvent=function(){return Promise.resolve()},ke.prototype.sendCustomEvent=function(){return Promise.resolve()},ke.prototype.sendViewEvent=function(){return Promise.resolve()},ke.prototype.getVisit=function(){return Promise.resolve({id:"",visitorId:""})},ke.prototype.getHealth=function(){return Promise.resolve({status:""})},ke.prototype.registerBeforeSendEventHook=function(){},ke.prototype.addEventTypeMapping=function(){},ke);function ke(){this.runtime=new oe}var Te=(Ae.prototype.disable=function(){this.coveoAnalyticsClient instanceof ie&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new Pe},Ae.prototype.enable=function(){this.coveoAnalyticsClient=new ie(this.opts)},Ae.prototype.logInterfaceLoad=function(){return this.logSearchEvent(Ee.interfaceLoad)},Ae.prototype.logInterfaceChange=function(e){return this.logSearchEvent(Ee.interfaceChange,e)},Ae.prototype.logDidYouMeanAutomatic=function(){return this.logSearchEvent(Ee.didyoumeanAutomatic)},Ae.prototype.logDidYouMeanClick=function(){return this.logSearchEvent(Ee.didyoumeanClick)},Ae.prototype.logResultsSort=function(e){return this.logSearchEvent(Ee.resultsSort,e)},Ae.prototype.logSearchboxSubmit=function(){return this.logSearchEvent(Ee.searchboxSubmit)},Ae.prototype.logSearchboxClear=function(){return this.logSearchEvent(Ee.searchboxClear)},Ae.prototype.logSearchboxAsYouType=function(){return this.logSearchEvent(Ee.searchboxAsYouType)},Ae.prototype.logBreadcrumbFacet=function(e){return this.logSearchEvent(Ee.breadcrumbFacet,e)},Ae.prototype.logBreadcrumbResetAll=function(){return this.logSearchEvent(Ee.breadcrumbResetAll)},Ae.prototype.logDocumentQuickview=function(e,t){return this.logClickEvent(Ee.documentQuickview,e,t)},Ae.prototype.logDocumentOpen=function(e,t){return this.logClickEvent(Ee.documentOpen,e,t)},Ae.prototype.logOmniboxAnalytics=function(e){return this.logSearchEvent(Ee.omniboxAnalytics,e)},Ae.prototype.logOmniboxFromLink=function(e){return this.logSearchEvent(Ee.omniboxFromLink,e)},Ae.prototype.logTriggerNotify=function(e){return this.logCustomEvent(Ee.triggerNotify,e)},Ae.prototype.logTriggerExecute=function(e){return this.logCustomEvent(Ee.triggerExecute,e)},Ae.prototype.logTriggerQuery=function(){var e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(Ee.triggerQuery,e)},Ae.prototype.logTriggerRedirect=function(e){var t=h(h({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(Ee.triggerRedirect,t)},Ae.prototype.logPagerResize=function(e){return this.logCustomEvent(Ee.pagerResize,e)},Ae.prototype.logPagerNumber=function(e){return this.logCustomEvent(Ee.pagerNumber,e)},Ae.prototype.logPagerNext=function(e){return this.logCustomEvent(Ee.pagerNext,e)},Ae.prototype.logPagerPrevious=function(e){return this.logCustomEvent(Ee.pagerPrevious,e)},Ae.prototype.logPagerScrolling=function(){return this.logCustomEvent(Ee.pagerScrolling)},Ae.prototype.logFacetClearAll=function(e){return this.logSearchEvent(Ee.facetClearAll,e)},Ae.prototype.logFacetSearch=function(e){return this.logSearchEvent(Ee.facetSearch,e)},Ae.prototype.logFacetSelect=function(e){return this.logSearchEvent(Ee.facetSelect,e)},Ae.prototype.logFacetDeselect=function(e){return this.logSearchEvent(Ee.facetDeselect,e)},Ae.prototype.logFacetExclude=function(e){return this.logSearchEvent(Ee.facetExclude,e)},Ae.prototype.logFacetUnexclude=function(e){return this.logSearchEvent(Ee.facetUnexclude,e)},Ae.prototype.logFacetSelectAll=function(e){return this.logSearchEvent(Ee.facetSelectAll,e)},Ae.prototype.logFacetUpdateSort=function(e){return this.logSearchEvent(Ee.facetUpdateSort,e)},Ae.prototype.logFacetShowMore=function(e){return this.logCustomEvent(Ee.facetShowMore,e)},Ae.prototype.logFacetShowLess=function(e){return this.logCustomEvent(Ee.facetShowLess,e)},Ae.prototype.logQueryError=function(e){return this.logCustomEvent(Ee.queryError,e)},Ae.prototype.logCustomEvent=function(e,t){var n=h(h({},this.provider.getBaseMetadata()),t),o={eventType:xe[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:n};return this.coveoAnalyticsClient.sendCustomEvent(o)},Ae.prototype.logSearchEvent=function(e,t){var n=h(h({},this.provider.getBaseMetadata()),t),o=h(h({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:n,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(o)},Ae.prototype.logClickEvent=function(e,t,n,o){var r=h(h(h({},this.provider.getBaseMetadata()),n),o),i=h(h({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:r});return this.coveoAnalyticsClient.sendClickEvent(i)},Ae);function Ae(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new Pe:new ie(e)}var Oe=Object.freeze({__proto__:null,analytics:ae,donottrack:ue,history:O,SimpleAnalytics:Ce,storage:C,CoveoAnalyticsClient:ie,CoveoUA:ye,handleOneAnalyticsEvent:we,CoveoSearchPageClient:Te});window.Promise instanceof Function||console.error('This script uses window.Promise which is not supported in your browser. Consider adding a polyfill like "es6-promise".'),window.fetch instanceof Function||console.error('This script uses window.fetch which is not supported in your browser. Consider adding a polyfill like "fetch".');var Re=self.coveoua||we;self.coveoua=we,self.coveoanalytics=Oe,Re.q&&a(Re.q.filter(function(e){return"init"===e[0]}),Re.q.filter(function(e){return"init"!==e[0]})).forEach(function(e){return we.apply(void 0,e)});return self.coveoua}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).coveoua=t()}(this,function(){"use strict";var n,e,d=function(){return(d=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function s(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function r(e,s,a,u){return new(a=a||Promise)(function(r,t){function n(e){try{i(u.next(e))}catch(e){t(e)}}function o(e){try{i(u.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?r(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(n,o)}i((u=u.apply(e,s||[])).next())})}function v(r,n){var o,i,s,e,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return e={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(o)throw new TypeError("Generator is already executing.");for(;a;)try{if(o=1,i&&(s=2&t[0]?i.return:t[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,t[1])).done)return s;switch(i=0,s&&(t=[2&t[0],s.value]),t[0]){case 0:case 1:s=t;break;case 4:return a.label++,{value:t[1],done:!1};case 5:a.label++,i=t[1],t=[0];continue;case 7:t=a.ops.pop(),a.trys.pop();continue;default:if(!(s=0<(s=a.trys).length&&s[s.length-1])&&(6===t[0]||2===t[0])){a=0;continue}if(3===t[0]&&(!s||t[1]>s[0]&&t[1]<s[3])){a.label=t[1];break}if(6===t[0]&&a.label<s[1]){a.label=s[1],s=t;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(t);break}s[2]&&a.ops.pop(),a.trys.pop();continue}t=n.call(r,a)}catch(e){t=[6,e],i=0}finally{o=s=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function a(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),o=0;for(t=0;t<r;t++)for(var i=arguments[t],s=0,a=i.length;s<a;s++,o++)n[o]=i[s];return n}(e=n=n||{}).search="search",e.click="click",e.custom="custom",e.view="view",e.collect="collect";var o=(t.prototype.sendEvent=function(a,u){return r(this,void 0,void 0,function(){var t,r,n,o,i,s;return v(this,function(e){switch(e.label){case 0:return t=this.opts,r=t.baseUrl,n=t.visitorIdProvider,o=this.shouldAppendVisitorId(a)?this.visitorIdParam:"",[4,fetch(r+"/analytics/"+a+o,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(u),credentials:"include"})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return(s=e.sent()).visitorId&&(n.currentVisitorId=s.visitorId),[2,s];case 3:try{i.json()}catch(e){}throw console.error('An error has occured when sending the "'+a+'" event.',i,u),new Error('An error has occurred when sending the "'+a+'" event. Check the console logs for more details.')}})})},t.prototype.shouldAppendVisitorId=function(e){return-1!==[n.click,n.custom,n.search,n.view].indexOf(e)},Object.defineProperty(t.prototype,"visitorIdParam",{get:function(){var e=this.opts.visitorIdProvider.currentVisitorId;return e?"?visitor="+e:""},enumerable:!0,configurable:!0}),t.prototype.getHeaders=function(){var e=this.opts.token;return d(d({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})},t);function t(e){this.opts=e}function i(){return"undefined"!=typeof navigator}function u(){return"undefined"!=typeof localStorage}function c(){return i()&&navigator.cookieEnabled}function l(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}function p(e,t){return-1!==f.indexOf(e)?d({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t}var f=[n.click,n.custom,n.search,n.view],h=(y.set=function(e,t,r){var n,o,i,s,a;s=r?((i=new Date).setTime(i.getTime()+r),"; expires="+i.toGMTString()):"",-1===(a=location.hostname).indexOf(".")?document.cookie=e+"="+t+s+"; path=/":((o=a.split(".")).shift(),n="."+o.join("."),document.cookie=e+"="+t+s+"; path=/; domain="+n,null!=y.get(e)&&y.get(e)==t||(n="."+a,document.cookie=e+"="+t+s+"; path=/; domain="+n))},y.get=function(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){var o=r[n];if(0==(o=o.replace(/^\s+/,"")).indexOf(t))return o.substring(t.length,o.length)}return null},y.erase=function(e){y.set(e,"",-1)},y);function y(){}function g(){return u()?localStorage:c()?new m:"undefined"!=typeof sessionStorage?sessionStorage:new S}var m=(w.prototype.getItem=function(e){return h.get(""+w.prefix+e)},w.prototype.removeItem=function(e){h.erase(""+w.prefix+e)},w.prototype.setItem=function(e,t){h.set(""+w.prefix+e,t)},w.prefix="coveo_",w);function w(){}var E=(b.prototype.getItem=function(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)},b.prototype.removeItem=function(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)},b.prototype.setItem=function(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)},b);function b(){this.cookieStorage=new m}var S=(C.prototype.getItem=function(e){return null},C.prototype.removeItem=function(e){},C.prototype.setItem=function(e,t){},C);function C(){}var I=Object.freeze({__proto__:null,preferredStorage:null,getAvailableStorage:g,CookieStorage:m,CookieAndLocalStorage:E,NullStorage:S}),x="__coveo.analytics.history",k=(P.prototype.addElement=function(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);var t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])},P.prototype.getHistory=function(){var e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)},P.prototype.getHistoryWithInternalTime=function(){try{var e=this.store.getItem(x);return e?JSON.parse(e):[]}catch(e){return[]}},P.prototype.setHistory=function(e){try{this.store.setItem(x,JSON.stringify(e.slice(0,20)))}catch(e){}},P.prototype.clear=function(){try{this.store.removeItem(x)}catch(e){}},P.prototype.getMostRecentElement=function(){var e=this.getHistoryWithInternalTime();return null==e?null:e.sort(function(e,t){return(t.internalTime||0)-(e.internalTime||0)})[0]},P.prototype.cropQueryElement=function(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))},P.prototype.isValidEntry=function(e){var t=this.getMostRecentElement();return!t||t.value!=e.value||6e4<(e.internalTime||0)-(t.internalTime||0)},P.prototype.stripInternalTime=function(e){return e.map(function(e){return{name:e.name,time:e.time,value:e.value}})},P);function P(e){this.store=e||g(),this.store instanceof m||!c()||(new m).removeItem(x)}function A(e,t){return e===n.view?(R(t.contentIdValue),d({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t}function T(t){return[function(e){return Y.test(e)},function(e){return W.test(e)},function(e){return-1!==U.indexOf(e)},function(e){return"custom"===e}].some(function(e){return e(t)})}var O=Object.freeze({__proto__:null,STORE_KEY:x,MAX_NUMBER_OF_HISTORY_ELEMENTS:20,MIN_THRESHOLD_FOR_DUPLICATE_VALUE:6e4,MAX_VALUE_SIZE:75,HistoryStore:k,default:k}),R=function(e){var t=new k,r={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(r)},F=function(e){return e?(Number(e)^L(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):(""+1e7+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,F)},L=function(e){if(l())return crypto.getRandomValues(e);for(var t=0,r=0;t<e.length;t++)0==(3&t)&&(r=4294967296*Math.random()),e[t]=r>>>((3&t)<<3)&255;return e},V={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},q={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},j=d(d(d(d(d({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),N=Object.keys,_=function(o,i,s){return N(o).reduce(function(e,t){var r,n="il"+(i+1)+"pi"+(s+1)+(q[t]||t);return d(d({},e),((r={})[n]=o[t],r))},{})},U=N(j).map(function(e){return j[e]}),M=N(V).map(function(e){return V[e]}),B=N(q).map(function(e){return q[e]}),D=a(M,["custom"]).join("|"),H=a(B,["custom"]).join("|"),Q="(pr[0-9]+)",z="(il[0-9]+pi[0-9]+)",Y=new RegExp("^"+Q+"("+D+")$"),W=new RegExp("^("+z+"("+H+"))|(il[0-9]+nm)$"),J=new RegExp("^"+Q+"custom$"),$=new RegExp("^"+z+"custom$"),G=function(n,o){return N(o).reduce(function(e,t){var r;return d(d({},e),((r={})[""+n+t]=o[t],r))},{})},K=(X.prototype.sendEvent=function(i,s){return r(this,void 0,void 0,function(){var t,r,n,o;return v(this,function(e){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');return t=this.opts.baseUrl,r=this.encodeForEventType(i,s),n=this.getQueryParamsForEventType(i),o=t+"/analytics/"+i+"?"+n,console.log('Sending beacon for "'+i+'" with: ',JSON.stringify(s)),navigator.sendBeacon(o,new Blob([r],{type:"application/x-www-form-urlencoded"})),[2]})})},X.prototype.encodeForEventType=function(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(d({access_token:this.opts.token},t))},X.prototype.getQueryParamsForEventType=function(e){var t=this.opts,r=t.token,n=t.visitorIdProvider.currentVisitorId;return[r&&this.isEventTypeLegacy(e)?"access_token="+r:"",n?"visitorId="+n:""].filter(function(e){return!!e}).join("&")},X.prototype.isEventTypeLegacy=function(e){return-1!==[n.click,n.custom,n.search,n.view].indexOf(e)},X.prototype.encodeForLegacyType=function(e,t){return e+"Event="+encodeURIComponent(JSON.stringify(t))},X.prototype.encodeForFormUrlEncoded=function(t){var r=this;return Object.keys(t).filter(function(e){return!!t[e]}).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(r.encodeValue(t[e]))}).join("&")},X.prototype.encodeValue=function(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)},X);function X(e){this.opts=e}var Z=(ee.prototype.sendEvent=function(e,t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,Promise.resolve()]})})},ee);function ee(){}var te=function(e,t){u()&&c()?this.storage=new E:u()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new S),this.beaconClient=new K(e),window.addEventListener("beforeunload",function(){return t()})},re=function(){this.storage=new S,this.beaconClient=new Z},ne=function(){this.storage=new S,this.beaconClient=new Z},oe={default:"https://platform.cloud.coveo.com/rest/ua",production:"https://platform.cloud.coveo.com/rest/ua",hipaa:"https://platformhipaa.cloud.coveo.com/rest/ua"},ie=(Object.defineProperty(se.prototype,"defaultOptions",{get:function(){return{endpoint:oe.default,token:"",version:"v15"}},enumerable:!0,configurable:!0}),se.prototype.initRuntime=function(e){var t=this;return"undefined"!=typeof window&&"undefined"!=typeof document?new te(e,function(){return t.flushBufferWithBeacon()}):new re},Object.defineProperty(se.prototype,"analyticsBeaconClient",{get:function(){return this.runtime.beaconClient},enumerable:!0,configurable:!0}),Object.defineProperty(se.prototype,"storage",{get:function(){return this.runtime.storage},enumerable:!0,configurable:!0}),se.prototype.initVisitorId=function(){var e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||F()},Object.defineProperty(se.prototype,"currentVisitorId",{get:function(){return this.visitorId},set:function(e){this.visitorId=e,this.storage.setItem("visitorId",e)},enumerable:!0,configurable:!0}),se.prototype.sendEvent=function(f){for(var h=[],e=1;e<arguments.length;e++)h[e-1]=arguments[e];return r(this,void 0,void 0,function(){var t,r,n,o,i,s,a,u,c,l,p=this;return v(this,function(e){switch(e.label){case 0:return t=this.eventTypeMapping[f]||{},n=void 0===(r=t.newEventType)?f:r,i=void 0===(o=t.variableLengthArgumentsNames)?[]:o,a=void 0!==(s=t.addVisitorIdParameter)&&s,c=void 0!==(u=t.usesMeasurementProtocol)&&u,l=[function(e){return 0<i.length?p.parseVariableArgumentsPayload(i,e):e[0]},function(e){return d({visitorId:a?p.visitorId:""},e)},function(e){return c?p.ensureAnonymousUserWhenUsingApiKey(e):e},function(e){return p.beforeSendHooks.reduce(function(e,t){return t(f,e)},e)},function(e){return p.removeEmptyPayloadValues(e,f)},function(e){return p.validateParams(e)},function(e){return c?N(o=e).reduce(function(e,t){var r,n=j[t]||t;return d(d({},e),((r={})[n]=o[t],r))},{}):e;var o},function(e){return c?p.removeUnknownParameters(e):e},function(e){return c?p.processCustomParameters(e):e}].reduce(function(e,t){return t(e)},h),this.bufferedRequests.push({eventType:n,payload:l,handled:!1}),[4,this.deferExecution()];case 1:return e.sent(),[4,this.sendFromBufferWithFetch()];case 2:return[2,e.sent()]}})})},se.prototype.deferExecution=function(){return new Promise(function(e){return setTimeout(e,0)})},se.prototype.flushBufferWithBeacon=function(){for(;this.hasPendingRequests();){var e=this.bufferedRequests.pop(),t=e.eventType,r=e.payload;this.analyticsBeaconClient.sendEvent(t,r)}},se.prototype.sendFromBufferWithFetch=function(){return r(this,void 0,void 0,function(){var t,r,n;return v(this,function(e){return(t=this.bufferedRequests.shift())?(r=t.eventType,n=t.payload,[2,this.analyticsFetchClient.sendEvent(r,n)]):[2]})})},se.prototype.hasPendingRequests=function(){return 0<this.bufferedRequests.length},se.prototype.clear=function(){this.storage.removeItem("visitorId"),(new k).clear()},se.prototype.sendSearchEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.search,t)]})})},se.prototype.sendClickEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.click,t)]})})},se.prototype.sendCustomEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.custom,t)]})})},se.prototype.sendViewEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.view,t)]})})},se.prototype.getVisit=function(){return r(this,void 0,void 0,function(){var t;return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/visit")];case 1:return[4,e.sent().json()];case 2:return t=e.sent(),this.visitorId=t.visitorId,[2,t]}})})},se.prototype.getHealth=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/monitoring/health")];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}})})},se.prototype.registerBeforeSendEventHook=function(e){this.beforeSendHooks.push(e)},se.prototype.addEventTypeMapping=function(e,t){this.eventTypeMapping[e]=t},se.prototype.parseVariableArgumentsPayload=function(e,t){for(var r={},n=0,o=t.length;n<o;n++){var i=t[n];if("string"==typeof i)r[e[n]]=i;else if("object"==typeof i)return d(d({},r),i)}return r},se.prototype.isKeyAllowedEmpty=function(e,t){var r;return-1!==((r={})[n.search]=["queryText"],(r[e]||[]).indexOf(t))},se.prototype.removeEmptyPayloadValues=function(n,r){var o=this;return Object.keys(n).filter(function(e){return o.isKeyAllowedEmpty(r,e)||null!=(t=n[e])&&""!==t;var t}).reduce(function(e,t){var r;return d(d({},e),((r={})[t]=n[t],r))},{})},se.prototype.removeUnknownParameters=function(n){return Object.keys(n).filter(function(e){if(T(e))return!0;console.log(e,"is not processed by coveoua")}).reduce(function(e,t){var r;return d(d({},e),((r={})[t]=n[t],r))},{})},se.prototype.processCustomParameters=function(e){var i,t=e.custom,r=s(e,["custom"]),n=N(i=r).reduce(function(e,t){var r,n=J.exec(t)||$.exec(t);if(n){var o=n[1];return d(d({},e),G(o,i[t]))}return d(d({},e),((r={})[t]=i[t],r))},{});return d(d({},t||{}),n)},se.prototype.validateParams=function(e){var t=e.anonymizeIp,r=s(e,["anonymizeIp"]);return void 0!==t&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+t).toLowerCase())&&(r.anonymizeIp=1),r},se.prototype.ensureAnonymousUserWhenUsingApiKey=function(e){var t,r=e.userId,n=s(e,["userId"]);return null!=(t=this.options.token)&&t.startsWith("xx")&&!r?(n.userId="anonymous",n):e},Object.defineProperty(se.prototype,"baseUrl",{get:function(){var e=this.options,t=e.version,r=e.endpoint,n=-1!==r.indexOf(".cloud.coveo.com");return r+(n?"":"/rest")+"/"+t},enumerable:!0,configurable:!0}),se);function se(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=d(d({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[A,p],this.eventTypeMapping={};var t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new o(t),this.initVisitorId()}var ae=Object.freeze({__proto__:null,Version:"v15",Endpoints:oe,CoveoAnalyticsClient:ie,default:ie}),ue=i()?[!0,"yes","1"].indexOf(navigator.doNotTrack||navigator.msDoNotTrack||window.doNotTrack):0,ce=Object.freeze({__proto__:null,doNotTrack:ue,default:ue}),le=(pe.prototype.register=function(e,t){this.plugins[e]=t},pe.prototype.execute=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=this.plugins[e];return o[t].apply(o,r)},pe);function pe(){this.plugins={}}function fe(e){return e.protocol+"//"+e.hostname+(0===e.pathname.indexOf("/")?e.pathname:"/"+e.pathname)+e.search}var he={pageview:"pageview",event:"event"},de=Object.keys(he).map(function(e){return he[e]}),ve=(ye.prototype.addProduct=function(e){this.products.push(e)},ye.prototype.addImpression=function(e){this.impressions.push(e)},ye.prototype.setAction=function(e,t){this.action=e,this.actionData=t},ye.prototype.clearData=function(){this.products=[],this.impressions=[],this.action=void 0,this.actionData={}},ye.prototype.addHooksForECEvents=function(){var o=this;this.client.registerBeforeSendEventHook(function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=t[0];return-1!==de.indexOf(e)?o.addECDataToPayload(e,n):n})},ye.prototype.addHooksForPageView=function(){this.client.addEventTypeMapping(he.pageview,{newEventType:n.collect,variableLengthArgumentsNames:["page"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ye.prototype.addHooksForEvent=function(){this.client.addEventTypeMapping(he.event,{newEventType:n.collect,variableLengthArgumentsNames:["eventCategory","eventAction","eventLabel","eventValue"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ye.prototype.addECDataToPayload=function(e,t){var r=d(d(d(d({},this.getLocationInformation(e,t)),this.getDefaultContextInformation(e)),this.action?{action:this.action}:{}),this.actionData||{}),n=this.products.reduce(function(e,t,r){return d(d({},e),(i=r,N(o=t).reduce(function(e,t){var r,n="pr"+(i+1)+(V[t]||t);return d(d({},e),((r={})[n]=o[t],r))},{})));var o,i},{}),o=this.getImpressionsByList().reduce(function(e,t,r){return d(d({},e),function(e,n){var t=e.impressions.reduce(function(e,t,r){return d(d({},e),_(t,n,r))},{});return e.listName&&(t["il"+(n+1)+"nm"]=e.listName),t}(t,r))},{});return this.clearData(),d(d(d(d({},o),n),r),t)},ye.prototype.getImpressionsByList=function(){return this.impressions.reduce(function(e,t){var r=t.list,n=s(t,["list"]),o=e.find(function(e){return e.listName===r});return o?o.impressions.push(n):e.push({listName:r,impressions:[n]}),e},[])},ye.prototype.updateStateForNewPageView=function(e){this.hasSentFirstPageView&&(this.pageViewId=this.uuidGenerator(),this.lastReferrer=this.lastLocation),e.page?this.lastLocation=""+this.lastLocation.split("/").slice(0,3).join("/")+e.page.replace(/^\/?(.*)$/,"/$1"):this.lastLocation=fe(window.location),this.hasSentFirstPageView=!0},ye.prototype.getLocationInformation=function(e,t){return e===he.pageview&&this.updateStateForNewPageView(t),{referrer:this.lastReferrer,location:this.lastLocation}},ye.prototype.getDefaultContextInformation=function(e){var t={hitType:e,pageViewId:this.pageViewId},r={title:document.title,encoding:document.characterSet},n={screenResolution:screen.width+"x"+screen.height,screenColor:screen.colorDepth+"-bit"},o={language:navigator.language,userAgent:navigator.userAgent},i={time:Date.now().toString(),eventId:this.uuidGenerator()};return d(d(d(d(d({},t),i),n),o),r)},ye);function ye(e){var t=e.client,r=e.uuidGenerator,n=void 0===r?F:r;this.products=[],this.impressions=[],this.actionData={},this.client=t,this.uuidGenerator=n,this.pageViewId=n(),this.lastLocation=fe(window.location),this.lastReferrer=document.referrer,this.addHooksForPageView(),this.addHooksForEvent(),this.addHooksForECEvents()}var ge=(me.prototype.init=function(e,t){var r=this;if(!e)throw new Error("You must pass your token when you call 'init'");if("string"==typeof e?(t=t||oe.default,this.client=new ie({token:e,endpoint:t})):"object"==typeof e&&void 0!==e.sendEvent&&(this.client=e),!this.client)throw new Error("You must pass either your token or a valid object when you call 'init'");this.plugins.register("ec",new ve({client:this.client})),this.client.registerBeforeSendEventHook(function(e,t){return d(d({},t),r.params)})},me.prototype.initForProxy=function(e){if(!e)throw new Error("You must pass your endpoint when you call 'initForProxy'");if("string"!=typeof e)throw new Error("You must pass a string as the endpoint parameter when you call 'initForProxy'");this.client=new ie({endpoint:e})},me.prototype.set=function(t,e){var r=this;"string"==typeof t?this.params[t]=e:Object.keys(t).map(function(e){r.params[e]=t[e]})},me.prototype.send=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=t[0],o=t.slice(1);if(void 0===this.client)throw new Error("You must call init before sending an event");if(!n)throw new Error('You must provide an event type when calling "send".');return(e=this.client).sendEvent.apply(e,a([n.toLowerCase()],o))},me.prototype.onLoad=function(e){if(void 0===e)throw new Error("You must pass a function when you call 'onLoad'");e()},me.prototype.callPlugin=function(e,t){for(var r,n=[],o=2;o<arguments.length;o++)n[o-2]=arguments[o];(r=this.plugins).execute.apply(r,a([e,t],n))},me.prototype.reset=function(){this.client=void 0,this.plugins=new le,this.params={}},me);function me(){this.plugins=new le,this.params={}}function we(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/.exec(e),o=(n[1],n[2]),i=n[3],s=Ce[i];if(o&&i)return Ce.callPlugin.apply(Ce,a([o,i],t));if(s)return s.apply(Ce,t);throw new Error('The action "'+e+'" does not exist. Available actions: '+["init","set","send","onLoad","callPlugin"].join(", ")+".")}var Ee,be,Se,Ce=new ge,Ie=Object.freeze({__proto__:null,CoveoUA:ge,coveoua:Ce,handleOneAnalyticsEvent:we,default:we});(Se=be=be||{}).interfaceLoad="interfaceLoad",Se.interfaceChange="interfaceChange",Se.didyoumeanAutomatic="didyoumeanAutomatic",Se.didyoumeanClick="didyoumeanClick",Se.resultsSort="resultsSort",Se.searchboxSubmit="searchboxSubmit",Se.searchboxClear="searchboxClear",Se.searchboxAsYouType="searchboxAsYouType",Se.breadcrumbFacet="breadcrumbFacet",Se.breadcrumbResetAll="breadcrumbResetAll",Se.documentQuickview="documentQuickview",Se.documentOpen="documentOpen",Se.omniboxAnalytics="omniboxAnalytics",Se.omniboxFromLink="omniboxFromLink",Se.triggerNotify="notify",Se.triggerExecute="execute",Se.triggerQuery="query",Se.triggerRedirect="redirect",Se.pagerResize="pagerResize",Se.pagerNumber="pagerNumber",Se.pagerNext="pagerNext",Se.pagerPrevious="pagerPrevious",Se.pagerScrolling="pagerScrolling",Se.facetClearAll="facetClearAll",Se.facetSearch="facetSearch",Se.facetSelect="facetSelect",Se.facetSelectAll="facetSelectAll",Se.facetDeselect="facetDeselect",Se.facetExclude="facetExclude",Se.facetUnexclude="facetUnexclude",Se.facetUpdateSort="facetUpdateSort",Se.facetShowMore="showMoreFacetResults",Se.facetShowLess="showLessFacetResults",Se.queryError="query",Se.queryErrorBack="errorBack",Se.queryErrorClear="errorClearQuery",Se.queryErrorRetry="errorRetry";var xe=((Ee={})[be.triggerNotify]="queryPipelineTriggers",Ee[be.triggerExecute]="queryPipelineTriggers",Ee[be.triggerQuery]="queryPipelineTriggers",Ee[be.triggerRedirect]="queryPipelineTriggers",Ee[be.queryError]="errors",Ee[be.queryErrorBack]="errors",Ee[be.queryErrorClear]="errors",Ee[be.queryErrorRetry]="errors",Ee[be.pagerNext]="getMoreResults",Ee[be.pagerPrevious]="getMoreResults",Ee[be.pagerNumber]="getMoreResults",Ee[be.pagerResize]="getMoreResults",Ee[be.pagerScrolling]="getMoreResults",Ee[be.facetSearch]="facet",Ee[be.facetShowLess]="facet",Ee[be.facetShowMore]="facet",Ee),ke=(Pe.prototype.sendEvent=function(){return Promise.resolve()},Pe.prototype.sendSearchEvent=function(){return Promise.resolve()},Pe.prototype.sendClickEvent=function(){return Promise.resolve()},Pe.prototype.sendCustomEvent=function(){return Promise.resolve()},Pe.prototype.sendViewEvent=function(){return Promise.resolve()},Pe.prototype.getVisit=function(){return Promise.resolve({id:"",visitorId:""})},Pe.prototype.getHealth=function(){return Promise.resolve({status:""})},Pe.prototype.registerBeforeSendEventHook=function(){},Pe.prototype.addEventTypeMapping=function(){},Pe);function Pe(){this.runtime=new ne}var Ae=(Te.prototype.disable=function(){this.coveoAnalyticsClient instanceof ie&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new ke},Te.prototype.enable=function(){this.coveoAnalyticsClient=new ie(this.opts)},Te.prototype.logInterfaceLoad=function(){return this.logSearchEvent(be.interfaceLoad)},Te.prototype.logInterfaceChange=function(e){return this.logSearchEvent(be.interfaceChange,e)},Te.prototype.logDidYouMeanAutomatic=function(){return this.logSearchEvent(be.didyoumeanAutomatic)},Te.prototype.logDidYouMeanClick=function(){return this.logSearchEvent(be.didyoumeanClick)},Te.prototype.logResultsSort=function(e){return this.logSearchEvent(be.resultsSort,e)},Te.prototype.logSearchboxSubmit=function(){return this.logSearchEvent(be.searchboxSubmit)},Te.prototype.logSearchboxClear=function(){return this.logSearchEvent(be.searchboxClear)},Te.prototype.logSearchboxAsYouType=function(){return this.logSearchEvent(be.searchboxAsYouType)},Te.prototype.logBreadcrumbFacet=function(e){return this.logSearchEvent(be.breadcrumbFacet,e)},Te.prototype.logBreadcrumbResetAll=function(){return this.logSearchEvent(be.breadcrumbResetAll)},Te.prototype.logDocumentQuickview=function(e,t){return this.logClickEvent(be.documentQuickview,e,t)},Te.prototype.logDocumentOpen=function(e,t){return this.logClickEvent(be.documentOpen,e,t)},Te.prototype.logOmniboxAnalytics=function(e){return this.logSearchEvent(be.omniboxAnalytics,e)},Te.prototype.logOmniboxFromLink=function(e){return this.logSearchEvent(be.omniboxFromLink,e)},Te.prototype.logTriggerNotify=function(e){return this.logCustomEvent(be.triggerNotify,e)},Te.prototype.logTriggerExecute=function(e){return this.logCustomEvent(be.triggerExecute,e)},Te.prototype.logTriggerQuery=function(){var e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(be.triggerQuery,e)},Te.prototype.logTriggerRedirect=function(e){var t=d(d({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(be.triggerRedirect,t)},Te.prototype.logPagerResize=function(e){return this.logCustomEvent(be.pagerResize,e)},Te.prototype.logPagerNumber=function(e){return this.logCustomEvent(be.pagerNumber,e)},Te.prototype.logPagerNext=function(e){return this.logCustomEvent(be.pagerNext,e)},Te.prototype.logPagerPrevious=function(e){return this.logCustomEvent(be.pagerPrevious,e)},Te.prototype.logPagerScrolling=function(){return this.logCustomEvent(be.pagerScrolling)},Te.prototype.logFacetClearAll=function(e){return this.logSearchEvent(be.facetClearAll,e)},Te.prototype.logFacetSearch=function(e){return this.logSearchEvent(be.facetSearch,e)},Te.prototype.logFacetSelect=function(e){return this.logSearchEvent(be.facetSelect,e)},Te.prototype.logFacetDeselect=function(e){return this.logSearchEvent(be.facetDeselect,e)},Te.prototype.logFacetExclude=function(e){return this.logSearchEvent(be.facetExclude,e)},Te.prototype.logFacetUnexclude=function(e){return this.logSearchEvent(be.facetUnexclude,e)},Te.prototype.logFacetSelectAll=function(e){return this.logSearchEvent(be.facetSelectAll,e)},Te.prototype.logFacetUpdateSort=function(e){return this.logSearchEvent(be.facetUpdateSort,e)},Te.prototype.logFacetShowMore=function(e){return this.logCustomEvent(be.facetShowMore,e)},Te.prototype.logFacetShowLess=function(e){return this.logCustomEvent(be.facetShowLess,e)},Te.prototype.logQueryError=function(e){return this.logCustomEvent(be.queryError,e)},Te.prototype.logQueryErrorBack=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(be.queryErrorBack)];case 1:return e.sent(),[2,this.logSearchEvent(be.queryErrorBack)]}})})},Te.prototype.logQueryErrorRetry=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(be.queryErrorRetry)];case 1:return e.sent(),[2,this.logSearchEvent(be.queryErrorRetry)]}})})},Te.prototype.logQueryErrorClear=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(be.queryErrorClear)];case 1:return e.sent(),[2,this.logSearchEvent(be.queryErrorClear)]}})})},Te.prototype.logCustomEvent=function(e,t){var r=d(d({},this.provider.getBaseMetadata()),t),n={eventType:xe[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:r};return this.coveoAnalyticsClient.sendCustomEvent(n)},Te.prototype.logSearchEvent=function(e,t){var r=d(d({},this.provider.getBaseMetadata()),t),n=d(d({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:r,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(n)},Te.prototype.logClickEvent=function(e,t,r,n){var o=d(d(d({},this.provider.getBaseMetadata()),r),n),i=d(d({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:o});return this.coveoAnalyticsClient.sendClickEvent(i)},Te);function Te(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new ke:new ie(e)}var Oe=Object.freeze({__proto__:null,analytics:ae,donottrack:ce,history:O,SimpleAnalytics:Ie,storage:I,CoveoAnalyticsClient:ie,CoveoUA:ge,handleOneAnalyticsEvent:we,CoveoSearchPageClient:Ae});window.Promise instanceof Function||console.error('This script uses window.Promise which is not supported in your browser. Consider adding a polyfill like "es6-promise".'),window.fetch instanceof Function||console.error('This script uses window.fetch which is not supported in your browser. Consider adding a polyfill like "fetch".');var Re=self.coveoua||we;self.coveoua=we,self.coveoanalytics=Oe,Re.q&&a(Re.q.filter(function(e){return"init"===e[0]}),Re.q.filter(function(e){return"init"!==e[0]})).forEach(function(e){return we.apply(void 0,e)});return self.coveoua}); | ||
//# sourceMappingURL=coveoua.js.map |
@@ -70,4 +70,5 @@ import { AnyEventResponse, ClickEventRequest, ClickEventResponse, CustomEventRequest, CustomEventResponse, EventType, HealthResponse, SearchEventRequest, SearchEventResponse, ViewEventRequest, ViewEventResponse, VisitResponse, VariableArgumentsPayload } from '../events'; | ||
private validateParams; | ||
private ensureAnonymousUserWhenUsingApiKey; | ||
private get baseUrl(); | ||
} | ||
export default CoveoAnalyticsClient; |
@@ -53,2 +53,5 @@ import { ClientOptions, AnalyticsClient } from '../client/analytics'; | ||
logQueryError(meta: QueryErrorMeta): Promise<void | import("../events").CustomEventResponse>; | ||
logQueryErrorBack(): Promise<void | import("../events").SearchEventResponse>; | ||
logQueryErrorRetry(): Promise<void | import("../events").SearchEventResponse>; | ||
logQueryErrorClear(): Promise<void | import("../events").SearchEventResponse>; | ||
logCustomEvent(event: SearchPageEvents, metadata?: Record<string, any>): Promise<void | import("../events").CustomEventResponse>; | ||
@@ -55,0 +58,0 @@ logSearchEvent(event: SearchPageEvents, metadata?: Record<string, any>): Promise<void | import("../events").SearchEventResponse>; |
@@ -36,3 +36,6 @@ import { DocumentInformation } from '../events'; | ||
facetShowLess = "showLessFacetResults", | ||
queryError = "query" | ||
queryError = "query", | ||
queryErrorBack = "errorBack", | ||
queryErrorClear = "errorClearQuery", | ||
queryErrorRetry = "errorRetry" | ||
} | ||
@@ -39,0 +42,0 @@ export declare const CustomEventsTypes: Partial<Record<SearchPageEvents, string>>; |
@@ -15,3 +15,3 @@ /*! ***************************************************************************** | ||
***************************************************************************** */ | ||
function e(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function t(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))}var r;!function(e){e.search="search",e.click="click",e.custom="custom",e.view="view",e.collect="collect"}(r||(r={}));class n{constructor(e){this.opts=e}sendEvent(e,r){return t(this,void 0,void 0,(function*(){const{baseUrl:t,visitorIdProvider:n}=this.opts,i=this.shouldAppendVisitorId(e)?this.visitorIdParam:"",o=yield fetch(`${t}/analytics/${e}${i}`,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(r),credentials:"include"});if(o.ok){const e=yield o.json();return e.visitorId&&(n.currentVisitorId=e.visitorId),e}try{o.json()}catch(e){}throw console.error(`An error has occured when sending the "${e}" event.`,o,r),new Error(`An error has occurred when sending the "${e}" event. Check the console logs for more details.`)}))}shouldAppendVisitorId(e){return-1!==[r.click,r.custom,r.search,r.view].indexOf(e)}get visitorIdParam(){const{visitorIdProvider:e}=this.opts,t=e.currentVisitorId;return t?"?visitor="+t:""}getHeaders(){const{token:e}=this.opts;return Object.assign(Object.assign({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})}}function i(){return"undefined"!=typeof localStorage}function o(){return"undefined"!=typeof navigator&&navigator.cookieEnabled}function s(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}const a=[r.click,r.custom,r.search,r.view],c=(e,t)=>-1!==a.indexOf(e)?Object.assign({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t;class l{static set(e,t,r){var n,i,o,s,a;r?((o=new Date).setTime(o.getTime()+r),s="; expires="+o.toGMTString()):s="",-1===(a=location.hostname).indexOf(".")?document.cookie=e+"="+t+s+"; path=/":((i=a.split(".")).shift(),n="."+i.join("."),document.cookie=e+"="+t+s+"; path=/; domain="+n,null!=l.get(e)&&l.get(e)==t||(n="."+a,document.cookie=e+"="+t+s+"; path=/; domain="+n))}static get(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){var i=r[n];if(0==(i=i.replace(/^\s+/,"")).indexOf(t))return i.substring(t.length,i.length)}return null}static erase(e){l.set(e,"",-1)}}function u(){return i()?localStorage:o()?new g:"undefined"!=typeof sessionStorage?sessionStorage:new h}class g{getItem(e){return l.get(`${g.prefix}${e}`)}removeItem(e){l.erase(`${g.prefix}${e}`)}setItem(e,t){l.set(`${g.prefix}${e}`,t)}}g.prefix="coveo_";class d{constructor(){this.cookieStorage=new g}getItem(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)}removeItem(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)}setItem(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)}}class h{getItem(e){return null}removeItem(e){}setItem(e,t){}}const v="__coveo.analytics.history";class m{constructor(e){this.store=e||u(),this.store instanceof g||!o()||(new g).removeItem(v)}addElement(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);let t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])}getHistory(){const e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)}getHistoryWithInternalTime(){try{const e=this.store.getItem(v);return e?JSON.parse(e):[]}catch(e){return[]}}setHistory(e){try{this.store.setItem(v,JSON.stringify(e.slice(0,20)))}catch(e){}}clear(){try{this.store.removeItem(v)}catch(e){}}getMostRecentElement(){let e=this.getHistoryWithInternalTime();if(null!=e){return e.sort((e,t)=>(t.internalTime||0)-(e.internalTime||0))[0]}return null}cropQueryElement(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))}isValidEntry(e){let t=this.getMostRecentElement();return!t||t.value!=e.value||(e.internalTime||0)-(t.internalTime||0)>6e4}stripInternalTime(e){return e.map(e=>{const{name:t,time:r,value:n}=e;return{name:t,time:r,value:n}})}}const p=(e,t)=>e===r.view?(f(t.contentIdValue),Object.assign({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t,f=e=>{const t=new m,r={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(r)},y=e=>e?(Number(e)^b(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,y),b=e=>{if(s())return crypto.getRandomValues(e);for(var t=0,r=0;t<e.length;t++)0==(3&t)&&(r=4294967296*Math.random()),e[t]=r>>>((3&t)<<3)&255;return e},E={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},S={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},w=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),O=Object.keys,I=O(w).map(e=>w[e]),x=O(E).map(e=>E[e]),C=O(S).map(e=>S[e]),j=[...x,"custom"].join("|"),k=[...C,"custom"].join("|"),P=new RegExp(`^(pr[0-9]+)(${j})$`),T=new RegExp(`^((il[0-9]+pi[0-9]+)(${k}))|(il[0-9]+nm)$`),A=new RegExp("^(pr[0-9]+)custom$"),R=new RegExp("^(il[0-9]+pi[0-9]+)custom$"),F=e=>P.test(e),V=e=>T.test(e),$=e=>-1!==I.indexOf(e),U=e=>"custom"===e,q=(e,t)=>O(t).reduce((r,n)=>Object.assign(Object.assign({},r),{[`${e}${n}`]:t[n]}),{});class M{constructor(e){this.opts=e}sendEvent(e,r){return t(this,void 0,void 0,(function*(){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');const{baseUrl:t}=this.opts,n=this.encodeForEventType(e,r),i=this.getQueryParamsForEventType(e),o=`${t}/analytics/${e}?${i}`;console.log(`Sending beacon for "${e}" with: `,JSON.stringify(r)),navigator.sendBeacon(o,new Blob([n],{type:"application/x-www-form-urlencoded"}))}))}encodeForEventType(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(Object.assign({access_token:this.opts.token},t))}getQueryParamsForEventType(e){const{token:t,visitorIdProvider:r}=this.opts,n=r.currentVisitorId;return[t&&this.isEventTypeLegacy(e)?"access_token="+t:"",n?"visitorId="+n:""].filter(e=>!!e).join("&")}isEventTypeLegacy(e){return-1!==[r.click,r.custom,r.search,r.view].indexOf(e)}encodeForLegacyType(e,t){return`${e}Event=${encodeURIComponent(JSON.stringify(t))}`}encodeForFormUrlEncoded(e){return Object.keys(e).filter(t=>!!e[t]).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(this.encodeValue(e[t]))}`).join("&")}encodeValue(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)}}class N{sendEvent(e,r){return t(this,void 0,void 0,(function*(){return Promise.resolve()}))}}class L{constructor(e,t){i()&&o()?this.storage=new d:i()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new h),this.beaconClient=new M(e),window.addEventListener("beforeunload",()=>t())}}class B{constructor(){this.storage=new h,this.beaconClient=new N}}class D{constructor(){this.storage=new h,this.beaconClient=new N}}const H="https://platform.cloud.coveo.com/rest/ua";class Q{constructor(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=Object.assign(Object.assign({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[p,c],this.eventTypeMapping={};const t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new n(t),this.initVisitorId()}get defaultOptions(){return{endpoint:H,token:"",version:"v15"}}initRuntime(e){return"undefined"!=typeof window&&"undefined"!=typeof document?new L(e,()=>this.flushBufferWithBeacon()):new B}get analyticsBeaconClient(){return this.runtime.beaconClient}get storage(){return this.runtime.storage}initVisitorId(){const e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||y()}get currentVisitorId(){return this.visitorId}set currentVisitorId(e){this.visitorId=e,this.storage.setItem("visitorId",e)}sendEvent(e,...r){return t(this,void 0,void 0,(function*(){const{newEventType:t=e,variableLengthArgumentsNames:n=[],addVisitorIdParameter:i=!1,usesMeasurementProtocol:o=!1}=this.eventTypeMapping[e]||{},s=[e=>n.length>0?this.parseVariableArgumentsPayload(n,e):e[0],e=>Object.assign({visitorId:i?this.visitorId:""},e),t=>this.beforeSendHooks.reduce((t,r)=>r(e,t),t),t=>this.removeEmptyPayloadValues(t,e),e=>this.validateParams(e),e=>{return o?O(t=e).reduce((e,r)=>{const n=w[r]||r;return Object.assign(Object.assign({},e),{[n]:t[r]})},{}):e;var t},e=>o?this.removeUnknownParameters(e):e,e=>o?this.processCustomParameters(e):e].reduce((e,t)=>t(e),r);return this.bufferedRequests.push({eventType:t,payload:s,handled:!1}),yield this.deferExecution(),yield this.sendFromBufferWithFetch()}))}deferExecution(){return new Promise(e=>setTimeout(e,0))}flushBufferWithBeacon(){for(;this.hasPendingRequests();){const{eventType:e,payload:t}=this.bufferedRequests.pop();this.analyticsBeaconClient.sendEvent(e,t)}}sendFromBufferWithFetch(){return t(this,void 0,void 0,(function*(){const e=this.bufferedRequests.shift();if(e){const{eventType:t,payload:r}=e;return this.analyticsFetchClient.sendEvent(t,r)}}))}hasPendingRequests(){return this.bufferedRequests.length>0}clear(){this.storage.removeItem("visitorId"),(new m).clear()}sendSearchEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.search,e)}))}sendClickEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.click,e)}))}sendCustomEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.custom,e)}))}sendViewEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.view,e)}))}getVisit(){return t(this,void 0,void 0,(function*(){const e=yield fetch(this.baseUrl+"/analytics/visit"),t=yield e.json();return this.visitorId=t.visitorId,t}))}getHealth(){return t(this,void 0,void 0,(function*(){const e=yield fetch(this.baseUrl+"/analytics/monitoring/health");return yield e.json()}))}registerBeforeSendEventHook(e){this.beforeSendHooks.push(e)}addEventTypeMapping(e,t){this.eventTypeMapping[e]=t}parseVariableArgumentsPayload(e,t){const r={};for(let n=0,i=t.length;n<i;n++){const i=t[n];if("string"==typeof i)r[e[n]]=i;else if("object"==typeof i)return Object.assign(Object.assign({},r),i)}return r}isKeyAllowedEmpty(e,t){return-1!==({[r.search]:["queryText"]}[e]||[]).indexOf(t)}removeEmptyPayloadValues(e,t){return Object.keys(e).filter(r=>{return this.isKeyAllowedEmpty(t,r)||null!=(n=e[r])&&""!==n;var n}).reduce((t,r)=>Object.assign(Object.assign({},t),{[r]:e[r]}),{})}removeUnknownParameters(e){return Object.keys(e).filter(e=>{if((e=>[F,V,$,U].some(t=>t(e)))(e))return!0;console.log(e,"is not processed by coveoua")}).reduce((t,r)=>Object.assign(Object.assign({},t),{[r]:e[r]}),{})}processCustomParameters(t){const{custom:r}=t,n=e(t,["custom"]),i=O(o=n).reduce((e,t)=>{const r=A.exec(t)||R.exec(t);if(r){const n=r[1];return Object.assign(Object.assign({},e),q(n,o[t]))}return Object.assign(Object.assign({},e),{[t]:o[t]})},{});var o;return Object.assign(Object.assign({},r||{}),i)}validateParams(t){const{anonymizeIp:r}=t,n=e(t,["anonymizeIp"]);return void 0!==r&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+r).toLowerCase())&&(n.anonymizeIp=1),n}get baseUrl(){const{version:e,endpoint:t}=this.options,r=-1!==t.indexOf(".cloud.coveo.com");return`${t}${r?"":"/rest"}/${e}`}}var z;!function(e){e.interfaceLoad="interfaceLoad",e.interfaceChange="interfaceChange",e.didyoumeanAutomatic="didyoumeanAutomatic",e.didyoumeanClick="didyoumeanClick",e.resultsSort="resultsSort",e.searchboxSubmit="searchboxSubmit",e.searchboxClear="searchboxClear",e.searchboxAsYouType="searchboxAsYouType",e.breadcrumbFacet="breadcrumbFacet",e.breadcrumbResetAll="breadcrumbResetAll",e.documentQuickview="documentQuickview",e.documentOpen="documentOpen",e.omniboxAnalytics="omniboxAnalytics",e.omniboxFromLink="omniboxFromLink",e.triggerNotify="notify",e.triggerExecute="execute",e.triggerQuery="query",e.triggerRedirect="redirect",e.pagerResize="pagerResize",e.pagerNumber="pagerNumber",e.pagerNext="pagerNext",e.pagerPrevious="pagerPrevious",e.pagerScrolling="pagerScrolling",e.facetClearAll="facetClearAll",e.facetSearch="facetSearch",e.facetSelect="facetSelect",e.facetSelectAll="facetSelectAll",e.facetDeselect="facetDeselect",e.facetExclude="facetExclude",e.facetUnexclude="facetUnexclude",e.facetUpdateSort="facetUpdateSort",e.facetShowMore="showMoreFacetResults",e.facetShowLess="showLessFacetResults",e.queryError="query"}(z||(z={}));const W={[z.triggerNotify]:"queryPipelineTriggers",[z.triggerExecute]:"queryPipelineTriggers",[z.triggerQuery]:"queryPipelineTriggers",[z.triggerRedirect]:"queryPipelineTriggers",[z.queryError]:"errors",[z.pagerNext]:"getMoreResults",[z.pagerPrevious]:"getMoreResults",[z.pagerNumber]:"getMoreResults",[z.pagerResize]:"getMoreResults",[z.pagerScrolling]:"getMoreResults",[z.facetSearch]:"facet",[z.facetShowLess]:"facet",[z.facetShowMore]:"facet"};class J{constructor(){this.runtime=new D}sendEvent(){return Promise.resolve()}sendSearchEvent(){return Promise.resolve()}sendClickEvent(){return Promise.resolve()}sendCustomEvent(){return Promise.resolve()}sendViewEvent(){return Promise.resolve()}getVisit(){return Promise.resolve({id:"",visitorId:""})}getHealth(){return Promise.resolve({status:""})}registerBeforeSendEventHook(){}addEventTypeMapping(){}}class Y{constructor(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new J:new Q(e)}disable(){this.coveoAnalyticsClient instanceof Q&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new J}enable(){this.coveoAnalyticsClient=new Q(this.opts)}logInterfaceLoad(){return this.logSearchEvent(z.interfaceLoad)}logInterfaceChange(e){return this.logSearchEvent(z.interfaceChange,e)}logDidYouMeanAutomatic(){return this.logSearchEvent(z.didyoumeanAutomatic)}logDidYouMeanClick(){return this.logSearchEvent(z.didyoumeanClick)}logResultsSort(e){return this.logSearchEvent(z.resultsSort,e)}logSearchboxSubmit(){return this.logSearchEvent(z.searchboxSubmit)}logSearchboxClear(){return this.logSearchEvent(z.searchboxClear)}logSearchboxAsYouType(){return this.logSearchEvent(z.searchboxAsYouType)}logBreadcrumbFacet(e){return this.logSearchEvent(z.breadcrumbFacet,e)}logBreadcrumbResetAll(){return this.logSearchEvent(z.breadcrumbResetAll)}logDocumentQuickview(e,t){return this.logClickEvent(z.documentQuickview,e,t)}logDocumentOpen(e,t){return this.logClickEvent(z.documentOpen,e,t)}logOmniboxAnalytics(e){return this.logSearchEvent(z.omniboxAnalytics,e)}logOmniboxFromLink(e){return this.logSearchEvent(z.omniboxFromLink,e)}logTriggerNotify(e){return this.logCustomEvent(z.triggerNotify,e)}logTriggerExecute(e){return this.logCustomEvent(z.triggerExecute,e)}logTriggerQuery(){const e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(z.triggerQuery,e)}logTriggerRedirect(e){const t=Object.assign(Object.assign({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(z.triggerRedirect,t)}logPagerResize(e){return this.logCustomEvent(z.pagerResize,e)}logPagerNumber(e){return this.logCustomEvent(z.pagerNumber,e)}logPagerNext(e){return this.logCustomEvent(z.pagerNext,e)}logPagerPrevious(e){return this.logCustomEvent(z.pagerPrevious,e)}logPagerScrolling(){return this.logCustomEvent(z.pagerScrolling)}logFacetClearAll(e){return this.logSearchEvent(z.facetClearAll,e)}logFacetSearch(e){return this.logSearchEvent(z.facetSearch,e)}logFacetSelect(e){return this.logSearchEvent(z.facetSelect,e)}logFacetDeselect(e){return this.logSearchEvent(z.facetDeselect,e)}logFacetExclude(e){return this.logSearchEvent(z.facetExclude,e)}logFacetUnexclude(e){return this.logSearchEvent(z.facetUnexclude,e)}logFacetSelectAll(e){return this.logSearchEvent(z.facetSelectAll,e)}logFacetUpdateSort(e){return this.logSearchEvent(z.facetUpdateSort,e)}logFacetShowMore(e){return this.logCustomEvent(z.facetShowMore,e)}logFacetShowLess(e){return this.logCustomEvent(z.facetShowLess,e)}logQueryError(e){return this.logCustomEvent(z.queryError,e)}logCustomEvent(e,t){const r=Object.assign(Object.assign({},this.provider.getBaseMetadata()),t),n={eventType:W[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:r};return this.coveoAnalyticsClient.sendCustomEvent(n)}logSearchEvent(e,t){const r=Object.assign(Object.assign({},this.provider.getBaseMetadata()),t),n=Object.assign(Object.assign({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:r,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(n)}logClickEvent(e,t,r,n){const i=Object.assign(Object.assign(Object.assign({},this.provider.getBaseMetadata()),r),n),o=Object.assign(Object.assign({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:i});return this.coveoAnalyticsClient.sendClickEvent(o)}}export{Q as CoveoAnalyticsClient,Y as CoveoSearchPageClient}; | ||
function e(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function t(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))}var r;!function(e){e.search="search",e.click="click",e.custom="custom",e.view="view",e.collect="collect"}(r||(r={}));class n{constructor(e){this.opts=e}sendEvent(e,r){return t(this,void 0,void 0,(function*(){const{baseUrl:t,visitorIdProvider:n}=this.opts,o=this.shouldAppendVisitorId(e)?this.visitorIdParam:"",i=yield fetch(`${t}/analytics/${e}${o}`,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(r),credentials:"include"});if(i.ok){const e=yield i.json();return e.visitorId&&(n.currentVisitorId=e.visitorId),e}try{i.json()}catch(e){}throw console.error(`An error has occured when sending the "${e}" event.`,i,r),new Error(`An error has occurred when sending the "${e}" event. Check the console logs for more details.`)}))}shouldAppendVisitorId(e){return-1!==[r.click,r.custom,r.search,r.view].indexOf(e)}get visitorIdParam(){const{visitorIdProvider:e}=this.opts,t=e.currentVisitorId;return t?"?visitor="+t:""}getHeaders(){const{token:e}=this.opts;return Object.assign(Object.assign({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})}}function o(){return"undefined"!=typeof localStorage}function i(){return"undefined"!=typeof navigator&&navigator.cookieEnabled}function s(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}const a=[r.click,r.custom,r.search,r.view],c=(e,t)=>-1!==a.indexOf(e)?Object.assign({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t;class l{static set(e,t,r){var n,o,i,s,a;r?((i=new Date).setTime(i.getTime()+r),s="; expires="+i.toGMTString()):s="",-1===(a=location.hostname).indexOf(".")?document.cookie=e+"="+t+s+"; path=/":((o=a.split(".")).shift(),n="."+o.join("."),document.cookie=e+"="+t+s+"; path=/; domain="+n,null!=l.get(e)&&l.get(e)==t||(n="."+a,document.cookie=e+"="+t+s+"; path=/; domain="+n))}static get(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){var o=r[n];if(0==(o=o.replace(/^\s+/,"")).indexOf(t))return o.substring(t.length,o.length)}return null}static erase(e){l.set(e,"",-1)}}function u(){return o()?localStorage:i()?new d:"undefined"!=typeof sessionStorage?sessionStorage:new h}class d{getItem(e){return l.get(`${d.prefix}${e}`)}removeItem(e){l.erase(`${d.prefix}${e}`)}setItem(e,t){l.set(`${d.prefix}${e}`,t)}}d.prefix="coveo_";class g{constructor(){this.cookieStorage=new d}getItem(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)}removeItem(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)}setItem(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)}}class h{getItem(e){return null}removeItem(e){}setItem(e,t){}}const v="__coveo.analytics.history";class m{constructor(e){this.store=e||u(),this.store instanceof d||!i()||(new d).removeItem(v)}addElement(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);let t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])}getHistory(){const e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)}getHistoryWithInternalTime(){try{const e=this.store.getItem(v);return e?JSON.parse(e):[]}catch(e){return[]}}setHistory(e){try{this.store.setItem(v,JSON.stringify(e.slice(0,20)))}catch(e){}}clear(){try{this.store.removeItem(v)}catch(e){}}getMostRecentElement(){let e=this.getHistoryWithInternalTime();if(null!=e){return e.sort((e,t)=>(t.internalTime||0)-(e.internalTime||0))[0]}return null}cropQueryElement(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))}isValidEntry(e){let t=this.getMostRecentElement();return!t||t.value!=e.value||(e.internalTime||0)-(t.internalTime||0)>6e4}stripInternalTime(e){return e.map(e=>{const{name:t,time:r,value:n}=e;return{name:t,time:r,value:n}})}}const p=(e,t)=>e===r.view?(y(t.contentIdValue),Object.assign({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t,y=e=>{const t=new m,r={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(r)},f=e=>e?(Number(e)^b(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,f),b=e=>{if(s())return crypto.getRandomValues(e);for(var t=0,r=0;t<e.length;t++)0==(3&t)&&(r=4294967296*Math.random()),e[t]=r>>>((3&t)<<3)&255;return e},E={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},S={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},w=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),I=Object.keys,O=I(w).map(e=>w[e]),C=I(E).map(e=>E[e]),x=I(S).map(e=>S[e]),k=[...C,"custom"].join("|"),j=[...x,"custom"].join("|"),P=new RegExp(`^(pr[0-9]+)(${k})$`),T=new RegExp(`^((il[0-9]+pi[0-9]+)(${j}))|(il[0-9]+nm)$`),A=new RegExp("^(pr[0-9]+)custom$"),R=new RegExp("^(il[0-9]+pi[0-9]+)custom$"),q=e=>P.test(e),F=e=>T.test(e),U=e=>-1!==O.indexOf(e),V=e=>"custom"===e,$=(e,t)=>I(t).reduce((r,n)=>Object.assign(Object.assign({},r),{[`${e}${n}`]:t[n]}),{});class B{constructor(e){this.opts=e}sendEvent(e,r){return t(this,void 0,void 0,(function*(){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');const{baseUrl:t}=this.opts,n=this.encodeForEventType(e,r),o=this.getQueryParamsForEventType(e),i=`${t}/analytics/${e}?${o}`;console.log(`Sending beacon for "${e}" with: `,JSON.stringify(r)),navigator.sendBeacon(i,new Blob([n],{type:"application/x-www-form-urlencoded"}))}))}encodeForEventType(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(Object.assign({access_token:this.opts.token},t))}getQueryParamsForEventType(e){const{token:t,visitorIdProvider:r}=this.opts,n=r.currentVisitorId;return[t&&this.isEventTypeLegacy(e)?"access_token="+t:"",n?"visitorId="+n:""].filter(e=>!!e).join("&")}isEventTypeLegacy(e){return-1!==[r.click,r.custom,r.search,r.view].indexOf(e)}encodeForLegacyType(e,t){return`${e}Event=${encodeURIComponent(JSON.stringify(t))}`}encodeForFormUrlEncoded(e){return Object.keys(e).filter(t=>!!e[t]).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(this.encodeValue(e[t]))}`).join("&")}encodeValue(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)}}class M{sendEvent(e,r){return t(this,void 0,void 0,(function*(){return Promise.resolve()}))}}class N{constructor(e,t){o()&&i()?this.storage=new g:o()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new h),this.beaconClient=new B(e),window.addEventListener("beforeunload",()=>t())}}class L{constructor(){this.storage=new h,this.beaconClient=new M}}class Q{constructor(){this.storage=new h,this.beaconClient=new M}}const D="https://platform.cloud.coveo.com/rest/ua";class H{constructor(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=Object.assign(Object.assign({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[p,c],this.eventTypeMapping={};const t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new n(t),this.initVisitorId()}get defaultOptions(){return{endpoint:D,token:"",version:"v15"}}initRuntime(e){return"undefined"!=typeof window&&"undefined"!=typeof document?new N(e,()=>this.flushBufferWithBeacon()):new L}get analyticsBeaconClient(){return this.runtime.beaconClient}get storage(){return this.runtime.storage}initVisitorId(){const e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||f()}get currentVisitorId(){return this.visitorId}set currentVisitorId(e){this.visitorId=e,this.storage.setItem("visitorId",e)}sendEvent(e,...r){return t(this,void 0,void 0,(function*(){const{newEventType:t=e,variableLengthArgumentsNames:n=[],addVisitorIdParameter:o=!1,usesMeasurementProtocol:i=!1}=this.eventTypeMapping[e]||{},s=[e=>n.length>0?this.parseVariableArgumentsPayload(n,e):e[0],e=>Object.assign({visitorId:o?this.visitorId:""},e),e=>i?this.ensureAnonymousUserWhenUsingApiKey(e):e,t=>this.beforeSendHooks.reduce((t,r)=>r(e,t),t),t=>this.removeEmptyPayloadValues(t,e),e=>this.validateParams(e),e=>{return i?I(t=e).reduce((e,r)=>{const n=w[r]||r;return Object.assign(Object.assign({},e),{[n]:t[r]})},{}):e;var t},e=>i?this.removeUnknownParameters(e):e,e=>i?this.processCustomParameters(e):e].reduce((e,t)=>t(e),r);return this.bufferedRequests.push({eventType:t,payload:s,handled:!1}),yield this.deferExecution(),yield this.sendFromBufferWithFetch()}))}deferExecution(){return new Promise(e=>setTimeout(e,0))}flushBufferWithBeacon(){for(;this.hasPendingRequests();){const{eventType:e,payload:t}=this.bufferedRequests.pop();this.analyticsBeaconClient.sendEvent(e,t)}}sendFromBufferWithFetch(){return t(this,void 0,void 0,(function*(){const e=this.bufferedRequests.shift();if(e){const{eventType:t,payload:r}=e;return this.analyticsFetchClient.sendEvent(t,r)}}))}hasPendingRequests(){return this.bufferedRequests.length>0}clear(){this.storage.removeItem("visitorId"),(new m).clear()}sendSearchEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.search,e)}))}sendClickEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.click,e)}))}sendCustomEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.custom,e)}))}sendViewEvent(e){return t(this,void 0,void 0,(function*(){return this.sendEvent(r.view,e)}))}getVisit(){return t(this,void 0,void 0,(function*(){const e=yield fetch(this.baseUrl+"/analytics/visit"),t=yield e.json();return this.visitorId=t.visitorId,t}))}getHealth(){return t(this,void 0,void 0,(function*(){const e=yield fetch(this.baseUrl+"/analytics/monitoring/health");return yield e.json()}))}registerBeforeSendEventHook(e){this.beforeSendHooks.push(e)}addEventTypeMapping(e,t){this.eventTypeMapping[e]=t}parseVariableArgumentsPayload(e,t){const r={};for(let n=0,o=t.length;n<o;n++){const o=t[n];if("string"==typeof o)r[e[n]]=o;else if("object"==typeof o)return Object.assign(Object.assign({},r),o)}return r}isKeyAllowedEmpty(e,t){return-1!==({[r.search]:["queryText"]}[e]||[]).indexOf(t)}removeEmptyPayloadValues(e,t){return Object.keys(e).filter(r=>{return this.isKeyAllowedEmpty(t,r)||null!=(n=e[r])&&""!==n;var n}).reduce((t,r)=>Object.assign(Object.assign({},t),{[r]:e[r]}),{})}removeUnknownParameters(e){return Object.keys(e).filter(e=>{if((e=>[q,F,U,V].some(t=>t(e)))(e))return!0;console.log(e,"is not processed by coveoua")}).reduce((t,r)=>Object.assign(Object.assign({},t),{[r]:e[r]}),{})}processCustomParameters(t){const{custom:r}=t,n=e(t,["custom"]),o=I(i=n).reduce((e,t)=>{const r=A.exec(t)||R.exec(t);if(r){const n=r[1];return Object.assign(Object.assign({},e),$(n,i[t]))}return Object.assign(Object.assign({},e),{[t]:i[t]})},{});var i;return Object.assign(Object.assign({},r||{}),o)}validateParams(t){const{anonymizeIp:r}=t,n=e(t,["anonymizeIp"]);return void 0!==r&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+r).toLowerCase())&&(n.anonymizeIp=1),n}ensureAnonymousUserWhenUsingApiKey(t){const{userId:r}=t,n=e(t,["userId"]);return(null==(o=this.options.token)?void 0:o.startsWith("xx"))&&!r?(n.userId="anonymous",n):t;var o}get baseUrl(){const{version:e,endpoint:t}=this.options,r=-1!==t.indexOf(".cloud.coveo.com");return`${t}${r?"":"/rest"}/${e}`}}var z;!function(e){e.interfaceLoad="interfaceLoad",e.interfaceChange="interfaceChange",e.didyoumeanAutomatic="didyoumeanAutomatic",e.didyoumeanClick="didyoumeanClick",e.resultsSort="resultsSort",e.searchboxSubmit="searchboxSubmit",e.searchboxClear="searchboxClear",e.searchboxAsYouType="searchboxAsYouType",e.breadcrumbFacet="breadcrumbFacet",e.breadcrumbResetAll="breadcrumbResetAll",e.documentQuickview="documentQuickview",e.documentOpen="documentOpen",e.omniboxAnalytics="omniboxAnalytics",e.omniboxFromLink="omniboxFromLink",e.triggerNotify="notify",e.triggerExecute="execute",e.triggerQuery="query",e.triggerRedirect="redirect",e.pagerResize="pagerResize",e.pagerNumber="pagerNumber",e.pagerNext="pagerNext",e.pagerPrevious="pagerPrevious",e.pagerScrolling="pagerScrolling",e.facetClearAll="facetClearAll",e.facetSearch="facetSearch",e.facetSelect="facetSelect",e.facetSelectAll="facetSelectAll",e.facetDeselect="facetDeselect",e.facetExclude="facetExclude",e.facetUnexclude="facetUnexclude",e.facetUpdateSort="facetUpdateSort",e.facetShowMore="showMoreFacetResults",e.facetShowLess="showLessFacetResults",e.queryError="query",e.queryErrorBack="errorBack",e.queryErrorClear="errorClearQuery",e.queryErrorRetry="errorRetry"}(z||(z={}));const W={[z.triggerNotify]:"queryPipelineTriggers",[z.triggerExecute]:"queryPipelineTriggers",[z.triggerQuery]:"queryPipelineTriggers",[z.triggerRedirect]:"queryPipelineTriggers",[z.queryError]:"errors",[z.queryErrorBack]:"errors",[z.queryErrorClear]:"errors",[z.queryErrorRetry]:"errors",[z.pagerNext]:"getMoreResults",[z.pagerPrevious]:"getMoreResults",[z.pagerNumber]:"getMoreResults",[z.pagerResize]:"getMoreResults",[z.pagerScrolling]:"getMoreResults",[z.facetSearch]:"facet",[z.facetShowLess]:"facet",[z.facetShowMore]:"facet"};class J{constructor(){this.runtime=new Q}sendEvent(){return Promise.resolve()}sendSearchEvent(){return Promise.resolve()}sendClickEvent(){return Promise.resolve()}sendCustomEvent(){return Promise.resolve()}sendViewEvent(){return Promise.resolve()}getVisit(){return Promise.resolve({id:"",visitorId:""})}getHealth(){return Promise.resolve({status:""})}registerBeforeSendEventHook(){}addEventTypeMapping(){}}class Y{constructor(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new J:new H(e)}disable(){this.coveoAnalyticsClient instanceof H&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new J}enable(){this.coveoAnalyticsClient=new H(this.opts)}logInterfaceLoad(){return this.logSearchEvent(z.interfaceLoad)}logInterfaceChange(e){return this.logSearchEvent(z.interfaceChange,e)}logDidYouMeanAutomatic(){return this.logSearchEvent(z.didyoumeanAutomatic)}logDidYouMeanClick(){return this.logSearchEvent(z.didyoumeanClick)}logResultsSort(e){return this.logSearchEvent(z.resultsSort,e)}logSearchboxSubmit(){return this.logSearchEvent(z.searchboxSubmit)}logSearchboxClear(){return this.logSearchEvent(z.searchboxClear)}logSearchboxAsYouType(){return this.logSearchEvent(z.searchboxAsYouType)}logBreadcrumbFacet(e){return this.logSearchEvent(z.breadcrumbFacet,e)}logBreadcrumbResetAll(){return this.logSearchEvent(z.breadcrumbResetAll)}logDocumentQuickview(e,t){return this.logClickEvent(z.documentQuickview,e,t)}logDocumentOpen(e,t){return this.logClickEvent(z.documentOpen,e,t)}logOmniboxAnalytics(e){return this.logSearchEvent(z.omniboxAnalytics,e)}logOmniboxFromLink(e){return this.logSearchEvent(z.omniboxFromLink,e)}logTriggerNotify(e){return this.logCustomEvent(z.triggerNotify,e)}logTriggerExecute(e){return this.logCustomEvent(z.triggerExecute,e)}logTriggerQuery(){const e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(z.triggerQuery,e)}logTriggerRedirect(e){const t=Object.assign(Object.assign({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(z.triggerRedirect,t)}logPagerResize(e){return this.logCustomEvent(z.pagerResize,e)}logPagerNumber(e){return this.logCustomEvent(z.pagerNumber,e)}logPagerNext(e){return this.logCustomEvent(z.pagerNext,e)}logPagerPrevious(e){return this.logCustomEvent(z.pagerPrevious,e)}logPagerScrolling(){return this.logCustomEvent(z.pagerScrolling)}logFacetClearAll(e){return this.logSearchEvent(z.facetClearAll,e)}logFacetSearch(e){return this.logSearchEvent(z.facetSearch,e)}logFacetSelect(e){return this.logSearchEvent(z.facetSelect,e)}logFacetDeselect(e){return this.logSearchEvent(z.facetDeselect,e)}logFacetExclude(e){return this.logSearchEvent(z.facetExclude,e)}logFacetUnexclude(e){return this.logSearchEvent(z.facetUnexclude,e)}logFacetSelectAll(e){return this.logSearchEvent(z.facetSelectAll,e)}logFacetUpdateSort(e){return this.logSearchEvent(z.facetUpdateSort,e)}logFacetShowMore(e){return this.logCustomEvent(z.facetShowMore,e)}logFacetShowLess(e){return this.logCustomEvent(z.facetShowLess,e)}logQueryError(e){return this.logCustomEvent(z.queryError,e)}logQueryErrorBack(){return t(this,void 0,void 0,(function*(){return yield this.logCustomEvent(z.queryErrorBack),this.logSearchEvent(z.queryErrorBack)}))}logQueryErrorRetry(){return t(this,void 0,void 0,(function*(){return yield this.logCustomEvent(z.queryErrorRetry),this.logSearchEvent(z.queryErrorRetry)}))}logQueryErrorClear(){return t(this,void 0,void 0,(function*(){return yield this.logCustomEvent(z.queryErrorClear),this.logSearchEvent(z.queryErrorClear)}))}logCustomEvent(e,t){const r=Object.assign(Object.assign({},this.provider.getBaseMetadata()),t),n={eventType:W[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:r};return this.coveoAnalyticsClient.sendCustomEvent(n)}logSearchEvent(e,t){const r=Object.assign(Object.assign({},this.provider.getBaseMetadata()),t),n=Object.assign(Object.assign({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:r,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(n)}logClickEvent(e,t,r,n){const o=Object.assign(Object.assign(Object.assign({},this.provider.getBaseMetadata()),r),n),i=Object.assign(Object.assign({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:o});return this.coveoAnalyticsClient.sendClickEvent(i)}}export{H as CoveoAnalyticsClient,Y as CoveoSearchPageClient}; | ||
//# sourceMappingURL=library.es.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).coveoua={})}(this,function(e){"use strict";var o,t,h=function(){return(h=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function a(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function n(e,a,s,c){return new(s=s||Promise)(function(n,t){function o(e){try{i(c.next(e))}catch(e){t(e)}}function r(e){try{i(c.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?n(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(o,r)}i((c=c.apply(e,a||[])).next())})}function v(n,o){var r,i,a,e,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return e={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=0,a&&(t=[2&t[0],a.value]),t[0]){case 0:case 1:a=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,i=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(a=0<(a=s.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3])){s.label=t[1];break}if(6===t[0]&&s.label<a[1]){s.label=a[1],a=t;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(t);break}a[2]&&s.ops.pop(),s.trys.pop();continue}t=o.call(n,s)}catch(e){t=[6,e],i=0}finally{r=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function s(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var o=Array(e),r=0;for(t=0;t<n;t++)for(var i=arguments[t],a=0,s=i.length;a<s;a++,r++)o[r]=i[a];return o}(t=o=o||{}).search="search",t.click="click",t.custom="custom",t.view="view",t.collect="collect";var r=(i.prototype.sendEvent=function(s,c){return n(this,void 0,void 0,function(){var t,n,o,r,i,a;return v(this,function(e){switch(e.label){case 0:return t=this.opts,n=t.baseUrl,o=t.visitorIdProvider,r=this.shouldAppendVisitorId(s)?this.visitorIdParam:"",[4,fetch(n+"/analytics/"+s+r,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(c),credentials:"include"})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return(a=e.sent()).visitorId&&(o.currentVisitorId=a.visitorId),[2,a];case 3:try{i.json()}catch(e){}throw console.error('An error has occured when sending the "'+s+'" event.',i,c),new Error('An error has occurred when sending the "'+s+'" event. Check the console logs for more details.')}})})},i.prototype.shouldAppendVisitorId=function(e){return-1!==[o.click,o.custom,o.search,o.view].indexOf(e)},Object.defineProperty(i.prototype,"visitorIdParam",{get:function(){var e=this.opts.visitorIdProvider.currentVisitorId;return e?"?visitor="+e:""},enumerable:!0,configurable:!0}),i.prototype.getHeaders=function(){var e=this.opts.token;return h(h({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})},i);function i(e){this.opts=e}function c(){return"undefined"!=typeof navigator}function u(){return"undefined"!=typeof localStorage}function l(){return c()&&navigator.cookieEnabled}function p(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}function f(e,t){return-1!==d.indexOf(e)?h({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t}var d=[o.click,o.custom,o.search,o.view],g=(y.set=function(e,t,n){var o,r,i,a,s;a=n?((i=new Date).setTime(i.getTime()+n),"; expires="+i.toGMTString()):"",-1===(s=location.hostname).indexOf(".")?document.cookie=e+"="+t+a+"; path=/":((r=s.split(".")).shift(),o="."+r.join("."),document.cookie=e+"="+t+a+"; path=/; domain="+o,null!=y.get(e)&&y.get(e)==t||(o="."+s,document.cookie=e+"="+t+a+"; path=/; domain="+o))},y.get=function(e){for(var t=e+"=",n=document.cookie.split(";"),o=0;o<n.length;o++){var r=n[o];if(0==(r=r.replace(/^\s+/,"")).indexOf(t))return r.substring(t.length,r.length)}return null},y.erase=function(e){y.set(e,"",-1)},y);function y(){}function m(){return u()?localStorage:l()?new w:"undefined"!=typeof sessionStorage?sessionStorage:new I}var w=(b.prototype.getItem=function(e){return g.get(""+b.prefix+e)},b.prototype.removeItem=function(e){g.erase(""+b.prefix+e)},b.prototype.setItem=function(e,t){g.set(""+b.prefix+e,t)},b.prefix="coveo_",b);function b(){}var E=(S.prototype.getItem=function(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)},S.prototype.removeItem=function(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)},S.prototype.setItem=function(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)},S);function S(){this.cookieStorage=new w}var I=(C.prototype.getItem=function(e){return null},C.prototype.removeItem=function(e){},C.prototype.setItem=function(e,t){},C);function C(){}var x=Object.freeze({__proto__:null,preferredStorage:null,getAvailableStorage:m,CookieStorage:w,CookieAndLocalStorage:E,NullStorage:I}),P="__coveo.analytics.history",k=(T.prototype.addElement=function(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);var t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])},T.prototype.getHistory=function(){var e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)},T.prototype.getHistoryWithInternalTime=function(){try{var e=this.store.getItem(P);return e?JSON.parse(e):[]}catch(e){return[]}},T.prototype.setHistory=function(e){try{this.store.setItem(P,JSON.stringify(e.slice(0,20)))}catch(e){}},T.prototype.clear=function(){try{this.store.removeItem(P)}catch(e){}},T.prototype.getMostRecentElement=function(){var e=this.getHistoryWithInternalTime();return null==e?null:e.sort(function(e,t){return(t.internalTime||0)-(e.internalTime||0)})[0]},T.prototype.cropQueryElement=function(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))},T.prototype.isValidEntry=function(e){var t=this.getMostRecentElement();return!t||t.value!=e.value||6e4<(e.internalTime||0)-(t.internalTime||0)},T.prototype.stripInternalTime=function(e){return e.map(function(e){return{name:e.name,time:e.time,value:e.value}})},T);function T(e){this.store=e||m(),this.store instanceof w||!l()||(new w).removeItem(P)}function A(e,t){return e===o.view?(F(t.contentIdValue),h({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t}function O(t){return[function(e){return W.test(e)},function(e){return J.test(e)},function(e){return-1!==D.indexOf(e)},function(e){return"custom"===e}].some(function(e){return e(t)})}var R=Object.freeze({__proto__:null,STORE_KEY:P,MAX_NUMBER_OF_HISTORY_ELEMENTS:20,MIN_THRESHOLD_FOR_DUPLICATE_VALUE:6e4,MAX_VALUE_SIZE:75,HistoryStore:k,default:k}),F=function(e){var t=new k,n={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(n)},L=function(e){return e?(Number(e)^V(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):(""+1e7+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,L)},V=function(e){if(p())return crypto.getRandomValues(e);for(var t=0,n=0;t<e.length;t++)0==(3&t)&&(n=4294967296*Math.random()),e[t]=n>>>((3&t)<<3)&255;return e},j={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},N={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},_=h(h(h(h(h({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),M=Object.keys,U=function(r,i,a){return M(r).reduce(function(e,t){var n,o="il"+(i+1)+"pi"+(a+1)+(N[t]||t);return h(h({},e),((n={})[o]=r[t],n))},{})},D=M(_).map(function(e){return _[e]}),H=M(j).map(function(e){return j[e]}),q=M(N).map(function(e){return N[e]}),B=s(H,["custom"]).join("|"),z=s(q,["custom"]).join("|"),Q="(pr[0-9]+)",Y="(il[0-9]+pi[0-9]+)",W=new RegExp("^"+Q+"("+B+")$"),J=new RegExp("^("+Y+"("+z+"))|(il[0-9]+nm)$"),$=new RegExp("^"+Q+"custom$"),G=new RegExp("^"+Y+"custom$"),K=function(o,r){return M(r).reduce(function(e,t){var n;return h(h({},e),((n={})[""+o+t]=r[t],n))},{})},X=(Z.prototype.sendEvent=function(i,a){return n(this,void 0,void 0,function(){var t,n,o,r;return v(this,function(e){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');return t=this.opts.baseUrl,n=this.encodeForEventType(i,a),o=this.getQueryParamsForEventType(i),r=t+"/analytics/"+i+"?"+o,console.log('Sending beacon for "'+i+'" with: ',JSON.stringify(a)),navigator.sendBeacon(r,new Blob([n],{type:"application/x-www-form-urlencoded"})),[2]})})},Z.prototype.encodeForEventType=function(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(h({access_token:this.opts.token},t))},Z.prototype.getQueryParamsForEventType=function(e){var t=this.opts,n=t.token,o=t.visitorIdProvider.currentVisitorId;return[n&&this.isEventTypeLegacy(e)?"access_token="+n:"",o?"visitorId="+o:""].filter(function(e){return!!e}).join("&")},Z.prototype.isEventTypeLegacy=function(e){return-1!==[o.click,o.custom,o.search,o.view].indexOf(e)},Z.prototype.encodeForLegacyType=function(e,t){return e+"Event="+encodeURIComponent(JSON.stringify(t))},Z.prototype.encodeForFormUrlEncoded=function(t){var n=this;return Object.keys(t).filter(function(e){return!!t[e]}).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(n.encodeValue(t[e]))}).join("&")},Z.prototype.encodeValue=function(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)},Z);function Z(e){this.opts=e}var ee=(te.prototype.sendEvent=function(e,t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,Promise.resolve()]})})},te);function te(){}var ne=function(e,t){u()&&l()?this.storage=new E:u()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new I),this.beaconClient=new X(e),window.addEventListener("beforeunload",function(){return t()})},oe=function(){this.storage=new I,this.beaconClient=new ee},re=function(){this.storage=new I,this.beaconClient=new ee},ie={default:"https://platform.cloud.coveo.com/rest/ua",production:"https://platform.cloud.coveo.com/rest/ua",hipaa:"https://platformhipaa.cloud.coveo.com/rest/ua"},ae=(Object.defineProperty(se.prototype,"defaultOptions",{get:function(){return{endpoint:ie.default,token:"",version:"v15"}},enumerable:!0,configurable:!0}),se.prototype.initRuntime=function(e){var t=this;return"undefined"!=typeof window&&"undefined"!=typeof document?new ne(e,function(){return t.flushBufferWithBeacon()}):new oe},Object.defineProperty(se.prototype,"analyticsBeaconClient",{get:function(){return this.runtime.beaconClient},enumerable:!0,configurable:!0}),Object.defineProperty(se.prototype,"storage",{get:function(){return this.runtime.storage},enumerable:!0,configurable:!0}),se.prototype.initVisitorId=function(){var e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||L()},Object.defineProperty(se.prototype,"currentVisitorId",{get:function(){return this.visitorId},set:function(e){this.visitorId=e,this.storage.setItem("visitorId",e)},enumerable:!0,configurable:!0}),se.prototype.sendEvent=function(f){for(var d=[],e=1;e<arguments.length;e++)d[e-1]=arguments[e];return n(this,void 0,void 0,function(){var t,n,o,r,i,a,s,c,u,l,p=this;return v(this,function(e){switch(e.label){case 0:return t=this.eventTypeMapping[f]||{},o=void 0===(n=t.newEventType)?f:n,i=void 0===(r=t.variableLengthArgumentsNames)?[]:r,s=void 0!==(a=t.addVisitorIdParameter)&&a,u=void 0!==(c=t.usesMeasurementProtocol)&&c,l=[function(e){return 0<i.length?p.parseVariableArgumentsPayload(i,e):e[0]},function(e){return h({visitorId:s?p.visitorId:""},e)},function(e){return p.beforeSendHooks.reduce(function(e,t){return t(f,e)},e)},function(e){return p.removeEmptyPayloadValues(e,f)},function(e){return p.validateParams(e)},function(e){return u?M(r=e).reduce(function(e,t){var n,o=_[t]||t;return h(h({},e),((n={})[o]=r[t],n))},{}):e;var r},function(e){return u?p.removeUnknownParameters(e):e},function(e){return u?p.processCustomParameters(e):e}].reduce(function(e,t){return t(e)},d),this.bufferedRequests.push({eventType:o,payload:l,handled:!1}),[4,this.deferExecution()];case 1:return e.sent(),[4,this.sendFromBufferWithFetch()];case 2:return[2,e.sent()]}})})},se.prototype.deferExecution=function(){return new Promise(function(e){return setTimeout(e,0)})},se.prototype.flushBufferWithBeacon=function(){for(;this.hasPendingRequests();){var e=this.bufferedRequests.pop(),t=e.eventType,n=e.payload;this.analyticsBeaconClient.sendEvent(t,n)}},se.prototype.sendFromBufferWithFetch=function(){return n(this,void 0,void 0,function(){var t,n,o;return v(this,function(e){return(t=this.bufferedRequests.shift())?(n=t.eventType,o=t.payload,[2,this.analyticsFetchClient.sendEvent(n,o)]):[2]})})},se.prototype.hasPendingRequests=function(){return 0<this.bufferedRequests.length},se.prototype.clear=function(){this.storage.removeItem("visitorId"),(new k).clear()},se.prototype.sendSearchEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.search,t)]})})},se.prototype.sendClickEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.click,t)]})})},se.prototype.sendCustomEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.custom,t)]})})},se.prototype.sendViewEvent=function(t){return n(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(o.view,t)]})})},se.prototype.getVisit=function(){return n(this,void 0,void 0,function(){var t;return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/visit")];case 1:return[4,e.sent().json()];case 2:return t=e.sent(),this.visitorId=t.visitorId,[2,t]}})})},se.prototype.getHealth=function(){return n(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/monitoring/health")];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}})})},se.prototype.registerBeforeSendEventHook=function(e){this.beforeSendHooks.push(e)},se.prototype.addEventTypeMapping=function(e,t){this.eventTypeMapping[e]=t},se.prototype.parseVariableArgumentsPayload=function(e,t){for(var n={},o=0,r=t.length;o<r;o++){var i=t[o];if("string"==typeof i)n[e[o]]=i;else if("object"==typeof i)return h(h({},n),i)}return n},se.prototype.isKeyAllowedEmpty=function(e,t){var n;return-1!==((n={})[o.search]=["queryText"],(n[e]||[]).indexOf(t))},se.prototype.removeEmptyPayloadValues=function(o,n){var r=this;return Object.keys(o).filter(function(e){return r.isKeyAllowedEmpty(n,e)||null!=(t=o[e])&&""!==t;var t}).reduce(function(e,t){var n;return h(h({},e),((n={})[t]=o[t],n))},{})},se.prototype.removeUnknownParameters=function(o){return Object.keys(o).filter(function(e){if(O(e))return!0;console.log(e,"is not processed by coveoua")}).reduce(function(e,t){var n;return h(h({},e),((n={})[t]=o[t],n))},{})},se.prototype.processCustomParameters=function(e){var i,t=e.custom,n=a(e,["custom"]),o=M(i=n).reduce(function(e,t){var n,o=$.exec(t)||G.exec(t);if(o){var r=o[1];return h(h({},e),K(r,i[t]))}return h(h({},e),((n={})[t]=i[t],n))},{});return h(h({},t||{}),o)},se.prototype.validateParams=function(e){var t=e.anonymizeIp,n=a(e,["anonymizeIp"]);return void 0!==t&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+t).toLowerCase())&&(n.anonymizeIp=1),n},Object.defineProperty(se.prototype,"baseUrl",{get:function(){var e=this.options,t=e.version,n=e.endpoint,o=-1!==n.indexOf(".cloud.coveo.com");return n+(o?"":"/rest")+"/"+t},enumerable:!0,configurable:!0}),se);function se(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=h(h({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[A,f],this.eventTypeMapping={};var t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new r(t),this.initVisitorId()}var ce=Object.freeze({__proto__:null,Version:"v15",Endpoints:ie,CoveoAnalyticsClient:ae,default:ae}),ue=c()?[!0,"yes","1"].indexOf(navigator.doNotTrack||navigator.msDoNotTrack||window.doNotTrack):0,le=Object.freeze({__proto__:null,doNotTrack:ue,default:ue}),pe=(fe.prototype.register=function(e,t){this.plugins[e]=t},fe.prototype.execute=function(e,t){for(var n=[],o=2;o<arguments.length;o++)n[o-2]=arguments[o];var r=this.plugins[e];return r[t].apply(r,n)},fe);function fe(){this.plugins={}}function de(e){return e.protocol+"//"+e.hostname+(0===e.pathname.indexOf("/")?e.pathname:"/"+e.pathname)+e.search}var he={pageview:"pageview",event:"event"},ve=Object.keys(he).map(function(e){return he[e]}),ge=(ye.prototype.addProduct=function(e){this.products.push(e)},ye.prototype.addImpression=function(e){this.impressions.push(e)},ye.prototype.setAction=function(e,t){this.action=e,this.actionData=t},ye.prototype.clearData=function(){this.products=[],this.impressions=[],this.action=void 0,this.actionData={}},ye.prototype.addHooksForECEvents=function(){var r=this;this.client.registerBeforeSendEventHook(function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var o=t[0];return-1!==ve.indexOf(e)?r.addECDataToPayload(e,o):o})},ye.prototype.addHooksForPageView=function(){this.client.addEventTypeMapping(he.pageview,{newEventType:o.collect,variableLengthArgumentsNames:["page"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ye.prototype.addHooksForEvent=function(){this.client.addEventTypeMapping(he.event,{newEventType:o.collect,variableLengthArgumentsNames:["eventCategory","eventAction","eventLabel","eventValue"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ye.prototype.addECDataToPayload=function(e,t){var n=h(h(h(h({},this.getLocationInformation(e,t)),this.getDefaultContextInformation(e)),this.action?{action:this.action}:{}),this.actionData||{}),o=this.products.reduce(function(e,t,n){return h(h({},e),(i=n,M(r=t).reduce(function(e,t){var n,o="pr"+(i+1)+(j[t]||t);return h(h({},e),((n={})[o]=r[t],n))},{})));var r,i},{}),r=this.getImpressionsByList().reduce(function(e,t,n){return h(h({},e),function(e,o){var t=e.impressions.reduce(function(e,t,n){return h(h({},e),U(t,o,n))},{});return e.listName&&(t["il"+(o+1)+"nm"]=e.listName),t}(t,n))},{});return this.clearData(),h(h(h(h({},r),o),n),t)},ye.prototype.getImpressionsByList=function(){return this.impressions.reduce(function(e,t){var n=t.list,o=a(t,["list"]),r=e.find(function(e){return e.listName===n});return r?r.impressions.push(o):e.push({listName:n,impressions:[o]}),e},[])},ye.prototype.updateStateForNewPageView=function(e){this.hasSentFirstPageView&&(this.pageViewId=this.uuidGenerator(),this.lastReferrer=this.lastLocation),e.page?this.lastLocation=""+this.lastLocation.split("/").slice(0,3).join("/")+e.page.replace(/^\/?(.*)$/,"/$1"):this.lastLocation=de(window.location),this.hasSentFirstPageView=!0},ye.prototype.getLocationInformation=function(e,t){return e===he.pageview&&this.updateStateForNewPageView(t),{referrer:this.lastReferrer,location:this.lastLocation}},ye.prototype.getDefaultContextInformation=function(e){var t={hitType:e,pageViewId:this.pageViewId},n={title:document.title,encoding:document.characterSet},o={screenResolution:screen.width+"x"+screen.height,screenColor:screen.colorDepth+"-bit"},r={language:navigator.language,userAgent:navigator.userAgent},i={time:Date.now().toString(),eventId:this.uuidGenerator()};return h(h(h(h(h({},t),i),o),r),n)},ye);function ye(e){var t=e.client,n=e.uuidGenerator,o=void 0===n?L:n;this.products=[],this.impressions=[],this.actionData={},this.client=t,this.uuidGenerator=o,this.pageViewId=o(),this.lastLocation=de(window.location),this.lastReferrer=document.referrer,this.addHooksForPageView(),this.addHooksForEvent(),this.addHooksForECEvents()}var me=(we.prototype.init=function(e,t){var n=this;if(!e)throw new Error("You must pass your token when you call 'init'");if("string"==typeof e?(t=t||ie.default,this.client=new ae({token:e,endpoint:t})):"object"==typeof e&&void 0!==e.sendEvent&&(this.client=e),!this.client)throw new Error("You must pass either your token or a valid object when you call 'init'");this.plugins.register("ec",new ge({client:this.client})),this.client.registerBeforeSendEventHook(function(e,t){return h(h({},t),n.params)})},we.prototype.initForProxy=function(e){if(!e)throw new Error("You must pass your endpoint when you call 'initForProxy'");if("string"!=typeof e)throw new Error("You must pass a string as the endpoint parameter when you call 'initForProxy'");this.client=new ae({endpoint:e})},we.prototype.set=function(t,e){var n=this;"string"==typeof t?this.params[t]=e:Object.keys(t).map(function(e){n.params[e]=t[e]})},we.prototype.send=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var o=t[0],r=t.slice(1);if(void 0===this.client)throw new Error("You must call init before sending an event");if(!o)throw new Error('You must provide an event type when calling "send".');return(e=this.client).sendEvent.apply(e,s([o.toLowerCase()],r))},we.prototype.onLoad=function(e){if(void 0===e)throw new Error("You must pass a function when you call 'onLoad'");e()},we.prototype.callPlugin=function(e,t){for(var n,o=[],r=2;r<arguments.length;r++)o[r-2]=arguments[r];(n=this.plugins).execute.apply(n,s([e,t],o))},we.prototype.reset=function(){this.client=void 0,this.plugins=new pe,this.params={}},we);function we(){this.plugins=new pe,this.params={}}function be(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var o=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/.exec(e),r=(o[1],o[2]),i=o[3],a=Ce[i];if(r&&i)return Ce.callPlugin.apply(Ce,s([r,i],t));if(a)return a.apply(Ce,t);throw new Error('The action "'+e+'" does not exist. Available actions: '+["init","set","send","onLoad","callPlugin"].join(", ")+".")}var Ee,Se,Ie,Ce=new me,xe=Object.freeze({__proto__:null,CoveoUA:me,coveoua:Ce,handleOneAnalyticsEvent:be,default:be});(Ie=Se=Se||{}).interfaceLoad="interfaceLoad",Ie.interfaceChange="interfaceChange",Ie.didyoumeanAutomatic="didyoumeanAutomatic",Ie.didyoumeanClick="didyoumeanClick",Ie.resultsSort="resultsSort",Ie.searchboxSubmit="searchboxSubmit",Ie.searchboxClear="searchboxClear",Ie.searchboxAsYouType="searchboxAsYouType",Ie.breadcrumbFacet="breadcrumbFacet",Ie.breadcrumbResetAll="breadcrumbResetAll",Ie.documentQuickview="documentQuickview",Ie.documentOpen="documentOpen",Ie.omniboxAnalytics="omniboxAnalytics",Ie.omniboxFromLink="omniboxFromLink",Ie.triggerNotify="notify",Ie.triggerExecute="execute",Ie.triggerQuery="query",Ie.triggerRedirect="redirect",Ie.pagerResize="pagerResize",Ie.pagerNumber="pagerNumber",Ie.pagerNext="pagerNext",Ie.pagerPrevious="pagerPrevious",Ie.pagerScrolling="pagerScrolling",Ie.facetClearAll="facetClearAll",Ie.facetSearch="facetSearch",Ie.facetSelect="facetSelect",Ie.facetSelectAll="facetSelectAll",Ie.facetDeselect="facetDeselect",Ie.facetExclude="facetExclude",Ie.facetUnexclude="facetUnexclude",Ie.facetUpdateSort="facetUpdateSort",Ie.facetShowMore="showMoreFacetResults",Ie.facetShowLess="showLessFacetResults",Ie.queryError="query";var Pe=((Ee={})[Se.triggerNotify]="queryPipelineTriggers",Ee[Se.triggerExecute]="queryPipelineTriggers",Ee[Se.triggerQuery]="queryPipelineTriggers",Ee[Se.triggerRedirect]="queryPipelineTriggers",Ee[Se.queryError]="errors",Ee[Se.pagerNext]="getMoreResults",Ee[Se.pagerPrevious]="getMoreResults",Ee[Se.pagerNumber]="getMoreResults",Ee[Se.pagerResize]="getMoreResults",Ee[Se.pagerScrolling]="getMoreResults",Ee[Se.facetSearch]="facet",Ee[Se.facetShowLess]="facet",Ee[Se.facetShowMore]="facet",Ee),ke=(Te.prototype.sendEvent=function(){return Promise.resolve()},Te.prototype.sendSearchEvent=function(){return Promise.resolve()},Te.prototype.sendClickEvent=function(){return Promise.resolve()},Te.prototype.sendCustomEvent=function(){return Promise.resolve()},Te.prototype.sendViewEvent=function(){return Promise.resolve()},Te.prototype.getVisit=function(){return Promise.resolve({id:"",visitorId:""})},Te.prototype.getHealth=function(){return Promise.resolve({status:""})},Te.prototype.registerBeforeSendEventHook=function(){},Te.prototype.addEventTypeMapping=function(){},Te);function Te(){this.runtime=new re}var Ae=(Oe.prototype.disable=function(){this.coveoAnalyticsClient instanceof ae&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new ke},Oe.prototype.enable=function(){this.coveoAnalyticsClient=new ae(this.opts)},Oe.prototype.logInterfaceLoad=function(){return this.logSearchEvent(Se.interfaceLoad)},Oe.prototype.logInterfaceChange=function(e){return this.logSearchEvent(Se.interfaceChange,e)},Oe.prototype.logDidYouMeanAutomatic=function(){return this.logSearchEvent(Se.didyoumeanAutomatic)},Oe.prototype.logDidYouMeanClick=function(){return this.logSearchEvent(Se.didyoumeanClick)},Oe.prototype.logResultsSort=function(e){return this.logSearchEvent(Se.resultsSort,e)},Oe.prototype.logSearchboxSubmit=function(){return this.logSearchEvent(Se.searchboxSubmit)},Oe.prototype.logSearchboxClear=function(){return this.logSearchEvent(Se.searchboxClear)},Oe.prototype.logSearchboxAsYouType=function(){return this.logSearchEvent(Se.searchboxAsYouType)},Oe.prototype.logBreadcrumbFacet=function(e){return this.logSearchEvent(Se.breadcrumbFacet,e)},Oe.prototype.logBreadcrumbResetAll=function(){return this.logSearchEvent(Se.breadcrumbResetAll)},Oe.prototype.logDocumentQuickview=function(e,t){return this.logClickEvent(Se.documentQuickview,e,t)},Oe.prototype.logDocumentOpen=function(e,t){return this.logClickEvent(Se.documentOpen,e,t)},Oe.prototype.logOmniboxAnalytics=function(e){return this.logSearchEvent(Se.omniboxAnalytics,e)},Oe.prototype.logOmniboxFromLink=function(e){return this.logSearchEvent(Se.omniboxFromLink,e)},Oe.prototype.logTriggerNotify=function(e){return this.logCustomEvent(Se.triggerNotify,e)},Oe.prototype.logTriggerExecute=function(e){return this.logCustomEvent(Se.triggerExecute,e)},Oe.prototype.logTriggerQuery=function(){var e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(Se.triggerQuery,e)},Oe.prototype.logTriggerRedirect=function(e){var t=h(h({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(Se.triggerRedirect,t)},Oe.prototype.logPagerResize=function(e){return this.logCustomEvent(Se.pagerResize,e)},Oe.prototype.logPagerNumber=function(e){return this.logCustomEvent(Se.pagerNumber,e)},Oe.prototype.logPagerNext=function(e){return this.logCustomEvent(Se.pagerNext,e)},Oe.prototype.logPagerPrevious=function(e){return this.logCustomEvent(Se.pagerPrevious,e)},Oe.prototype.logPagerScrolling=function(){return this.logCustomEvent(Se.pagerScrolling)},Oe.prototype.logFacetClearAll=function(e){return this.logSearchEvent(Se.facetClearAll,e)},Oe.prototype.logFacetSearch=function(e){return this.logSearchEvent(Se.facetSearch,e)},Oe.prototype.logFacetSelect=function(e){return this.logSearchEvent(Se.facetSelect,e)},Oe.prototype.logFacetDeselect=function(e){return this.logSearchEvent(Se.facetDeselect,e)},Oe.prototype.logFacetExclude=function(e){return this.logSearchEvent(Se.facetExclude,e)},Oe.prototype.logFacetUnexclude=function(e){return this.logSearchEvent(Se.facetUnexclude,e)},Oe.prototype.logFacetSelectAll=function(e){return this.logSearchEvent(Se.facetSelectAll,e)},Oe.prototype.logFacetUpdateSort=function(e){return this.logSearchEvent(Se.facetUpdateSort,e)},Oe.prototype.logFacetShowMore=function(e){return this.logCustomEvent(Se.facetShowMore,e)},Oe.prototype.logFacetShowLess=function(e){return this.logCustomEvent(Se.facetShowLess,e)},Oe.prototype.logQueryError=function(e){return this.logCustomEvent(Se.queryError,e)},Oe.prototype.logCustomEvent=function(e,t){var n=h(h({},this.provider.getBaseMetadata()),t),o={eventType:Pe[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:n};return this.coveoAnalyticsClient.sendCustomEvent(o)},Oe.prototype.logSearchEvent=function(e,t){var n=h(h({},this.provider.getBaseMetadata()),t),o=h(h({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:n,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(o)},Oe.prototype.logClickEvent=function(e,t,n,o){var r=h(h(h({},this.provider.getBaseMetadata()),n),o),i=h(h({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:r});return this.coveoAnalyticsClient.sendClickEvent(i)},Oe);function Oe(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new ke:new ae(e)}e.CoveoAnalyticsClient=ae,e.CoveoSearchPageClient=Ae,e.CoveoUA=me,e.SimpleAnalytics=xe,e.analytics=ce,e.donottrack=le,e.handleOneAnalyticsEvent=be,e.history=R,e.storage=x,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).coveoua={})}(this,function(e){"use strict";var n,t,d=function(){return(d=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function s(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function r(e,s,a,u){return new(a=a||Promise)(function(r,t){function n(e){try{i(u.next(e))}catch(e){t(e)}}function o(e){try{i(u.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?r(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(n,o)}i((u=u.apply(e,s||[])).next())})}function v(r,n){var o,i,s,e,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return e={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(o)throw new TypeError("Generator is already executing.");for(;a;)try{if(o=1,i&&(s=2&t[0]?i.return:t[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,t[1])).done)return s;switch(i=0,s&&(t=[2&t[0],s.value]),t[0]){case 0:case 1:s=t;break;case 4:return a.label++,{value:t[1],done:!1};case 5:a.label++,i=t[1],t=[0];continue;case 7:t=a.ops.pop(),a.trys.pop();continue;default:if(!(s=0<(s=a.trys).length&&s[s.length-1])&&(6===t[0]||2===t[0])){a=0;continue}if(3===t[0]&&(!s||t[1]>s[0]&&t[1]<s[3])){a.label=t[1];break}if(6===t[0]&&a.label<s[1]){a.label=s[1],s=t;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(t);break}s[2]&&a.ops.pop(),a.trys.pop();continue}t=n.call(r,a)}catch(e){t=[6,e],i=0}finally{o=s=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function a(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),o=0;for(t=0;t<r;t++)for(var i=arguments[t],s=0,a=i.length;s<a;s++,o++)n[o]=i[s];return n}(t=n=n||{}).search="search",t.click="click",t.custom="custom",t.view="view",t.collect="collect";var o=(i.prototype.sendEvent=function(a,u){return r(this,void 0,void 0,function(){var t,r,n,o,i,s;return v(this,function(e){switch(e.label){case 0:return t=this.opts,r=t.baseUrl,n=t.visitorIdProvider,o=this.shouldAppendVisitorId(a)?this.visitorIdParam:"",[4,fetch(r+"/analytics/"+a+o,{method:"POST",headers:this.getHeaders(),mode:"cors",body:JSON.stringify(u),credentials:"include"})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return(s=e.sent()).visitorId&&(n.currentVisitorId=s.visitorId),[2,s];case 3:try{i.json()}catch(e){}throw console.error('An error has occured when sending the "'+a+'" event.',i,u),new Error('An error has occurred when sending the "'+a+'" event. Check the console logs for more details.')}})})},i.prototype.shouldAppendVisitorId=function(e){return-1!==[n.click,n.custom,n.search,n.view].indexOf(e)},Object.defineProperty(i.prototype,"visitorIdParam",{get:function(){var e=this.opts.visitorIdProvider.currentVisitorId;return e?"?visitor="+e:""},enumerable:!0,configurable:!0}),i.prototype.getHeaders=function(){var e=this.opts.token;return d(d({},e?{Authorization:"Bearer "+e}:{}),{"Content-Type":"application/json"})},i);function i(e){this.opts=e}function u(){return"undefined"!=typeof navigator}function c(){return"undefined"!=typeof localStorage}function l(){return u()&&navigator.cookieEnabled}function p(){return"undefined"!=typeof crypto&&void 0!==crypto.getRandomValues}function f(e,t){return-1!==h.indexOf(e)?d({language:document.documentElement.lang,userAgent:navigator.userAgent},t):t}var h=[n.click,n.custom,n.search,n.view],y=(g.set=function(e,t,r){var n,o,i,s,a;s=r?((i=new Date).setTime(i.getTime()+r),"; expires="+i.toGMTString()):"",-1===(a=location.hostname).indexOf(".")?document.cookie=e+"="+t+s+"; path=/":((o=a.split(".")).shift(),n="."+o.join("."),document.cookie=e+"="+t+s+"; path=/; domain="+n,null!=g.get(e)&&g.get(e)==t||(n="."+a,document.cookie=e+"="+t+s+"; path=/; domain="+n))},g.get=function(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){var o=r[n];if(0==(o=o.replace(/^\s+/,"")).indexOf(t))return o.substring(t.length,o.length)}return null},g.erase=function(e){g.set(e,"",-1)},g);function g(){}function m(){return c()?localStorage:l()?new E:"undefined"!=typeof sessionStorage?sessionStorage:new I}var E=(w.prototype.getItem=function(e){return y.get(""+w.prefix+e)},w.prototype.removeItem=function(e){y.erase(""+w.prefix+e)},w.prototype.setItem=function(e,t){y.set(""+w.prefix+e,t)},w.prefix="coveo_",w);function w(){}var b=(S.prototype.getItem=function(e){return localStorage.getItem(e)||this.cookieStorage.getItem(e)},S.prototype.removeItem=function(e){this.cookieStorage.removeItem(e),localStorage.removeItem(e)},S.prototype.setItem=function(e,t){localStorage.setItem(e,t),this.cookieStorage.setItem(e,t)},S);function S(){this.cookieStorage=new E}var I=(C.prototype.getItem=function(e){return null},C.prototype.removeItem=function(e){},C.prototype.setItem=function(e,t){},C);function C(){}var x=Object.freeze({__proto__:null,preferredStorage:null,getAvailableStorage:m,CookieStorage:E,CookieAndLocalStorage:b,NullStorage:I}),k="__coveo.analytics.history",P=(A.prototype.addElement=function(e){e.internalTime=(new Date).getTime(),this.cropQueryElement(e);var t=this.getHistoryWithInternalTime();null!=t?this.isValidEntry(e)&&this.setHistory([e].concat(t)):this.setHistory([e])},A.prototype.getHistory=function(){var e=this.getHistoryWithInternalTime();return this.stripInternalTime(e)},A.prototype.getHistoryWithInternalTime=function(){try{var e=this.store.getItem(k);return e?JSON.parse(e):[]}catch(e){return[]}},A.prototype.setHistory=function(e){try{this.store.setItem(k,JSON.stringify(e.slice(0,20)))}catch(e){}},A.prototype.clear=function(){try{this.store.removeItem(k)}catch(e){}},A.prototype.getMostRecentElement=function(){var e=this.getHistoryWithInternalTime();return null==e?null:e.sort(function(e,t){return(t.internalTime||0)-(e.internalTime||0)})[0]},A.prototype.cropQueryElement=function(e){e.name&&"query"==e.name.toLowerCase()&&null!=e.value&&(e.value=e.value.slice(0,75))},A.prototype.isValidEntry=function(e){var t=this.getMostRecentElement();return!t||t.value!=e.value||6e4<(e.internalTime||0)-(t.internalTime||0)},A.prototype.stripInternalTime=function(e){return e.map(function(e){return{name:e.name,time:e.time,value:e.value}})},A);function A(e){this.store=e||m(),this.store instanceof E||!l()||(new E).removeItem(k)}function T(e,t){return e===n.view?(F(t.contentIdValue),d({location:window.location.toString(),referrer:document.referrer,title:document.title},t)):t}function O(t){return[function(e){return W.test(e)},function(e){return J.test(e)},function(e){return-1!==M.indexOf(e)},function(e){return"custom"===e}].some(function(e){return e(t)})}var R=Object.freeze({__proto__:null,STORE_KEY:k,MAX_NUMBER_OF_HISTORY_ELEMENTS:20,MIN_THRESHOLD_FOR_DUPLICATE_VALUE:6e4,MAX_VALUE_SIZE:75,HistoryStore:P,default:P}),F=function(e){var t=new P,r={name:"PageView",value:e,time:JSON.stringify(new Date)};t.addElement(r)},L=function(e){return e?(Number(e)^V(new Uint8Array(1))[0]%16>>Number(e)/4).toString(16):(""+1e7+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,L)},V=function(e){if(p())return crypto.getRandomValues(e);for(var t=0,r=0;t<e.length;t++)0==(3&t)&&(r=4294967296*Math.random()),e[t]=r>>>((3&t)<<3)&255;return e},j={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",price:"pr",quantity:"qt",coupon:"cc",position:"ps"},N={id:"id",name:"nm",brand:"br",category:"ca",variant:"va",position:"ps",price:"pr"},q=d(d(d(d(d({},{eventCategory:"ec",eventAction:"ea",eventLabel:"el",eventValue:"ev",page:"dp",visitorId:"cid",clientId:"cid",userId:"uid",currencyCode:"cu"}),{action:"pa",list:"pal",listSource:"pls"}),{id:"ti",revenue:"tr",tax:"tt",shipping:"ts",coupon:"tcc",affiliation:"ta",step:"cos",option:"col"}),{hitType:"t",pageViewId:"pid",encoding:"de",location:"dl",referrer:"dr",screenColor:"sd",screenResolution:"sr",title:"dt",userAgent:"ua",language:"ul",eventId:"z",time:"tm"}),{anonymizeIp:"aip"}),U=Object.keys,_=function(o,i,s){return U(o).reduce(function(e,t){var r,n="il"+(i+1)+"pi"+(s+1)+(N[t]||t);return d(d({},e),((r={})[n]=o[t],r))},{})},M=U(q).map(function(e){return q[e]}),B=U(j).map(function(e){return j[e]}),D=U(N).map(function(e){return N[e]}),H=a(B,["custom"]).join("|"),Q=a(D,["custom"]).join("|"),z="(pr[0-9]+)",Y="(il[0-9]+pi[0-9]+)",W=new RegExp("^"+z+"("+H+")$"),J=new RegExp("^("+Y+"("+Q+"))|(il[0-9]+nm)$"),$=new RegExp("^"+z+"custom$"),G=new RegExp("^"+Y+"custom$"),K=function(n,o){return U(o).reduce(function(e,t){var r;return d(d({},e),((r={})[""+n+t]=o[t],r))},{})},X=(Z.prototype.sendEvent=function(i,s){return r(this,void 0,void 0,function(){var t,r,n,o;return v(this,function(e){if(!navigator.sendBeacon)throw new Error('navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".');return t=this.opts.baseUrl,r=this.encodeForEventType(i,s),n=this.getQueryParamsForEventType(i),o=t+"/analytics/"+i+"?"+n,console.log('Sending beacon for "'+i+'" with: ',JSON.stringify(s)),navigator.sendBeacon(o,new Blob([r],{type:"application/x-www-form-urlencoded"})),[2]})})},Z.prototype.encodeForEventType=function(e,t){return this.isEventTypeLegacy(e)?this.encodeForLegacyType(e,t):this.encodeForFormUrlEncoded(d({access_token:this.opts.token},t))},Z.prototype.getQueryParamsForEventType=function(e){var t=this.opts,r=t.token,n=t.visitorIdProvider.currentVisitorId;return[r&&this.isEventTypeLegacy(e)?"access_token="+r:"",n?"visitorId="+n:""].filter(function(e){return!!e}).join("&")},Z.prototype.isEventTypeLegacy=function(e){return-1!==[n.click,n.custom,n.search,n.view].indexOf(e)},Z.prototype.encodeForLegacyType=function(e,t){return e+"Event="+encodeURIComponent(JSON.stringify(t))},Z.prototype.encodeForFormUrlEncoded=function(t){var r=this;return Object.keys(t).filter(function(e){return!!t[e]}).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(r.encodeValue(t[e]))}).join("&")},Z.prototype.encodeValue=function(e){return"number"==typeof e||"string"==typeof e||"boolean"==typeof e?e:JSON.stringify(e)},Z);function Z(e){this.opts=e}var ee=(te.prototype.sendEvent=function(e,t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,Promise.resolve()]})})},te);function te(){}var re=function(e,t){c()&&l()?this.storage=new b:c()?this.storage=localStorage:(console.warn("BrowserRuntime detected no valid storage available.",this),this.storage=new I),this.beaconClient=new X(e),window.addEventListener("beforeunload",function(){return t()})},ne=function(){this.storage=new I,this.beaconClient=new ee},oe=function(){this.storage=new I,this.beaconClient=new ee},ie={default:"https://platform.cloud.coveo.com/rest/ua",production:"https://platform.cloud.coveo.com/rest/ua",hipaa:"https://platformhipaa.cloud.coveo.com/rest/ua"},se=(Object.defineProperty(ae.prototype,"defaultOptions",{get:function(){return{endpoint:ie.default,token:"",version:"v15"}},enumerable:!0,configurable:!0}),ae.prototype.initRuntime=function(e){var t=this;return"undefined"!=typeof window&&"undefined"!=typeof document?new re(e,function(){return t.flushBufferWithBeacon()}):new ne},Object.defineProperty(ae.prototype,"analyticsBeaconClient",{get:function(){return this.runtime.beaconClient},enumerable:!0,configurable:!0}),Object.defineProperty(ae.prototype,"storage",{get:function(){return this.runtime.storage},enumerable:!0,configurable:!0}),ae.prototype.initVisitorId=function(){var e=this.visitorId||this.storage.getItem("visitorId")||"";this.currentVisitorId=e||L()},Object.defineProperty(ae.prototype,"currentVisitorId",{get:function(){return this.visitorId},set:function(e){this.visitorId=e,this.storage.setItem("visitorId",e)},enumerable:!0,configurable:!0}),ae.prototype.sendEvent=function(f){for(var h=[],e=1;e<arguments.length;e++)h[e-1]=arguments[e];return r(this,void 0,void 0,function(){var t,r,n,o,i,s,a,u,c,l,p=this;return v(this,function(e){switch(e.label){case 0:return t=this.eventTypeMapping[f]||{},n=void 0===(r=t.newEventType)?f:r,i=void 0===(o=t.variableLengthArgumentsNames)?[]:o,a=void 0!==(s=t.addVisitorIdParameter)&&s,c=void 0!==(u=t.usesMeasurementProtocol)&&u,l=[function(e){return 0<i.length?p.parseVariableArgumentsPayload(i,e):e[0]},function(e){return d({visitorId:a?p.visitorId:""},e)},function(e){return c?p.ensureAnonymousUserWhenUsingApiKey(e):e},function(e){return p.beforeSendHooks.reduce(function(e,t){return t(f,e)},e)},function(e){return p.removeEmptyPayloadValues(e,f)},function(e){return p.validateParams(e)},function(e){return c?U(o=e).reduce(function(e,t){var r,n=q[t]||t;return d(d({},e),((r={})[n]=o[t],r))},{}):e;var o},function(e){return c?p.removeUnknownParameters(e):e},function(e){return c?p.processCustomParameters(e):e}].reduce(function(e,t){return t(e)},h),this.bufferedRequests.push({eventType:n,payload:l,handled:!1}),[4,this.deferExecution()];case 1:return e.sent(),[4,this.sendFromBufferWithFetch()];case 2:return[2,e.sent()]}})})},ae.prototype.deferExecution=function(){return new Promise(function(e){return setTimeout(e,0)})},ae.prototype.flushBufferWithBeacon=function(){for(;this.hasPendingRequests();){var e=this.bufferedRequests.pop(),t=e.eventType,r=e.payload;this.analyticsBeaconClient.sendEvent(t,r)}},ae.prototype.sendFromBufferWithFetch=function(){return r(this,void 0,void 0,function(){var t,r,n;return v(this,function(e){return(t=this.bufferedRequests.shift())?(r=t.eventType,n=t.payload,[2,this.analyticsFetchClient.sendEvent(r,n)]):[2]})})},ae.prototype.hasPendingRequests=function(){return 0<this.bufferedRequests.length},ae.prototype.clear=function(){this.storage.removeItem("visitorId"),(new P).clear()},ae.prototype.sendSearchEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.search,t)]})})},ae.prototype.sendClickEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.click,t)]})})},ae.prototype.sendCustomEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.custom,t)]})})},ae.prototype.sendViewEvent=function(t){return r(this,void 0,void 0,function(){return v(this,function(e){return[2,this.sendEvent(n.view,t)]})})},ae.prototype.getVisit=function(){return r(this,void 0,void 0,function(){var t;return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/visit")];case 1:return[4,e.sent().json()];case 2:return t=e.sent(),this.visitorId=t.visitorId,[2,t]}})})},ae.prototype.getHealth=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,fetch(this.baseUrl+"/analytics/monitoring/health")];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}})})},ae.prototype.registerBeforeSendEventHook=function(e){this.beforeSendHooks.push(e)},ae.prototype.addEventTypeMapping=function(e,t){this.eventTypeMapping[e]=t},ae.prototype.parseVariableArgumentsPayload=function(e,t){for(var r={},n=0,o=t.length;n<o;n++){var i=t[n];if("string"==typeof i)r[e[n]]=i;else if("object"==typeof i)return d(d({},r),i)}return r},ae.prototype.isKeyAllowedEmpty=function(e,t){var r;return-1!==((r={})[n.search]=["queryText"],(r[e]||[]).indexOf(t))},ae.prototype.removeEmptyPayloadValues=function(n,r){var o=this;return Object.keys(n).filter(function(e){return o.isKeyAllowedEmpty(r,e)||null!=(t=n[e])&&""!==t;var t}).reduce(function(e,t){var r;return d(d({},e),((r={})[t]=n[t],r))},{})},ae.prototype.removeUnknownParameters=function(n){return Object.keys(n).filter(function(e){if(O(e))return!0;console.log(e,"is not processed by coveoua")}).reduce(function(e,t){var r;return d(d({},e),((r={})[t]=n[t],r))},{})},ae.prototype.processCustomParameters=function(e){var i,t=e.custom,r=s(e,["custom"]),n=U(i=r).reduce(function(e,t){var r,n=$.exec(t)||G.exec(t);if(n){var o=n[1];return d(d({},e),K(o,i[t]))}return d(d({},e),((r={})[t]=i[t],r))},{});return d(d({},t||{}),n)},ae.prototype.validateParams=function(e){var t=e.anonymizeIp,r=s(e,["anonymizeIp"]);return void 0!==t&&-1==["0","false","undefined","null","{}","[]",""].indexOf((""+t).toLowerCase())&&(r.anonymizeIp=1),r},ae.prototype.ensureAnonymousUserWhenUsingApiKey=function(e){var t,r=e.userId,n=s(e,["userId"]);return null!=(t=this.options.token)&&t.startsWith("xx")&&!r?(n.userId="anonymous",n):e},Object.defineProperty(ae.prototype,"baseUrl",{get:function(){var e=this.options,t=e.version,r=e.endpoint,n=-1!==r.indexOf(".cloud.coveo.com");return r+(n?"":"/rest")+"/"+t},enumerable:!0,configurable:!0}),ae);function ae(e){if(!e)throw new Error("You have to pass options to this constructor");this.options=d(d({},this.defaultOptions),e),this.visitorId="",this.bufferedRequests=[],this.beforeSendHooks=[T,f],this.eventTypeMapping={};var t={baseUrl:this.baseUrl,token:this.options.token,visitorIdProvider:this};this.runtime=this.initRuntime(t),this.analyticsFetchClient=new o(t),this.initVisitorId()}var ue=Object.freeze({__proto__:null,Version:"v15",Endpoints:ie,CoveoAnalyticsClient:se,default:se}),ce=u()?[!0,"yes","1"].indexOf(navigator.doNotTrack||navigator.msDoNotTrack||window.doNotTrack):0,le=Object.freeze({__proto__:null,doNotTrack:ce,default:ce}),pe=(fe.prototype.register=function(e,t){this.plugins[e]=t},fe.prototype.execute=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=this.plugins[e];return o[t].apply(o,r)},fe);function fe(){this.plugins={}}function he(e){return e.protocol+"//"+e.hostname+(0===e.pathname.indexOf("/")?e.pathname:"/"+e.pathname)+e.search}var de={pageview:"pageview",event:"event"},ve=Object.keys(de).map(function(e){return de[e]}),ye=(ge.prototype.addProduct=function(e){this.products.push(e)},ge.prototype.addImpression=function(e){this.impressions.push(e)},ge.prototype.setAction=function(e,t){this.action=e,this.actionData=t},ge.prototype.clearData=function(){this.products=[],this.impressions=[],this.action=void 0,this.actionData={}},ge.prototype.addHooksForECEvents=function(){var o=this;this.client.registerBeforeSendEventHook(function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=t[0];return-1!==ve.indexOf(e)?o.addECDataToPayload(e,n):n})},ge.prototype.addHooksForPageView=function(){this.client.addEventTypeMapping(de.pageview,{newEventType:n.collect,variableLengthArgumentsNames:["page"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ge.prototype.addHooksForEvent=function(){this.client.addEventTypeMapping(de.event,{newEventType:n.collect,variableLengthArgumentsNames:["eventCategory","eventAction","eventLabel","eventValue"],addVisitorIdParameter:!0,usesMeasurementProtocol:!0})},ge.prototype.addECDataToPayload=function(e,t){var r=d(d(d(d({},this.getLocationInformation(e,t)),this.getDefaultContextInformation(e)),this.action?{action:this.action}:{}),this.actionData||{}),n=this.products.reduce(function(e,t,r){return d(d({},e),(i=r,U(o=t).reduce(function(e,t){var r,n="pr"+(i+1)+(j[t]||t);return d(d({},e),((r={})[n]=o[t],r))},{})));var o,i},{}),o=this.getImpressionsByList().reduce(function(e,t,r){return d(d({},e),function(e,n){var t=e.impressions.reduce(function(e,t,r){return d(d({},e),_(t,n,r))},{});return e.listName&&(t["il"+(n+1)+"nm"]=e.listName),t}(t,r))},{});return this.clearData(),d(d(d(d({},o),n),r),t)},ge.prototype.getImpressionsByList=function(){return this.impressions.reduce(function(e,t){var r=t.list,n=s(t,["list"]),o=e.find(function(e){return e.listName===r});return o?o.impressions.push(n):e.push({listName:r,impressions:[n]}),e},[])},ge.prototype.updateStateForNewPageView=function(e){this.hasSentFirstPageView&&(this.pageViewId=this.uuidGenerator(),this.lastReferrer=this.lastLocation),e.page?this.lastLocation=""+this.lastLocation.split("/").slice(0,3).join("/")+e.page.replace(/^\/?(.*)$/,"/$1"):this.lastLocation=he(window.location),this.hasSentFirstPageView=!0},ge.prototype.getLocationInformation=function(e,t){return e===de.pageview&&this.updateStateForNewPageView(t),{referrer:this.lastReferrer,location:this.lastLocation}},ge.prototype.getDefaultContextInformation=function(e){var t={hitType:e,pageViewId:this.pageViewId},r={title:document.title,encoding:document.characterSet},n={screenResolution:screen.width+"x"+screen.height,screenColor:screen.colorDepth+"-bit"},o={language:navigator.language,userAgent:navigator.userAgent},i={time:Date.now().toString(),eventId:this.uuidGenerator()};return d(d(d(d(d({},t),i),n),o),r)},ge);function ge(e){var t=e.client,r=e.uuidGenerator,n=void 0===r?L:r;this.products=[],this.impressions=[],this.actionData={},this.client=t,this.uuidGenerator=n,this.pageViewId=n(),this.lastLocation=he(window.location),this.lastReferrer=document.referrer,this.addHooksForPageView(),this.addHooksForEvent(),this.addHooksForECEvents()}var me=(Ee.prototype.init=function(e,t){var r=this;if(!e)throw new Error("You must pass your token when you call 'init'");if("string"==typeof e?(t=t||ie.default,this.client=new se({token:e,endpoint:t})):"object"==typeof e&&void 0!==e.sendEvent&&(this.client=e),!this.client)throw new Error("You must pass either your token or a valid object when you call 'init'");this.plugins.register("ec",new ye({client:this.client})),this.client.registerBeforeSendEventHook(function(e,t){return d(d({},t),r.params)})},Ee.prototype.initForProxy=function(e){if(!e)throw new Error("You must pass your endpoint when you call 'initForProxy'");if("string"!=typeof e)throw new Error("You must pass a string as the endpoint parameter when you call 'initForProxy'");this.client=new se({endpoint:e})},Ee.prototype.set=function(t,e){var r=this;"string"==typeof t?this.params[t]=e:Object.keys(t).map(function(e){r.params[e]=t[e]})},Ee.prototype.send=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=t[0],o=t.slice(1);if(void 0===this.client)throw new Error("You must call init before sending an event");if(!n)throw new Error('You must provide an event type when calling "send".');return(e=this.client).sendEvent.apply(e,a([n.toLowerCase()],o))},Ee.prototype.onLoad=function(e){if(void 0===e)throw new Error("You must pass a function when you call 'onLoad'");e()},Ee.prototype.callPlugin=function(e,t){for(var r,n=[],o=2;o<arguments.length;o++)n[o-2]=arguments[o];(r=this.plugins).execute.apply(r,a([e,t],n))},Ee.prototype.reset=function(){this.client=void 0,this.plugins=new pe,this.params={}},Ee);function Ee(){this.plugins=new pe,this.params={}}function we(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/.exec(e),o=(n[1],n[2]),i=n[3],s=Ce[i];if(o&&i)return Ce.callPlugin.apply(Ce,a([o,i],t));if(s)return s.apply(Ce,t);throw new Error('The action "'+e+'" does not exist. Available actions: '+["init","set","send","onLoad","callPlugin"].join(", ")+".")}var be,Se,Ie,Ce=new me,xe=Object.freeze({__proto__:null,CoveoUA:me,coveoua:Ce,handleOneAnalyticsEvent:we,default:we});(Ie=Se=Se||{}).interfaceLoad="interfaceLoad",Ie.interfaceChange="interfaceChange",Ie.didyoumeanAutomatic="didyoumeanAutomatic",Ie.didyoumeanClick="didyoumeanClick",Ie.resultsSort="resultsSort",Ie.searchboxSubmit="searchboxSubmit",Ie.searchboxClear="searchboxClear",Ie.searchboxAsYouType="searchboxAsYouType",Ie.breadcrumbFacet="breadcrumbFacet",Ie.breadcrumbResetAll="breadcrumbResetAll",Ie.documentQuickview="documentQuickview",Ie.documentOpen="documentOpen",Ie.omniboxAnalytics="omniboxAnalytics",Ie.omniboxFromLink="omniboxFromLink",Ie.triggerNotify="notify",Ie.triggerExecute="execute",Ie.triggerQuery="query",Ie.triggerRedirect="redirect",Ie.pagerResize="pagerResize",Ie.pagerNumber="pagerNumber",Ie.pagerNext="pagerNext",Ie.pagerPrevious="pagerPrevious",Ie.pagerScrolling="pagerScrolling",Ie.facetClearAll="facetClearAll",Ie.facetSearch="facetSearch",Ie.facetSelect="facetSelect",Ie.facetSelectAll="facetSelectAll",Ie.facetDeselect="facetDeselect",Ie.facetExclude="facetExclude",Ie.facetUnexclude="facetUnexclude",Ie.facetUpdateSort="facetUpdateSort",Ie.facetShowMore="showMoreFacetResults",Ie.facetShowLess="showLessFacetResults",Ie.queryError="query",Ie.queryErrorBack="errorBack",Ie.queryErrorClear="errorClearQuery",Ie.queryErrorRetry="errorRetry";var ke=((be={})[Se.triggerNotify]="queryPipelineTriggers",be[Se.triggerExecute]="queryPipelineTriggers",be[Se.triggerQuery]="queryPipelineTriggers",be[Se.triggerRedirect]="queryPipelineTriggers",be[Se.queryError]="errors",be[Se.queryErrorBack]="errors",be[Se.queryErrorClear]="errors",be[Se.queryErrorRetry]="errors",be[Se.pagerNext]="getMoreResults",be[Se.pagerPrevious]="getMoreResults",be[Se.pagerNumber]="getMoreResults",be[Se.pagerResize]="getMoreResults",be[Se.pagerScrolling]="getMoreResults",be[Se.facetSearch]="facet",be[Se.facetShowLess]="facet",be[Se.facetShowMore]="facet",be),Pe=(Ae.prototype.sendEvent=function(){return Promise.resolve()},Ae.prototype.sendSearchEvent=function(){return Promise.resolve()},Ae.prototype.sendClickEvent=function(){return Promise.resolve()},Ae.prototype.sendCustomEvent=function(){return Promise.resolve()},Ae.prototype.sendViewEvent=function(){return Promise.resolve()},Ae.prototype.getVisit=function(){return Promise.resolve({id:"",visitorId:""})},Ae.prototype.getHealth=function(){return Promise.resolve({status:""})},Ae.prototype.registerBeforeSendEventHook=function(){},Ae.prototype.addEventTypeMapping=function(){},Ae);function Ae(){this.runtime=new oe}var Te=(Oe.prototype.disable=function(){this.coveoAnalyticsClient instanceof se&&this.coveoAnalyticsClient.clear(),this.coveoAnalyticsClient=new Pe},Oe.prototype.enable=function(){this.coveoAnalyticsClient=new se(this.opts)},Oe.prototype.logInterfaceLoad=function(){return this.logSearchEvent(Se.interfaceLoad)},Oe.prototype.logInterfaceChange=function(e){return this.logSearchEvent(Se.interfaceChange,e)},Oe.prototype.logDidYouMeanAutomatic=function(){return this.logSearchEvent(Se.didyoumeanAutomatic)},Oe.prototype.logDidYouMeanClick=function(){return this.logSearchEvent(Se.didyoumeanClick)},Oe.prototype.logResultsSort=function(e){return this.logSearchEvent(Se.resultsSort,e)},Oe.prototype.logSearchboxSubmit=function(){return this.logSearchEvent(Se.searchboxSubmit)},Oe.prototype.logSearchboxClear=function(){return this.logSearchEvent(Se.searchboxClear)},Oe.prototype.logSearchboxAsYouType=function(){return this.logSearchEvent(Se.searchboxAsYouType)},Oe.prototype.logBreadcrumbFacet=function(e){return this.logSearchEvent(Se.breadcrumbFacet,e)},Oe.prototype.logBreadcrumbResetAll=function(){return this.logSearchEvent(Se.breadcrumbResetAll)},Oe.prototype.logDocumentQuickview=function(e,t){return this.logClickEvent(Se.documentQuickview,e,t)},Oe.prototype.logDocumentOpen=function(e,t){return this.logClickEvent(Se.documentOpen,e,t)},Oe.prototype.logOmniboxAnalytics=function(e){return this.logSearchEvent(Se.omniboxAnalytics,e)},Oe.prototype.logOmniboxFromLink=function(e){return this.logSearchEvent(Se.omniboxFromLink,e)},Oe.prototype.logTriggerNotify=function(e){return this.logCustomEvent(Se.triggerNotify,e)},Oe.prototype.logTriggerExecute=function(e){return this.logCustomEvent(Se.triggerExecute,e)},Oe.prototype.logTriggerQuery=function(){var e={query:this.provider.getSearchEventRequestPayload().queryText};return this.logCustomEvent(Se.triggerQuery,e)},Oe.prototype.logTriggerRedirect=function(e){var t=d(d({},e),{query:this.provider.getSearchEventRequestPayload().queryText});return this.logCustomEvent(Se.triggerRedirect,t)},Oe.prototype.logPagerResize=function(e){return this.logCustomEvent(Se.pagerResize,e)},Oe.prototype.logPagerNumber=function(e){return this.logCustomEvent(Se.pagerNumber,e)},Oe.prototype.logPagerNext=function(e){return this.logCustomEvent(Se.pagerNext,e)},Oe.prototype.logPagerPrevious=function(e){return this.logCustomEvent(Se.pagerPrevious,e)},Oe.prototype.logPagerScrolling=function(){return this.logCustomEvent(Se.pagerScrolling)},Oe.prototype.logFacetClearAll=function(e){return this.logSearchEvent(Se.facetClearAll,e)},Oe.prototype.logFacetSearch=function(e){return this.logSearchEvent(Se.facetSearch,e)},Oe.prototype.logFacetSelect=function(e){return this.logSearchEvent(Se.facetSelect,e)},Oe.prototype.logFacetDeselect=function(e){return this.logSearchEvent(Se.facetDeselect,e)},Oe.prototype.logFacetExclude=function(e){return this.logSearchEvent(Se.facetExclude,e)},Oe.prototype.logFacetUnexclude=function(e){return this.logSearchEvent(Se.facetUnexclude,e)},Oe.prototype.logFacetSelectAll=function(e){return this.logSearchEvent(Se.facetSelectAll,e)},Oe.prototype.logFacetUpdateSort=function(e){return this.logSearchEvent(Se.facetUpdateSort,e)},Oe.prototype.logFacetShowMore=function(e){return this.logCustomEvent(Se.facetShowMore,e)},Oe.prototype.logFacetShowLess=function(e){return this.logCustomEvent(Se.facetShowLess,e)},Oe.prototype.logQueryError=function(e){return this.logCustomEvent(Se.queryError,e)},Oe.prototype.logQueryErrorBack=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(Se.queryErrorBack)];case 1:return e.sent(),[2,this.logSearchEvent(Se.queryErrorBack)]}})})},Oe.prototype.logQueryErrorRetry=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(Se.queryErrorRetry)];case 1:return e.sent(),[2,this.logSearchEvent(Se.queryErrorRetry)]}})})},Oe.prototype.logQueryErrorClear=function(){return r(this,void 0,void 0,function(){return v(this,function(e){switch(e.label){case 0:return[4,this.logCustomEvent(Se.queryErrorClear)];case 1:return e.sent(),[2,this.logSearchEvent(Se.queryErrorClear)]}})})},Oe.prototype.logCustomEvent=function(e,t){var r=d(d({},this.provider.getBaseMetadata()),t),n={eventType:ke[e],eventValue:e,lastSearchQueryUid:this.provider.getSearchUID(),customData:r};return this.coveoAnalyticsClient.sendCustomEvent(n)},Oe.prototype.logSearchEvent=function(e,t){var r=d(d({},this.provider.getBaseMetadata()),t),n=d(d({},this.provider.getSearchEventRequestPayload()),{searchQueryUid:this.provider.getSearchUID(),customData:r,actionCause:e});return this.coveoAnalyticsClient.sendSearchEvent(n)},Oe.prototype.logClickEvent=function(e,t,r,n){var o=d(d(d({},this.provider.getBaseMetadata()),r),n),i=d(d({},t),{searchQueryUid:this.provider.getSearchUID(),actionCause:e,customData:o});return this.coveoAnalyticsClient.sendClickEvent(i)},Oe);function Oe(e,t){this.opts=e,this.provider=t,this.coveoAnalyticsClient=!1===e.enableAnalytics?new Pe:new se(e)}e.CoveoAnalyticsClient=se,e.CoveoSearchPageClient=Te,e.CoveoUA=me,e.SimpleAnalytics=xe,e.analytics=ue,e.donottrack=le,e.handleOneAnalyticsEvent=we,e.history=R,e.storage=x,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
//# sourceMappingURL=library.js.map |
{ | ||
"name": "coveo.analytics", | ||
"version": "2.4.1", | ||
"version": "2.4.2", | ||
"description": "📈 Coveo analytics client (node and browser compatible) ", | ||
@@ -10,3 +10,3 @@ "main": "dist/library.js", | ||
"scripts": { | ||
"lint": "prettier **/*.* --write", | ||
"lint": "prettier */**/*.* --write", | ||
"build": "rollup -c", | ||
@@ -13,0 +13,0 @@ "start": "rollup -c -w --environment SERVE", |
@@ -245,2 +245,84 @@ import * as fetchMock from 'fetch-mock'; | ||
describe('with userId auto-detection', () => { | ||
const eventType = '🛂'; | ||
const expectUserId = (userId: {[key: string]: string}) => { | ||
const [body] = getParsedBodyCalls(); | ||
expect(body).toMatchObject(userId); | ||
}; | ||
describe('for API keys', () => { | ||
beforeEach(() => { | ||
client = new CoveoAnalyticsClient({ | ||
token: 'xxapikey', | ||
endpoint: anEndpoint, | ||
version: A_VERSION, | ||
}); | ||
mockFetchRequestForEventType(EventType.custom); | ||
}); | ||
describe('with measurement protocol', () => { | ||
beforeEach(() => { | ||
client.addEventTypeMapping(eventType, { | ||
newEventType: EventType.custom, | ||
usesMeasurementProtocol: true, | ||
}); | ||
}); | ||
it('should set the absent userId to anonymous', async () => { | ||
await client.sendEvent(eventType); | ||
expectUserId({uid: 'anonymous'}); | ||
}); | ||
it('should leave existing userIds', async () => { | ||
await client.sendEvent(eventType, {userId: 'bob'}); | ||
expectUserId({uid: 'bob'}); | ||
}); | ||
}); | ||
describe('without measurement protocol', () => { | ||
beforeEach(() => { | ||
client.addEventTypeMapping(eventType, { | ||
newEventType: EventType.custom, | ||
usesMeasurementProtocol: false, | ||
}); | ||
}); | ||
it('should do nothing with absent userId', async () => { | ||
await client.sendEvent(eventType); | ||
expectUserId({}); | ||
}); | ||
it('should leave existing userIds', async () => { | ||
await client.sendEvent(eventType, {userId: 'bob'}); | ||
expectUserId({userId: 'bob'}); | ||
}); | ||
}); | ||
}); | ||
describe('for OAuth Tokens', () => { | ||
beforeEach(() => { | ||
client = new CoveoAnalyticsClient({ | ||
token: 'xtoken', | ||
endpoint: anEndpoint, | ||
version: A_VERSION, | ||
}); | ||
mockFetchRequestForEventType(EventType.custom); | ||
client.addEventTypeMapping(eventType, { | ||
newEventType: EventType.custom, | ||
usesMeasurementProtocol: true, | ||
}); | ||
}); | ||
it('should do nothing with absent userId', async () => { | ||
await client.sendEvent(eventType); | ||
expectUserId({}); | ||
}); | ||
it('should leave existing userIds', async () => { | ||
await client.sendEvent(eventType, {userId: 'bob'}); | ||
expectUserId({uid: 'bob'}); | ||
}); | ||
}); | ||
}); | ||
it('should support clearing cookies for visitorId and historyStore', async () => { | ||
@@ -247,0 +329,0 @@ const visitorId = 'foo'; |
@@ -31,2 +31,3 @@ import {IAnalyticsBeaconClientOptions} from './analyticsBeaconClient'; | ||
import HistoryStore from '../history'; | ||
import {isApiKey} from './token'; | ||
@@ -168,2 +169,4 @@ export const Version = 'v15'; | ||
}); | ||
const setAnonymousUserStep: ProcessPayloadStep = (currentPayload) => | ||
usesMeasurementProtocol ? this.ensureAnonymousUserWhenUsingApiKey(currentPayload) : currentPayload; | ||
const processBeforeSendHooksStep: ProcessPayloadStep = (currentPayload) => | ||
@@ -184,2 +187,3 @@ this.beforeSendHooks.reduce((newPayload, current) => current(eventType, newPayload), currentPayload); | ||
addVisitorIdStep, | ||
setAnonymousUserStep, | ||
processBeforeSendHooksStep, | ||
@@ -347,2 +351,12 @@ cleanPayloadStep, | ||
private ensureAnonymousUserWhenUsingApiKey(payload: IRequestPayload): IRequestPayload { | ||
const {userId, ...rest} = payload; | ||
if (isApiKey(this.options.token) && !userId) { | ||
rest['userId'] = 'anonymous'; | ||
return rest; | ||
} else { | ||
return payload; | ||
} | ||
} | ||
private get baseUrl(): string { | ||
@@ -349,0 +363,0 @@ const {version, endpoint} = this.options; |
@@ -1,2 +0,2 @@ | ||
import {hasCryptoRandomValues} from "../detector"; | ||
import {hasCryptoRandomValues} from '../detector'; | ||
@@ -3,0 +3,0 @@ export const uuidv4 = (a?: number | string): string => { |
@@ -146,6 +146,6 @@ import {EC, Product, ImpressionList, BaseImpression} from '../plugins/ec'; | ||
const productSubKeysMatchGroup = [...productKeysMappingValues, "custom"].join('|'); | ||
const impressionSubKeysMatchGroup = [...impressionKeysMappingValues, "custom"].join('|'); | ||
const productPrefixMatchGroup = "(pr[0-9]+)"; | ||
const impressionPrefixMatchGroup = "(il[0-9]+pi[0-9]+)"; | ||
const productSubKeysMatchGroup = [...productKeysMappingValues, 'custom'].join('|'); | ||
const impressionSubKeysMatchGroup = [...impressionKeysMappingValues, 'custom'].join('|'); | ||
const productPrefixMatchGroup = '(pr[0-9]+)'; | ||
const impressionPrefixMatchGroup = '(il[0-9]+pi[0-9]+)'; | ||
const productKeyRegex = new RegExp(`^${productPrefixMatchGroup}(${productSubKeysMatchGroup})$`); | ||
@@ -158,15 +158,10 @@ const impressionKeyRegex = new RegExp(`^(${impressionPrefixMatchGroup}(${impressionSubKeysMatchGroup}))|(il[0-9]+nm)$`); | ||
const isImpressionKey = (key: string) => impressionKeyRegex.test(key); | ||
const isKnownMeasurementProtocolKey = (key: string) => measurementProtocolKeysMappingValues.indexOf(key) !== -1 | ||
const isCustomKey = (key: string) => key === "custom"; | ||
const isKnownMeasurementProtocolKey = (key: string) => measurementProtocolKeysMappingValues.indexOf(key) !== -1; | ||
const isCustomKey = (key: string) => key === 'custom'; | ||
export const isMeasurementProtocolKey = (key: string): boolean => { | ||
return [ | ||
isProductKey, | ||
isImpressionKey, | ||
isKnownMeasurementProtocolKey, | ||
isCustomKey | ||
].some(test => test(key)); | ||
return [isProductKey, isImpressionKey, isKnownMeasurementProtocolKey, isCustomKey].some((test) => test(key)); | ||
}; | ||
export const convertCustomMeasurementProtocolKeys = (data: {[name: string]: string | {[name:string] :string}}) => { | ||
export const convertCustomMeasurementProtocolKeys = (data: {[name: string]: string | {[name: string]: string}}) => { | ||
return keysOf(data).reduce((all, current) => { | ||
@@ -178,18 +173,21 @@ const match = customProductKeyRegex.exec(current) || customImpressionKeyRegex.exec(current); | ||
...all, | ||
...convertCustomObject(originalKey, data[current] as {[name: string]: string}) | ||
} | ||
...convertCustomObject(originalKey, data[current] as {[name: string]: string}), | ||
}; | ||
} else { | ||
return { | ||
...all, | ||
[current]: data[current] | ||
} | ||
[current]: data[current], | ||
}; | ||
} | ||
}, {}); | ||
} | ||
}; | ||
const convertCustomObject = (prefix: string, customData: {[name: string]: string}) => { | ||
return keysOf(customData).reduce((allCustom, currentCustomKey) => ({ | ||
...allCustom, | ||
[`${prefix}${currentCustomKey}`]: customData[currentCustomKey] | ||
}), {}); | ||
} | ||
return keysOf(customData).reduce( | ||
(allCustom, currentCustomKey) => ({ | ||
...allCustom, | ||
[`${prefix}${currentCustomKey}`]: customData[currentCustomKey], | ||
}), | ||
{} | ||
); | ||
}; |
@@ -1,2 +0,2 @@ | ||
export {CoveoSearchPageClient,SearchPageClientProvider} from '../searchPage/searchPageClient' | ||
export {CoveoSearchPageClient, SearchPageClientProvider} from '../searchPage/searchPageClient'; | ||
export {CoveoAnalyticsClient} from '../client/analytics'; |
@@ -8,4 +8,4 @@ import * as analytics from '../client/analytics'; | ||
export {CoveoUA, handleOneAnalyticsEvent} from './simpleanalytics'; | ||
export {CoveoSearchPageClient,SearchPageClientProvider} from '../searchPage/searchPageClient' | ||
export {CoveoSearchPageClient, SearchPageClientProvider} from '../searchPage/searchPageClient'; | ||
export {analytics, donottrack, history, SimpleAnalytics, storage}; |
@@ -337,2 +337,17 @@ import * as fetchMock from 'fetch-mock'; | ||
it('should send proper payload for #logQueryErrorBack', async () => { | ||
await client.logQueryErrorBack(); | ||
expectMatchPayload(SearchPageEvents.queryErrorBack); | ||
}); | ||
it('should send proper payload for #logQueryErrorRetry', async () => { | ||
await client.logQueryErrorRetry(); | ||
expectMatchPayload(SearchPageEvents.queryErrorRetry); | ||
}); | ||
it('should send proper payload for #logQueryErrorClear', async () => { | ||
await client.logQueryErrorClear(); | ||
expectMatchPayload(SearchPageEvents.queryErrorClear); | ||
}); | ||
it('should enable analytics tracking by default', () => { | ||
@@ -339,0 +354,0 @@ const c = new CoveoSearchPageClient({}, provider); |
@@ -192,2 +192,17 @@ import CoveoAnalyticsClient, {ClientOptions, AnalyticsClient} from '../client/analytics'; | ||
public async logQueryErrorBack() { | ||
await this.logCustomEvent(SearchPageEvents.queryErrorBack); | ||
return this.logSearchEvent(SearchPageEvents.queryErrorBack); | ||
} | ||
public async logQueryErrorRetry() { | ||
await this.logCustomEvent(SearchPageEvents.queryErrorRetry); | ||
return this.logSearchEvent(SearchPageEvents.queryErrorRetry); | ||
} | ||
public async logQueryErrorClear() { | ||
await this.logCustomEvent(SearchPageEvents.queryErrorClear); | ||
return this.logSearchEvent(SearchPageEvents.queryErrorClear); | ||
} | ||
public logCustomEvent(event: SearchPageEvents, metadata?: Record<string, any>) { | ||
@@ -194,0 +209,0 @@ const customData = {...this.provider.getBaseMetadata(), ...metadata}; |
@@ -140,2 +140,14 @@ import {DocumentInformation} from '../events'; | ||
queryError = 'query', | ||
/** | ||
* Identifies the search and custom event that gets logged when a user clicks the Go Back link after an error page. | ||
*/ | ||
queryErrorBack = 'errorBack', | ||
/** | ||
* Identifies the search and custom event that gets logged when a user clears the query box after an error page. | ||
*/ | ||
queryErrorClear = 'errorClearQuery', | ||
/** | ||
* Identifies the search and custom event that gets logged when a user clicks the Retry link after an error page. | ||
*/ | ||
queryErrorRetry = 'errorRetry', | ||
} | ||
@@ -149,2 +161,5 @@ | ||
[SearchPageEvents.queryError]: 'errors', | ||
[SearchPageEvents.queryErrorBack]: 'errors', | ||
[SearchPageEvents.queryErrorClear]: 'errors', | ||
[SearchPageEvents.queryErrorRetry]: 'errors', | ||
[SearchPageEvents.pagerNext]: 'getMoreResults', | ||
@@ -237,3 +252,3 @@ [SearchPageEvents.pagerPrevious]: 'getMoreResults', | ||
criteria: string; | ||
} | ||
} | ||
@@ -240,0 +255,0 @@ export interface QueryErrorMeta { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
532836
68
4034