Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.
TypeScript analyticsaudience-segmentationchartscohort-analysisgoogle-analyticsproduct-analyticsstatisticsuser-journeyweb-analytics
Add event collection.
Mike Cao9f3acd158351
diff --git a/lib/db.js b/lib/db.jsindex b925b52cf..8725f88c7 100644--- a/lib/db.js+++ b/lib/db.js@@ -68,3 +68,25 @@ export async function savePageView(website_id, session_id, url, referrer) {}),);}++export async function saveEvent(website_id, session_id, url, eventType, eventValue) {+ return runQuery(+ prisma.pageview.create({+ data: {+ website: {+ connect: {+ website_uuid: website_id,+ },+ },+ session: {+ connect: {+ session_uuid: session_id,+ },+ },+ url,+ eventType,+ eventValue,+ },+ }),+ );+}diff --git a/lib/utils.js b/lib/utils.jsindex ccf8c43d5..c2730f703 100644--- a/lib/utils.js+++ b/lib/utils.js@@ -91,6 +91,8 @@ export function parseCollectRequest(req) {const {url,referrer,+ eventType,+ eventValue,session: { website_id, session_id, time, hash: validationHash },} = payload;@@ -107,6 +109,8 @@ export function parseCollectRequest(req) {session_id,url,referrer,+ eventType,+ eventValue,};}}diff --git a/pages/api/collect.js b/pages/api/collect.jsindex 2f47cf9ad..724191f83 100644--- a/pages/api/collect.js+++ b/pages/api/collect.js@@ -1,5 +1,5 @@import { parseCollectRequest } from 'lib/utils';-import { savePageView } from 'lib/db';+import { savePageView, saveEvent } from 'lib/db';import { allowPost } from 'lib/middleware';export default async (req, res) => {@@ -8,12 +8,16 @@ export default async (req, res) => {const values = parseCollectRequest(req);if (values.success) {- const { type, website_id, session_id, url, referrer } = values;+ const { type, website_id, session_id, url, referrer, eventType, eventValue } = values;if (type === 'pageview') {await savePageView(website_id, session_id, url, referrer).catch(() => {values.success = 0;});+ } else if (type === 'event') {+ await saveEvent(website_id, session_id, url, eventType, eventValue).catch(() => {+ values.success = 0;+ });}}diff --git a/pages/index.js b/pages/index.jsindex e632bfd1d..0bd3d0acd 100644--- a/pages/index.js+++ b/pages/index.js@@ -14,6 +14,10 @@ export default function Home() {<Link href="/?q=123"><a>123</a></Link>+ <br />+ <button id="primary-button" className="otherClass umami--click" type="button">+ Button+ </button></Layout>);}diff --git a/public/umami.js b/public/umami.jsindex 51691c4e7..b4ab73349 100644--- a/public/umami.js+++ b/public/umami.js@@ -1 +1 @@-!function(){"use strict";function e(e){var n=this.constructor;return this.then((function(t){return n.resolve(e()).then((function(){return t}))}),(function(t){return n.resolve(e()).then((function(){return n.reject(t)}))}))}var n=setTimeout;function t(e){return Boolean(e&&void 0!==e.length)}function r(){}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],f(e,this)}function i(e,n){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn((function(){var t=1===e._state?n.onFulfilled:n.onRejected;if(null!==t){var r;try{r=t(e._value)}catch(e){return void s(n.promise,e)}u(n.promise,r)}else(1===e._state?u:s)(n.promise,e._value)}))):e._deferreds.push(n)}function u(e,n){try{if(n===e)throw new TypeError("A promise cannot be resolved with itself.");if(n&&("object"==typeof n||"function"==typeof n)){var t=n.then;if(n instanceof o)return e._state=3,e._value=n,void c(e);if("function"==typeof t)return void f((r=t,i=n,function(){r.apply(i,arguments)}),e)}e._state=1,e._value=n,c(e)}catch(n){s(e,n)}var r,i}function s(e,n){e._state=2,e._value=n,c(e)}function c(e){2===e._state&&0===e._deferreds.length&&o._immediateFn((function(){e._handled||o._unhandledRejectionFn(e._value)}));for(var n=0,t=e._deferreds.length;n<t;n++)i(e,e._deferreds[n]);e._deferreds=null}function a(e,n,t){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof n?n:null,this.promise=t}function f(e,n){var t=!1;try{e((function(e){t||(t=!0,u(n,e))}),(function(e){t||(t=!0,s(n,e))}))}catch(e){if(t)return;t=!0,s(n,e)}}o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,n){var t=new this.constructor(r);return i(this,new a(e,n,t)),t},o.prototype["finally"]=e,o.all=function(e){return new o((function(n,r){if(!t(e))return r(new TypeError("Promise.all accepts an array"));var o=Array.prototype.slice.call(e);if(0===o.length)return n([]);var i=o.length;function u(e,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var s=t.then;if("function"==typeof s)return void s.call(t,(function(n){u(e,n)}),r)}o[e]=t,0==--i&&n(o)}catch(e){r(e)}}for(var s=0;s<o.length;s++)u(s,o[s])}))},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o((function(n){n(e)}))},o.reject=function(e){return new o((function(n,t){t(e)}))},o.race=function(e){return new o((function(n,r){if(!t(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;i<u;i++)o.resolve(e[i]).then(n,r)}))},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){n(e,0)},o._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l["Promise"]=o,self.fetch||(self.fetch=function(e,n){return n=n||{},new Promise((function(t,r){var o=new XMLHttpRequest,i=[],u=[],s={},c=function(){return{ok:2==(o.status/100|0),statusText:o.statusText,status:o.status,url:o.responseURL,text:function(){return Promise.resolve(o.responseText)},json:function(){return Promise.resolve(JSON.parse(o.responseText))},blob:function(){return Promise.resolve(new Blob([o.response]))},clone:c,headers:{keys:function(){return i},entries:function(){return u},get:function(e){return s[e.toLowerCase()]},has:function(e){return e.toLowerCase()in s}}}};for(var a in o.open(n.method||"get",e,!0),o.onload=function(){o.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,n,t){i.push(n=n.toLowerCase()),u.push([n,t]),s[n]=s[n]?s[n]+","+t:t})),t(c())},o.onerror=r,o.withCredentials="include"==n.credentials,n.headers)o.setRequestHeader(a,n.headers[a]);o.send(n.body||null)}))});var d=window.screen,p=d.width,h=d.height,v=window.navigator.language,y=window.location,w=y.hostname,m=y.pathname,_=y.search,g=window.localStorage,b=window.document,j=window.history,P=b.querySelector("script[data-website-id]");if(P){var S=P.getAttribute("data-website-id");if(S){var T="umami.session",R=new URL(P.src).origin,x=p+"x"+h,F=""+m+_,O=b.referrer,E=function(e,n){return fetch(e,{method:"post",cache:"no-cache",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n)}).then((function(e){return e.json()}))},I=function(e){return E(R+"/api/session",e).then((function(e){var n=e.success,t=function(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&-1===n.indexOf(r)&&(t[r]=e[r]);return t}(e,["success"]);if(n)return g.setItem(T,JSON.stringify(t)),n}))},L=function(e,n){return E(R+"/api/collect",{type:"pageview",payload:{url:e,referrer:n,session:JSON.parse(g.getItem(T))}}).then((function(e){var n=e.success;return n||g.removeItem(T),n}))},A=function(e,n){var t=function(e){return{website_id:S,hostname:w,url:e,screen:x,language:v}}(e);g.getItem(T)?L(e,n).then((function(r){return!r&&I(t).then((function(t){return t&&L(e,n)}))})):I(t).then((function(t){return t&&L(e,n)}))},C=function(e,n,t){O=F,A(F=t,O)},J=function(e,n){var t=j[e];return function(e,r,o){var i=[e,r,o];return n.apply(null,i),t.apply(j,i)}};j.pushState=J("pushState",C),j.replaceState=J("replaceState",C),A(F,O)}}}();+!function(){"use strict";function e(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){return t.reject(n)}))}))}var t=setTimeout;function n(e){return Boolean(e&&void 0!==e.length)}function r(){}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],f(e,this)}function i(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn((function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void s(t.promise,e)}u(t.promise,r)}else(1===e._state?u:s)(t.promise,e._value)}))):e._deferreds.push(t)}function u(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof o)return e._state=3,e._value=t,void c(e);if("function"==typeof n)return void f((r=n,i=t,function(){r.apply(i,arguments)}),e)}e._state=1,e._value=t,c(e)}catch(t){s(e,t)}var r,i}function s(e,t){e._state=2,e._value=t,c(e)}function c(e){2===e._state&&0===e._deferreds.length&&o._immediateFn((function(){e._handled||o._unhandledRejectionFn(e._value)}));for(var t=0,n=e._deferreds.length;t<n;t++)i(e,e._deferreds[t]);e._deferreds=null}function a(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}function f(e,t){var n=!1;try{e((function(e){n||(n=!0,u(t,e))}),(function(e){n||(n=!0,s(t,e))}))}catch(e){if(n)return;n=!0,s(t,e)}}o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,t){var n=new this.constructor(r);return i(this,new a(e,t,n)),n},o.prototype["finally"]=e,o.all=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.all accepts an array"));var o=Array.prototype.slice.call(e);if(0===o.length)return t([]);var i=o.length;function u(e,n){try{if(n&&("object"==typeof n||"function"==typeof n)){var s=n.then;if("function"==typeof s)return void s.call(n,(function(t){u(e,t)}),r)}o[e]=n,0==--i&&t(o)}catch(e){r(e)}}for(var s=0;s<o.length;s++)u(s,o[s])}))},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o((function(t){t(e)}))},o.reject=function(e){return new o((function(t,n){n(e)}))},o.race=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;i<u;i++)o.resolve(e[i]).then(t,r)}))},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){t(e,0)},o._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l["Promise"]=o,self.fetch||(self.fetch=function(e,t){return t=t||{},new Promise((function(n,r){var o=new XMLHttpRequest,i=[],u=[],s={},c=function(){return{ok:2==(o.status/100|0),statusText:o.statusText,status:o.status,url:o.responseURL,text:function(){return Promise.resolve(o.responseText)},json:function(){return Promise.resolve(JSON.parse(o.responseText))},blob:function(){return Promise.resolve(new Blob([o.response]))},clone:c,headers:{keys:function(){return i},entries:function(){return u},get:function(e){return s[e.toLowerCase()]},has:function(e){return e.toLowerCase()in s}}}};for(var a in o.open(t.method||"get",e,!0),o.onload=function(){o.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,n){i.push(t=t.toLowerCase()),u.push([t,n]),s[t]=s[t]?s[t]+","+n:n})),n(c())},o.onerror=r,o.withCredentials="include"==t.credentials,t.headers)o.setRequestHeader(a,t.headers[a]);o.send(t.body||null)}))});var d=window.screen,p=d.width,h=d.height,v=window.navigator.language,y=window.location,m=y.hostname,w=y.pathname,g=y.search,_=window.localStorage,b=window.document,j=window.history,P=b.querySelector("script[data-website-id]");if(P){var S=P.getAttribute("data-website-id");if(S){var T="umami.session",R=new URL(P.src).origin,E=p+"x"+h,x=""+w+g,A=b.referrer,L=function(e,t){return fetch(e,{method:"post",cache:"no-cache",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)}).then((function(e){return e.json()}))},N=function(e){return L(R+"/api/session",e).then((function(e){var t=e.success,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&-1===t.indexOf(r)&&(n[r]=e[r]);return n}(e,["success"]);if(t)return _.setItem(T,JSON.stringify(n)),t}))},O=function(){return JSON.parse(_.getItem(T))},F=function(e,t){return L(R+"/api/collect",{type:"pageview",payload:{url:e,referrer:t,session:O()}}).then((function(e){var t=e.success;return t||_.removeItem(T),t}))},I=function(e){return JSON.stringify(e.getAttributeNames().reduce((function(t,n){return t[n]=e.getAttribute(n),t}),{tag:e.tagName.toLowerCase()}))},C=function(e,t){var n=function(e){return{website_id:S,hostname:m,url:e,screen:E,language:v}}(e);_.getItem(T)?F(e,t).then((function(r){return!r&&N(n).then((function(n){return n&&F(e,t)}))})):N(n).then((function(n){return n&&F(e,t)}))},J=function(e,t,n){A=x,C(x=n,A)},q=function(e,t){var n=j[e];return function(e,r,o){var i=[e,r,o];return t.apply(null,i),n.apply(j,i)}};j.pushState=q("pushState",J),j.replaceState=q("replaceState",J),b.querySelectorAll("[class*='umami--']").forEach((function(e){e.className.split(" ").forEach((function(t){if(console.log("class",t),/^umami--/.test(t)){var n=t.split("--")[1];console.log("event",n),n&&e.addEventListener(n,(function(){var t,r,o;t=x,r=n,o=I(e),L(R+"/api/collect",{type:"event",payload:{url:t,eventType:r,eventValue:o,session:O()}}).then((function(e){var t=e.success;return t||_.removeItem(T),t})),console.log("exec event",n,I(e))}))}})),console.log("match",e)})),C(x,A)}}}();diff --git a/scripts/umami/index.js b/scripts/umami/index.jsindex 21bea0746..3981b62d8 100644--- a/scripts/umami/index.js+++ b/scripts/umami/index.js@@ -10,6 +10,8 @@ const {history,} = window;+/* Load script */+const script = document.querySelector('script[data-website-id]');if (script) {@@ -22,6 +24,8 @@ if (script) {let currentUrl = `${pathname}${search}`;let currenrRef = document.referrer;+ /* Helper methods */+const post = (url, params) =>fetch(url, {method: 'post',@@ -56,6 +60,29 @@ if (script) {return success;});+ const trackEvent = (url, eventType, eventValue) =>+ post(`${hostUrl}/api/collect`, {+ type: 'event',+ payload: { url, eventType, eventValue, session: getSession() },+ }).then(({ success }) => {+ if (!success) {+ store.removeItem(sessionKey);+ }+ return success;+ });++ const elementToString = e => {+ return JSON.stringify(+ e.getAttributeNames().reduce(+ (obj, val) => {+ obj[val] = e.getAttribute(val);+ return obj;+ },+ { tag: e.tagName.toLowerCase() },+ ),+ );+ };+const execute = (url, referrer) => {const data = getSessionData(url);@@ -69,6 +96,8 @@ if (script) {}};+ /* Handle push state */+const handlePush = (state, title, url) => {currenrRef = currentUrl;currentUrl = url;@@ -87,6 +116,27 @@ if (script) {history.pushState = hook('pushState', handlePush);history.replaceState = hook('replaceState', handlePush);+ /* Handle events */++ document.querySelectorAll("[class*='umami--']").forEach(e => {+ e.className.split(' ').forEach(c => {+ console.log('class', c);+ if (/^umami--/.test(c)) {+ const [, event] = c.split('--');+ console.log('event', event);+ if (event) {+ e.addEventListener(event, () => {+ trackEvent(currentUrl, event, elementToString(e));+ console.log('exec event', event, elementToString(e));+ });+ }+ }+ });+ console.log('match', e);+ });++ /* Start */+execute(currentUrl, currenrRef);}}