kromemo
Version:
Browser event capture SDK for Kromemo: batching, retries, dedupe, TypeScript-first.
3 lines (2 loc) • 11.5 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).kromemo={})}(this,(function(e){"use strict";var t=function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},t.apply(this,arguments)};function n(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function u(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}c((r=r.apply(e,t||[])).next())}))}function r(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=u(0),a.throw=u(1),a.return=u(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function u(u){return function(c){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&u[0]?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[2&u[0],o.value]),u[0]){case 0:case 1:o=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,r=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==u[0]&&2!==u[0])){i=0;continue}if(3===u[0]&&(!o||u[1]>o[0]&&u[1]<o[3])){i.label=u[1];break}if(6===u[0]&&i.label<o[1]){i.label=o[1],o=u;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(u);break}o[2]&&i.ops.pop(),i.trys.pop();continue}u=t.call(e,i)}catch(e){u=[6,e],r=0}finally{n=o=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,c])}}}function o(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;function i(e){return"string"!=typeof e?e:e.length>2048?e.slice(0,2048):e}function a(e,t){if(void 0===t&&(t=new WeakSet),null!=e){if("string"==typeof e)return i(e);if("number"==typeof e||"boolean"==typeof e)return e;if("function"!=typeof e){if("symbol"==typeof e)return String(e);if(e instanceof Error)return{name:e.name,message:i(e.message),stack:"string"==typeof e.stack?i(e.stack):void 0};if("object"==typeof e){if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map((function(e){return a(e,t)})).filter((function(e){return void 0!==e}));for(var n={},r=0,o=Object.entries(e);r<o.length;r++){var u=o[r],c=u[0],s=a(u[1],t);void 0!==s&&(n[c]=s)}return n}try{return JSON.parse(JSON.stringify(e))}catch(t){return String(e)}}}}function u(e){try{return(new TextEncoder).encode(JSON.stringify(e)).length}catch(t){try{return JSON.stringify(e).length}catch(e){return 0}}}function c(){return Date.now()}function s(e){return new Promise((function(t){return setTimeout(t,e)}))}function f(e,t){var n=e||("undefined"!=typeof location?location.origin:""),r=n.endsWith("/")?"":"/";return"".concat(n).concat(r).concat(t,"/events")}function l(e,t,o){return void 0===o&&(o=!1),n(this,void 0,void 0,(function(){var n,i,a,u;return r(this,(function(r){switch(r.label){case 0:return n=f(t.endpointBase,t.projectId),[4,fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-api-ingest-key":t.apiKey},body:JSON.stringify({events:e}),keepalive:o,credentials:"omit",cache:"no-store",mode:"cors"})];case 1:i=r.sent(),a=i.status,u=void 0,r.label=2;case 2:return r.trys.push([2,4,,5]),[4,i.json()];case 3:return u=r.sent(),[3,5];case 4:return r.sent(),[3,5];case 5:return[2,{ok:i.ok,status:a,body:u}]}}))}))}function d(e){var t={sending:!1,timer:null},i=[];function a(){for(var t=[],n=0;n<i.length;){for(var r=[];n<i.length&&r.length<e.maxBatchSize;){var a=i[n];if(u({events:o(o([],r,!0),[a],!1)})>e.maxQueueBytes)break;r.push(a),n++}0!==r.length?t.push(r):(console.warn("[kromemo] Dropping oversized event"),n++)}return t}function c(){return n(this,void 0,void 0,(function(){var n,o,u,c,f,d,p,y,v,h,g;return r(this,(function(r){switch(r.label){case 0:if(t.sending)return[2];if(0===i.length)return[2];t.sending=!0,r.label=1;case 1:for(r.trys.push([1,,12,13]),n=a(),o=0,u=0,c=n;u<c.length;u++)f=c[u],o+=f.length;i.splice(0,o),d=0,p=n,r.label=2;case 2:if(!(d<p.length))return[3,11];y=p[d],v=0,h=Math.max(1,e.retryMaxAttempts),r.label=3;case 3:r.label=4;case 4:return r.trys.push([4,7,,9]),[4,l(y,{apiKey:e.apiKey,projectId:e.projectId,endpointBase:e.endpointBase})];case 5:return(g=r.sent()).ok||(g.status>=400&&g.status<500||++v>=h)?[3,10]:[4,s(500*Math.pow(2,v-1))];case 6:return r.sent(),[3,9];case 7:return r.sent(),++v>=h?[3,10]:[4,s(500*Math.pow(2,v-1))];case 8:return r.sent(),[3,9];case 9:return[3,3];case 10:return d++,[3,2];case 11:return[3,13];case 12:return t.sending=!1,[7];case 13:return[2]}}))}))}return function(){if(!t.timer&&(t.timer=setInterval((function(){c()}),e.flushIntervalMs),"undefined"!=typeof window)){var o=function(){!function(){n(this,void 0,void 0,(function(){var t,n,o,c,s,d;return r(this,(function(r){switch(r.label){case 0:if(0===i.length)return[2];t=a(),n=0,o=t,r.label=1;case 1:if(!(n<o.length))return[3,6];if(c=o[n],s=u({events:c}),d=!1,s<61440&&(d=function(e,t){if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;var n=f(t.endpointBase,t.projectId);try{var r=new Blob([JSON.stringify({events:e})],{type:"application/json"});return navigator.sendBeacon(n,r)}catch(e){return!1}}(c,{apiKey:e.apiKey,projectId:e.projectId,endpointBase:e.endpointBase})),d)return[3,5];r.label=2;case 2:return r.trys.push([2,4,,5]),[4,l(c,{apiKey:e.apiKey,projectId:e.projectId,endpointBase:e.endpointBase},!0)];case 3:case 4:return r.sent(),[3,5];case 5:return n++,[3,1];case 6:return i.length=0,[2]}}))}))}()};window.addEventListener("pagehide",o),window.addEventListener("beforeunload",o),document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&o()}))}}(),{enqueue:function(e){i.push(e)},flush:c,stop:function(){t.timer&&clearInterval(t.timer),t.timer=null}}}var p="kro:device_id",y="kro_device_id";function v(){var e=function(){try{return"undefined"!=typeof localStorage?localStorage.getItem(p):null}catch(e){return null}}()||function(){try{if("undefined"==typeof document||!document.cookie)return null;var e=document.cookie.match(new RegExp("(?:^|; )"+y.replace(/([.$?*|{}()\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):null}catch(e){return null}}();return e||function(e){try{return"undefined"!=typeof localStorage&&(localStorage.setItem(p,e),!0)}catch(e){return!1}}(e=function(){var e=globalThis.crypto||globalThis.msCrypto;if(!e||!e.getRandomValues){var t=function(){return Math.floor(4294967295*Math.random())};return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var n=15&t();return("x"===e?n:3&n|8).toString(16)}))}var n=new Uint8Array(16);e.getRandomValues(n),n[6]=15&n[6]|64,n[8]=63&n[8]|128;for(var r=[],o=0;o<n.length;o++)r.push((n[o]+256).toString(16).substr(1));return r[0]+r[1]+r[2]+r[3]+"-"+r[4]+r[5]+"-"+r[6]+r[7]+"-"+r[8]+r[9]+"-"+r[10]+r[11]+r[12]+r[13]+r[14]+r[15]}())||function(e){try{if("undefined"==typeof document)return!1;var t=location&&"https:"===location.protocol;return document.cookie="".concat(y,"=").concat(encodeURIComponent(e),"; path=/; max-age=").concat(3456e4,"; ").concat(t?"Secure; ":"","SameSite=Lax"),!0}catch(e){return!1}}(e),e}function h(){try{var e=[],t="undefined"!=typeof navigator?navigator:void 0;t&&(Array.isArray(t.languages)&&t.languages.length&&e.push.apply(e,t.languages),"string"==typeof t.language&&e.push(t.language));try{if("undefined"!=typeof Intl&&"function"==typeof Intl.DateTimeFormat)(u=(new Intl.DateTimeFormat).resolvedOptions().locale)&&e.push(u)}catch(e){}for(var n=0,r=e;n<r.length;n++){var o=g(r[n]);if(o)return o}try{var i=Intl;if(i&&"function"==typeof i.Locale){var a=e[0];if(a){var u,c=(u=new i.Locale(a))&&"string"==typeof u.region?String(u.region).toUpperCase():void 0;if(c&&/^[A-Z]{2}$/.test(c))return c}}}catch(e){}}catch(e){}}function g(e){if(e&&"string"==typeof e){for(var t=0,n=e.replace(/_/g,"-").split("-");t<n.length;t++){var r=n[t].toUpperCase();if(/^[A-Z]{2}$/.test(r))return r}var o=e.toUpperCase().match(/-([A-Z]{2})\b/);return o?o[1]:void 0}}function m(){try{var e="undefined"!=typeof navigator?navigator:void 0;if(!e)return;var t=e.userAgentData;if(t&&"string"==typeof t.platform&&t.platform){var n=String(t.platform).trim();if(n)return/^chrome os$/i.test(n)?"ChromeOS":n}var r="string"==typeof e.platform?e.platform:"";if(r){if(/^Mac/.test(r))return"macOS";if(/^Win/.test(r))return"Windows";if(/^Linux/.test(r))return"Linux";if(/iPhone|iPad|iPod/i.test(r))return"iOS"}var o="string"==typeof e.userAgent?e.userAgent:"";if(o){if(/Windows NT/i.test(o))return"Windows";if(/Android/i.test(o))return"Android";if(/iPhone|iPad|iPod|iOS/i.test(o))return"iOS";if(/Mac OS X/i.test(o))return"macOS";if(/CrOS/i.test(o))return"ChromeOS";if(/Linux/i.test(o))return"Linux"}}catch(e){}}var x=null,w=null,b=new Map;function S(e){var t=e.type||"event",n=e.name||"",r=e.url||"";return"".concat(t,"|").concat(n,"|").concat(r)}function I(e,t){if(!t||t<=0)return!1;var n=c();if(n-(b.get(e)||0)<t)return!0;if(b.set(e,n),b.size>1e3){var r=n-Math.max(10*t,3e4);b.forEach((function(e,t){e<r&&b.delete(t)}))}return!1}function k(){if(!w||!x)throw new Error("kromemo SDK is not initialized. Call init(...) first.")}function j(){return k(),{device_id:w.deviceId,url:"undefined"!=typeof location?location.href:void 0,referrer:"undefined"!=typeof document?document.referrer:void 0,os:w.os,country:w.country,ts:c()}}var B={init:function(e){var t,n,r,o,i;if(!e||!e.projectId||!e.apiKey)throw new Error("init requires projectId and apiKey");var a=v();return w={projectId:e.projectId,apiKey:e.apiKey,endpointBase:e.endpointBase,deviceId:a,maxBatchSize:null!==(t=e.maxBatchSize)&&void 0!==t?t:100,maxQueueBytes:null!==(n=e.maxQueueBytes)&&void 0!==n?n:5e5,flushIntervalMs:null!==(r=e.flushIntervalMs)&&void 0!==r?r:5e3,retryMaxAttempts:null!==(o=e.retryMaxAttempts)&&void 0!==o?o:3,os:m(),country:h(),dedupeWindowMs:null!==(i=e.dedupeWindowMs)&&void 0!==i?i:0},x=d({projectId:w.projectId,apiKey:w.apiKey,endpointBase:w.endpointBase,maxBatchSize:w.maxBatchSize,maxQueueBytes:w.maxQueueBytes,flushIntervalMs:w.flushIntervalMs,retryMaxAttempts:w.retryMaxAttempts}),{deviceId:a}},trackEvent:function(e){k();var n=e.name,r=e.ts,o=e.payload,i=t(t(t(t({},j()),{name:n,type:"event"}),r?{ts:r}:{}),{payload:a(o)});I(S(i),w.dedupeWindowMs)||x.enqueue(i)},trackView:function(e){var n;k();var r=null!==(n=null==e?void 0:e.name)&&void 0!==n?n:"view",o=(null==e?void 0:e.url)||("undefined"!=typeof location?location.href:void 0),i=null==e?void 0:e.payload,u=t(t({},j()),{name:r,type:"view",url:o,payload:a(i)});I(S(u),w.dedupeWindowMs)||x.enqueue(u)},trackError:function(e){k();var n=e.error,r=e.payload,o="string"==typeof n?{message:n}:{message:n.message,name:n.name,stack:n.stack},i=t(t({},j()),{name:"error",type:"error",payload:a(t(t({},o),r))});I(S(i),w.dedupeWindowMs)||x.enqueue(i)},flush:function(){return k(),x.flush()},shutdown:function(){x&&x.stop(),x=null,w=null}};e.default=B,e.kromemo=B,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=index.umd.js.map