Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@appbaseio/analytics

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@appbaseio/analytics - npm Package Compare versions

Comparing version 2.0.0-beta.1 to 2.0.0-beta.2

2

dist/@appbaseio/analytics.cjs.js

@@ -166,3 +166,3 @@ 'use strict';

click_on: clickConfig.objects,
click_type: clickConfig.type || 'result',
click_type: clickConfig.isSuggestionClick ? 'suggestion' : 'result',
query: clickConfig.query,

@@ -169,0 +169,0 @@ query_id: clickConfig.queryID,

@@ -162,3 +162,3 @@ import fetch from 'cross-fetch';

click_on: clickConfig.objects,
click_type: clickConfig.type || 'result',
click_type: clickConfig.isSuggestionClick ? 'suggestion' : 'result',
query: clickConfig.query,

@@ -165,0 +165,0 @@ query_id: clickConfig.queryID,

@@ -724,3 +724,3 @@ (function (global, factory) {

click_on: clickConfig.objects,
click_type: clickConfig.type || 'result',
click_type: clickConfig.isSuggestionClick ? 'suggestion' : 'result',
query: clickConfig.query,

@@ -727,0 +727,0 @@ query_id: clickConfig.queryID,

@@ -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).aa=t()}(this,(function(){"use strict";function e(){return(e=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function t(e){void 0===e&&(e="");for(var t,r=e,n="",o=0,i=0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.charAt(0|i)||(s="=",i%1);n+=s.charAt(63&o>>8-i%1*8)){if((t=r.charCodeAt(i+=.75))>255)throw new Error('"btoa" failed: The string to be encoded contains characters outside of the Latin1 range.');o=o<<8|t}return n}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var n=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){var n=function(e){function t(){this.fetch=!1,this.DOMException=e.DOMException}return t.prototype=e,new t}("undefined"!=typeof self?self:r);!function(e){!function(t){var r={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};if(r.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(e){return e&&n.indexOf(Object.prototype.toString.call(e))>-1};function i(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function s(e){return"string"!=typeof e&&(e=String(e)),e}function a(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r.iterable&&(t[Symbol.iterator]=function(){return t}),t}function u(e){this.map={},e instanceof u?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function c(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function h(e){var t=new FileReader,r=f(t);return t.readAsArrayBuffer(e),r}function l(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function d(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:r.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:r.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():r.arrayBuffer&&r.blob&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=l(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||o(e))?this._bodyArrayBuffer=l(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var e=c(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?c(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(h)}),this.text=function(){var e,t,r,n=c(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=f(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}u.prototype.append=function(e,t){e=i(e),t=s(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},u.prototype.delete=function(e){delete this.map[i(e)]},u.prototype.get=function(e){return e=i(e),this.has(e)?this.map[e]:null},u.prototype.has=function(e){return this.map.hasOwnProperty(i(e))},u.prototype.set=function(e,t){this.map[i(e)]=s(t)},u.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},u.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),a(e)},u.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),a(e)},u.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),a(e)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function p(e,t){var r,n,o=(t=t||{}).body;if(e instanceof p){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new u(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,o||null==e._bodyInit||(o=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new u(t.headers)),this.method=(r=t.method||this.method||"GET",n=r.toUpperCase(),y.indexOf(n)>-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(o))}})),t}function m(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new u(t.headers),this.url=t.url||"",this._initBody(e)}p.prototype.clone=function(){return new p(this,{body:this._bodyInit})},d.call(p.prototype),d.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},m.error=function(){var e=new m(null,{status:0,statusText:""});return e.type="error",e};var v=[301,302,303,307,308];m.redirect=function(e,t){if(-1===v.indexOf(t))throw new RangeError("Invalid status code");return new m(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function w(e,n){return new Promise((function(o,i){var s=new p(e,n);if(s.signal&&s.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new u,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();t.append(n,o)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new m(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&r.blob&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}w.polyfill=!0,e.fetch||(e.fetch=w,e.Headers=u,e.Request=p,e.Response=m),t.Headers=u,t.Request=p,t.Response=m,t.fetch=w}({})}(n),delete n.fetch.polyfill,(t=n.fetch).default=n.fetch,t.fetch=n.fetch,t.Headers=n.Headers,t.Request=n.Request,t.Response=n.Response,e.exports=t}));n.fetch,n.Headers,n.Request,n.Response;function o(e,t){if(null==e&&!t)throw new Error("appbase-analytics: query or queryID must be present to register a click/conversion event")}return{init:function(r){void 0===r&&(r={});var i={credentials:r.credentials,index:r.index,url:r.url,userID:r.userID,globalEventData:r.globalEventData,queryID:"",headers:null};return function(e){if(!e)throw new Error("appbase-analytics: A valid index must be present to record analytics events.")}(i.index),function(e){if(!e)throw new Error("appbase-analytics: Auth credentials is missing.")}(i.credentials),function(e){if(!e)throw new Error("appbase-analytics: URL is missing.")}(i.url),i._request=function(r,o,s){var a=e({},o,{user_id:i.userID,event_data:e({},o&&o.event_data,{},i.globalEventData)});return n(i.url+"/"+i.index+"/_analytics/"+r,{method:"PUT",headers:e({},i.headers,{"Content-Type":"application/json",Authorization:"Basic "+t(i.credentials)}),body:JSON.stringify(a)}).then((function(e){s&&s(null,e)})).catch((function(e){console.error(e),s&&s(e,null)}))},i.search=function(e,t){o(e.query);if(i._request){var r={query:e.query,event_data:e.eventData,filters:e.filters,hits:e.hits};i._request("search",r,(function(e,r){r&&r.json().then((function(e){e&&e.query_id&&(i.queryID=e.query_id)})).catch((function(e){console.error(e)})),t&&t(e,r)}))}},i.click=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={click_on:e.objects,click_type:e.type||"result",query:e.query,query_id:e.queryID,event_data:e.eventData};i._request("click",r,t)}},i.conversion=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={conversion_on:e.objects,query:e.query,query_id:e.queryID,event_data:e.eventData};i._request("conversion",r,t)}},i.setUserID=function(e){i.userID=e},i.setGlobalEventData=function(e){i.globalEventData=e},i.setHeaders=function(e){i.headers=e},i}}}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).aa=t()}(this,(function(){"use strict";function e(){return(e=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function t(e){void 0===e&&(e="");for(var t,r=e,n="",o=0,i=0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.charAt(0|i)||(s="=",i%1);n+=s.charAt(63&o>>8-i%1*8)){if((t=r.charCodeAt(i+=.75))>255)throw new Error('"btoa" failed: The string to be encoded contains characters outside of the Latin1 range.');o=o<<8|t}return n}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var n=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){var n=function(e){function t(){this.fetch=!1,this.DOMException=e.DOMException}return t.prototype=e,new t}("undefined"!=typeof self?self:r);!function(e){!function(t){var r={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};if(r.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(e){return e&&n.indexOf(Object.prototype.toString.call(e))>-1};function i(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function s(e){return"string"!=typeof e&&(e=String(e)),e}function a(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r.iterable&&(t[Symbol.iterator]=function(){return t}),t}function u(e){this.map={},e instanceof u?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function c(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function h(e){var t=new FileReader,r=f(t);return t.readAsArrayBuffer(e),r}function l(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function d(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:r.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:r.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():r.arrayBuffer&&r.blob&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=l(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||o(e))?this._bodyArrayBuffer=l(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var e=c(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?c(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(h)}),this.text=function(){var e,t,r,n=c(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=f(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}u.prototype.append=function(e,t){e=i(e),t=s(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},u.prototype.delete=function(e){delete this.map[i(e)]},u.prototype.get=function(e){return e=i(e),this.has(e)?this.map[e]:null},u.prototype.has=function(e){return this.map.hasOwnProperty(i(e))},u.prototype.set=function(e,t){this.map[i(e)]=s(t)},u.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},u.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),a(e)},u.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),a(e)},u.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),a(e)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function p(e,t){var r,n,o=(t=t||{}).body;if(e instanceof p){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new u(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,o||null==e._bodyInit||(o=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new u(t.headers)),this.method=(r=t.method||this.method||"GET",n=r.toUpperCase(),y.indexOf(n)>-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(o))}})),t}function m(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new u(t.headers),this.url=t.url||"",this._initBody(e)}p.prototype.clone=function(){return new p(this,{body:this._bodyInit})},d.call(p.prototype),d.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},m.error=function(){var e=new m(null,{status:0,statusText:""});return e.type="error",e};var v=[301,302,303,307,308];m.redirect=function(e,t){if(-1===v.indexOf(t))throw new RangeError("Invalid status code");return new m(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function w(e,n){return new Promise((function(o,i){var s=new p(e,n);if(s.signal&&s.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new u,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();t.append(n,o)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new m(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&r.blob&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}w.polyfill=!0,e.fetch||(e.fetch=w,e.Headers=u,e.Request=p,e.Response=m),t.Headers=u,t.Request=p,t.Response=m,t.fetch=w}({})}(n),delete n.fetch.polyfill,(t=n.fetch).default=n.fetch,t.fetch=n.fetch,t.Headers=n.Headers,t.Request=n.Request,t.Response=n.Response,e.exports=t}));n.fetch,n.Headers,n.Request,n.Response;function o(e,t){if(null==e&&!t)throw new Error("appbase-analytics: query or queryID must be present to register a click/conversion event")}return{init:function(r){void 0===r&&(r={});var i={credentials:r.credentials,index:r.index,url:r.url,userID:r.userID,globalEventData:r.globalEventData,queryID:"",headers:null};return function(e){if(!e)throw new Error("appbase-analytics: A valid index must be present to record analytics events.")}(i.index),function(e){if(!e)throw new Error("appbase-analytics: Auth credentials is missing.")}(i.credentials),function(e){if(!e)throw new Error("appbase-analytics: URL is missing.")}(i.url),i._request=function(r,o,s){var a=e({},o,{user_id:i.userID,event_data:e({},o&&o.event_data,{},i.globalEventData)});return n(i.url+"/"+i.index+"/_analytics/"+r,{method:"PUT",headers:e({},i.headers,{"Content-Type":"application/json",Authorization:"Basic "+t(i.credentials)}),body:JSON.stringify(a)}).then((function(e){s&&s(null,e)})).catch((function(e){console.error(e),s&&s(e,null)}))},i.search=function(e,t){o(e.query);if(i._request){var r={query:e.query,event_data:e.eventData,filters:e.filters,hits:e.hits};i._request("search",r,(function(e,r){r&&r.json().then((function(e){e&&e.query_id&&(i.queryID=e.query_id)})).catch((function(e){console.error(e)})),t&&t(e,r)}))}},i.click=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={click_on:e.objects,click_type:e.isSuggestionClick?"suggestion":"result",query:e.query,query_id:e.queryID,event_data:e.eventData};i._request("click",r,t)}},i.conversion=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={conversion_on:e.objects,query:e.query,query_id:e.queryID,event_data:e.eventData};i._request("conversion",r,t)}},i.setUserID=function(e){i.userID=e},i.setGlobalEventData=function(e){i.globalEventData=e},i.setHeaders=function(e){i.headers=e},i}}}));
//# sourceMappingURL=analytics.umd.min.js.map
{
"name": "@appbaseio/analytics",
"version": "2.0.0-beta.1",
"version": "2.0.0-beta.2",
"description": "Universal analytics library for appbase.io apps",

@@ -5,0 +5,0 @@ "main": "src/index.js",

@@ -5,3 +5,3 @@ [![NPM Version](https://img.shields.io/npm/v/@appbaseio/analytics.svg?style=flat)](https://www.npmjs.com/package/@appbaseio/analytics)

A universal analytics library that allows you to register click, conversion and custom events for appbase.io apps.
A universal analytics library that allows you to record search, click and conversion for appbase.io <b>clusters</b>.

@@ -14,8 +14,13 @@ ## TOC

- [Use cases](#use-cases)
- [Initialize search](#initialize-search)
- [Register click events](#register-click-events)
- [Register conversions](#register-conversions)
- [Record search](#record-search)
- [Record empty query search](#record-empty-query-search)
- [Record clicks](#record-clicks)
- [Record suggestion clicks](#record-suggestion-clicks)
- [Record clicks for a particular search event](#record-clicks-for-a-particular-search-event)
- [Record clicks with particular events](#record-clicks-with-particular-events)
- [Record conversions](#record-conversions)
- [Record conversions for a particular search event](#record-conversions-for-a-particular-search-event)
- [Record conversions with particular events](#record-conversions-with-particular-events)
- [Set user](#set-user)
- [Set custom events](#set-custom-events)
- [Set search state](#set-search-state)
- [Set global events](#set-global-events)
- [API Reference](#api-reference)

@@ -38,3 +43,3 @@ - [Contributing](#contributing)

```html
<script defer src="https://cdn.jsdelivr.net/npm/@appbaseio/analytics@1.0.0-alpha.1/dist/@appbaseio/analytics.umd.min.js"
<script defer src="https://cdn.jsdelivr.net/npm/@appbaseio/analytics@2.0.0-beta.2/dist/@appbaseio/analytics.umd.min.js"
></script>

@@ -47,5 +52,6 @@ ```

```js
const aaInstance = aa({
index: 'APP_NAME',
credentials: 'APP_CREDENTIALS'
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});

@@ -71,5 +77,6 @@ ```

const aaInstance = aa({
index: 'APP_NAME',
credentials: 'APP_CREDENTIALS'
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});

@@ -82,103 +89,67 @@ ```

The analytics library provides the utility methods to implement the appbase.io search analytics, the common use-cases are to record the clicks, conversions and apply the search headers to create a search session.
The analytics library provides the utility methods to integrate the appbase.io analytics in minutes, the common use-cases are to record the search, clicks and conversion events.
### Initialize search
### Record search
To register the click events you just need to create a search session and get the search id, a search session can be initialized bypassing the `x-search-query` header in the `_msearch` or `_search` request.
It helps you to track the search for a particular query term. It returns the `queryID` back which can be used to record clicks and conversions for the same search event.
We recommend to use `getAnalyticsHeaders` method to attach the analytics headers in search requests. For example:
```js
const aa = require('@appbaseio/analytics');
const aaInstance = aa({
index: 'APP_NAME',
credentials: 'APP_CREDENTIALS'
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});
const analyticsHeaders = aaInstance
.setSearchQuery('harry')
.getAnalyticsHeaders();
fetch(`https://scalr.api.appbse.io/${APP_NAME}/_search`, {
headers: analyticsHeaders
})
.then(res => {
const searchID = res.headers.get('X-Search-Id');
// Set the search id back to the analytics instance
if (searchID) {
aaInstance.setSearchID(searchID);
}
})
.catch(err => {
console.error(err);
});
aaInstance.search({
query: 'iphone'
});
```
Once you get the `searchID` back you need to use it to record the analytics events.
<b>Note:</b> `queryID` will be automatically set in the state and can be retrieved by using the `getQueryID` method once a search event has been registered successfully.
### Register click events
#### Record empty query search
Click events can be registered with the help of `registerClick` method which has the following signature:
`query` is the required key to record a search event however you can set it to empty string to register as an empty query search.
```ts
registerClick(
clickPosition: number, // position of the item in the list
isSuggestion?: boolean // whether a click is of type suggestion or results
): Promise<any>
```
#### Register a result click
```js
aa()
.setIndex('APP_NAME') // If index is not set during initialization
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error
.registerClick(`CLICK_POSITION`);
aaInstance.search({
query: ''
});
```
#### Register a suggestion click
### Record clicks
```js
aa()
.setIndex('APP_NAME') // If index is not set during initialization
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error
.registerClick(`CLICK_POSITION`, true);
```
Use the `click` method to record click events. The below example records the two clicks of the `result` type for a search query.
### Register conversions
```ts
const aa = require('@appbaseio/analytics');
```js
aa()
.setIndex('APP_NAME') // If index is not set during initialization
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error
.registerConversion();
```
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});
### Set user
```js
aa().setUserID('harry');
aaInstance.click({
query: 'iphone',
objects: {
iphoneX_19348: 1,
iphone7_19348: 3
}
});
```
### Set custom events
#### Record suggestion clicks
```js
aa().setCustomEvents({
key1: 'value1',
key2: 'value2'
});
```
Set the `isSuggestionClick` property to `true` to record as suggestion click.
### Set search state
```js
aa().setSearchState({
BookSensor: {
dataField: 'original_title',
value: 'harry',
queryFormat: 'or'
```ts
aaInstance.click({
query: 'iphone',
isSuggestionClick: true,
objects: {
iphoneX_19348: 1,
iphone7_19348: 3
}

@@ -188,260 +159,336 @@ });

[⬆ Back to Top](#appbase-analytics)
#### Record clicks for a particular search event
## API Reference
Use `queryID` instead of `query` to record clicks for a particular search event.
### Initialization
```ts
// Record a search
aaInstance.search({
query: 'iphone'
});
Although this library supports chaining i.e you can set and clear anything whenever you want but you can initialize it at once with some common properties to avoid the duplication.
```js
const aa = require('@appbaseio/analytics');
const aaInstance = aa({
index: 'APP_NAME',
credentials: 'APP_CREDENTIALS'
// Record a click for the last search made
aaInstance.click({
queryID: aaInstance.getQueryID(),
objects: {
iphoneX_19348: 1,
iphone7_19348: 3
}
});
```
Optional configuration options:
#### Record clicks with particular events
| Option | Type | Default | Description |
| ----------------- | --------- | ------------------------------ | ----------------------------------------------------------------------------------- |
| **`index`** | `string` | None (required) | App name for appbase.io apps or index name in case of `Arc` or `clusters`. |
| **`credentials`** | `string` | None (required) | API key for appbase.io hosted application. |
| `url` | `string` | `https://scalr.api.appbase.io` | Not needed for appbase.io apps but in case of `Arc` you need to define the arc URL. |
| `userID` | `string` | null | Sets the userID to be recorded. |
| `customEvents` | `object` | null | To set the custom events |
| `headers` | `object` | null | To set the custom headers |
| `emptyQuery` | `boolean` | true | To define whether to record the empty queries or not |
Attach the custom events to distinguish the click events.
### Methods
##
```ts
setIndex(index: string)
aaInstance.click({
query: 'iphone',
objects: {
iphoneX_19348: 1,
iphone7_19348: 3
},
eventData: {
click_source: 'promoted_collections'
}
});
```
To set the index or app name.
### Record conversions
##
To record a search conversion.
```ts
setCredentials(credentials: string)
```
const aa = require('@appbaseio/analytics');
To set the application auth credentials.
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});
##
```ts
setURL(url: string)
aaInstance.conversion({
query: 'iphone',
objects: ['iphoneX_19348', 'iphone7_19348']
});
```
To set the URL, required when you use the appbase.io clusters or `Arc`.
#### Record conversions for a particular search event
##
Use `queryID` instead of `query` to record conversions for a particular search event.
```ts
setHeaders(headers: Object)
// Record a search
aaInstance.search({
query: 'iphone'
});
// Record a conversion for the last search made
aaInstance.conversion({
queryID: aaInstance.getQueryID(),
objects: ['iphoneX_19348', 'iphone7_19348']
});
```
It allows you to set the custom headers in analytics endpoints.
#### Record conversions with particular events
##
Attach the custom events to distinguish the conversion events.
```ts
setSearchQuery(searchQuery: string)
aaInstance.conversion({
query: 'iphone',
objects: ['iphoneX_19348', 'iphone7_19348'],
eventData: {
conversion_source: 'promoted_collections'
}
});
```
Sets the search query which is needed to retrieve the search headers.
### Set user
##
It sets the unique identification for each user to distinguish analytics events for users.
```ts
clearSearchQuery();
```
const aa = require('@appbaseio/analytics');
Clears the search query
// Set during initialization
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL',
userID: 'jon@abc.com'
});
##
```ts
setSearchID(searchID: string)
// or set by using method
aaInstance.setUserID('jon@abc.com');
```
Sets the search ID which is required to register the analytics events.
### Set global events
##
Sets the custom events which will be attached for each event.
For example:
```ts
clearSearchID();
```
const aa = require('@appbaseio/analytics');
Clears the `searchID`
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL'
});
##
```ts
setSearchState(searchState: string)
// or set by using method
aaInstance.setGlobalEventData({
platform: 'ios'
});
```
Sets the search state which will be used to retrieve the search headers.
[⬆ Back to Top](#appbase-analytics)
##
## API Reference
```ts
clearSearchState();
```
### Initialization
Clears the saved search state.
```js
const aa = require('@appbaseio/analytics');
##
```ts
setUserID(userID: string)
const aaInstance = aa.init({
index: 'INDEX_NAME',
credentials: 'AUTH_CREDENTIALS',
url: 'CLUSTER_URL',
userID: 'USER_ID',
globalEventData: 'GLOBAL_EVENT_DATA'
headers?: 'CUSTOM_HEADERS'
});
```
Sets the user ID which will be used to retrieve the search headers.
Optional configuration options:
##
| Option | Type | Default | Description |
| ----------------- | -------- | --------------- | ------------------------------------------ |
| **`index`** | `string` | None (required) | Elasticsearch index name. |
| **`credentials`** | `string` | None (required) | API key for appbase.io hosted application. |
| **`url`** | `string` | None (required) | Appbaseio cluster url. |
| `userID` | `string` | null | Sets the userID to be recorded. |
| `globalEventData` | `object` | null | To set the custom events |
| `headers` | `object` | null | To set the custom headers |
```ts
clearUserID();
```
### Methods
Clears the userID
#### Record Search
##
```ts
setCustomEvents(customEvents: Object)
```
Sets the custom events which will override the existing custom events and will be used further in the analytics headers.
For example:
search(searchConfig: Object, callback: CallBack) => void
```js
aa().setCustomEvents({
platform: 'mac',
user_segment: 'free'
});
```
##
search configuration options:
```ts
clearCustomEvents();
```
| Option | Type | Default | Description |
| ----------- | -------- | --------------- | -------------------------------------------------------------------------------------- |
| **`query`** | `string` | None (required) | Search query, set to empty string to register as an empty query search. |
| `eventData` | `object` | null | To set the search filters, for e.g `{ "year": 2018 }` |
| `filters` | `object` | null | To set the custom events, for e.g `{ "platform": mac }` |
| `hits` | `array` | null | To set the search hits, a hit object can have the `id`, `type` & `source` properties . |
Clears the existing custom events
An example with all possible options:
##
```ts
addCustomEvent(customEvent: Object)
search(
{
query: 'iphone',
eventData: {
source: 'promoted_results'
},
filters: {
year: 2019
},
hits: [
{
id: '12345678',
source: {
title: 'iphoneX'
},
type: '_doc'
}
]
},
(err, res) => {
if (err) {
// handle error
} else if (res) {
// handle response
}
}
);
```
Add a particular custom event in the existing custom events.
#### Get queryID
```js
aa().addCustomEvent({
platform: 'mac'
});
```
The below method returns the `queryID` from the last search made.
##
```ts
removeCustomEvent(eventKey: string)
getQueryID(): string
```
Remove a custom event by key
#### Record Click
```js
aa().removeCustomEvent('platform');
```
To record a click event
##
```ts
setFilters(filters: Object)
click(clickConfig: Object, callback: CallBack) => void
```
Set the filters which will be used to retrieve the search headers.
click configuration options:
```js
aa().setFilters({
brand: 'Adidas',
category: 'shoes'
});
```
| Option | Type | Default | Description |
| ------------------- | ------------------------- | --------------- | --------------------------------------------------------------------------------------------- |
| **`query`** | `string` | None | Search query, set to empty string to register as an empty query search. |
| **`queryID`** | `string` | None | Search query ID returned from Appbase. |
| **`objects`** | `{[key: string]: number}` | None (required) | To set the click object ids followed by click positions, for example `{ "iphoneX_1234": 2 }`. |
| `isSuggestionClick` | `boolean` | `false` | Set as `true` to register as a suggestion click. |
| `eventData` | `object` | null | To set the custom events, for e.g `{ "platform": mac }` |
##
<b>Note: </b>
```ts
clearFilters();
```
`query` or `query_id` must be present.
Clear the filters
An example with all possible options:
##
```ts
addFilter(filter: Object)
click(
{
query: 'iphone',
// or
queryID: 'cf827a07-60a6-43ef-ab93-e1f8e1e3e1a8',
eventData: {
source: 'promoted_results'
},
objects: {
iphone_1234: 2
},
isSuggestionClick: true
},
(err, res) => {
if (err) {
// handle error
} else if (res) {
// handle response
}
}
);
```
Adds a filter in the existing filters.
#### Record conversion
##
To record a conversion event
```ts
removeFilter(filterKey: string)
conversion(conversionConfig: Object, callback: CallBack) => void
```
Removes a filter by key
conversion configuration options:
##
| Option | Type | Default | Description |
| ------------- | --------------- | --------------- | ----------------------------------------------------------------------- |
| **`query`** | `string` | None | Search query, set to empty string to register as an empty query search. |
| **`queryID`** | `string` | None | Search query ID returned from Appbase. |
| **`objects`** | `Array<string>` | None (required) | To set the converted object ids, for example: ["iphoneX_1234"]. |
| `eventData` | `object` | null | To set the custom events, for e.g `{ "platform": mac }` |
```ts
enableEmptyQuery();
```
<b>Note: </b>
Enables the recording of empty queries i.e create a search session even if the search query is empty.
`query` or `query_id` must be present.
##
An example with all possible options:
```ts
disableEmptyQuery();
conversion(
{
query: 'iphone',
// or
queryID: 'cf827a07-60a6-43ef-ab93-e1f8e1e3e1a8',
eventData: {
source: 'promoted_results'
},
objects: ['iphone_1234'],
isSuggestionClick: true
},
(err, res) => {
if (err) {
// handle error
} else if (res) {
// handle response
}
}
);
```
Disables the recording of empty queries.
#### Set headers
##
It allows you to set the custom headers in analytics endpoints.
```ts
registerClick(
clickPosition: number,
isSuggestion?: boolean
): Promise<any>
setHeaders(headers: Object)
```
Registers a click event
#### Set user
##
Sets the user ID which will be used to retrieve the search headers.
```ts
registerConversion(): Promise<any>
setUserID(userID: string)
```
Registers a search conversion
#### Set global events
##
Sets the global events which will be added to all analytics requests.
```ts
getAnalyticsHeaders(): Object
setGlobalEventData(globalEvents: Object)
```
Returns a list of search headers based on the analytics state which needs to be applied to the `_search` & `_msearch` request to create a search session.
##

@@ -464,3 +511,3 @@ [⬆ Back to Top](#appbase-analytics)

- **searchbox** A lightweight and performance focused searchbox UI libraries to query and display results from your ElasticSearch app (aka index).
- **searchbox** A lightweight and performance-focused search box UI libraries to query and display results from your ElasticSearch app (aka index).

@@ -467,0 +514,0 @@ - [**Vanilla**](https://github.com/appbaseio/searchbox) - (~16kB Minified + Gzipped)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc