@suprsend/web-sdk 0.1.3 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/. npmignore ADDED
@@ -0,0 +1 @@
1
+ /node_modules
@@ -1 +1 @@
1
- !function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:function(){return I}});var n="_suprsend_dist_id",r="bulk_api_call",i="event/",o="_suprsend_super_props",a={Edge:["Edge"],"Opera Mini":["Opera Mini"],"Opera Mobile":["Opera Mobi"],Opera:["Opera"],"Internet Explorer":["Trident","MSIE"],Chrome:["Chrome"],Firefox:["Firefox"],Safari:["Safari"],Mozilla:["Mozilla"]},c={Edge:/Edge\/([0-9]+(\.[0-9]+)?)/,"Opera Mini":/Opera Mini\/([0-9]+(\.[0-9]+)?)/,"Opera Mobile":/Version\/([0-9]+(\.[0-9]+)?)/,Opera:/Version\/([0-9]+(\.[0-9]+)?)/,"Internet Explorer":"rv:",Chrome:/Chrome\/([0-9]+(\.[0-9]+)?)/,Firefox:/rv:([0-9]+(\.[0-9]+)?)/,Safari:/Version\/([0-9]+(\.[0-9]+)?)/,Mozilla:/rv:([0-9]+(\.[0-9]+)?)/},u={"Chrome OS":"CrOS","Mac OS":"Macintosh",Windows:"Windows",iOS:"like Mac",Android:"Android",Linux:"Linux"};const l="https://collector.suprsend.workers.dev",s="1.0.0";function f(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw o}}}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var d;function v(e){return localStorage.getItem(e)}function _(e,t){localStorage.setItem(e,t)}function g(){var e=navigator.userAgent;for(var t in a){var n,r=f(a[t]);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(e.indexOf(i)>=0)return t}}catch(e){r.e(e)}finally{r.f()}}}function y(){var e=v(r)||"[]";return JSON.parse(e)}function h(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"post";return fetch("".concat(l,"/").concat(e),{method:n,body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}function b(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=y();if(t.length){var n=t.slice(0,20);h(i,n).then((function(e){if(!e.ok)throw new Error("Error in Fetch");var t=y();t.splice(0,20),_(r,JSON.stringify(t)),b()})).catch((function(){e&&m()}))}}function m(){d||(d=setInterval((function(){y().length?b():clearInterval(d)}),12e4))}const O={uuid:function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:3&n|8).toString(16)}))},epoch_milliseconds:function(){return Math.round(Date.now())},cookie_enabled:function(){return navigator.cookieEnabled},set_cookie:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365,r="";if(n){var i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3),r="; expires="+i.toUTCString()}document.cookie=e+"="+(t||"")+r+"; path=/"},get_cookie:function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return i.substring(t.length,i.length)}return null},remove_cookie:function(e){document.cookie=e+"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"},local_storage_enabled:function(){return!!window.localStorage},get_local_storage_item:v,set_local_storage_item:_,remove_local_storage_item:function(e){localStorage.removeItem(e)},get_parsed_local_store_data:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=v(e);return n?JSON.parse(n):t},browser:g,browser_version:function(){var e=navigator.userAgent,t=g(),n=c[t];if(n){var r=e.match(n);if(r&&r.length>1)return r[1]}},os:function(){var e=navigator.userAgent;for(var t in u)if(e.indexOf(u[t])>=0)return t},call_api:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return h(t,e).catch((function(){var t=y();null==t||t.push(e),_(r,JSON.stringify(t)),m()}))},bulk_call_api:b,format_props:function(e,t){var n;if(e instanceof Object){n={};for(var r=Object.keys(e),i=0;i<r.length;i++){var o=r[i];void 0!==e[o]&&(n[String(o)]=e[o])}}else null!=t&&(n=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}({},String(e),t));return n}};function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function k(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}const S=function(){function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.env=t,this.instance=n}var t,n;return t=e,(n=[{key:"_call_indetity",value:function(e){O.call_api(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?w(Object(n),!0).forEach((function(t){k(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):w(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({env:this.env,distinct_id:this.instance.distinct_id},e))}},{key:"set",value:function(e,t){var n=O.format_props(e,t);n&&this._call_indetity({$set:n})}},{key:"set_once",value:function(e,t){var n=O.format_props(e,t);n&&this._call_indetity({$set_once:n})}},{key:"increment",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=O.format_props(e,t);if(n){for(var r=Object.keys(n),i=0;i<r.length;i++){var o=r[i],a=Number(n[o]);a||delete n[o]}this._call_indetity({$add:n})}}},{key:"append",value:function(e,t){var n=O.format_props(e,t);n&&this._call_indetity({$append:n})}},{key:"remove",value:function(e,t){var n=O.format_props(e,t);n&&this._call_indetity({$remove:n})}},{key:"unset",value:function(e){var t;if("string"==typeof e)t=[String(e)];else{if(!(e instanceof Array))return;t=e.map((function(e){return String(e)}))}this._call_indetity({$unset:t})}},{key:"add_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$email",e)}},{key:"remove_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.remove("$email",e)}},{key:"add_sms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$sms",e)}},{key:"add_whatsapp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$whatsapp",e)}}])&&x(t.prototype,n),e}();function j(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function E(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?j(Object(n),!0).forEach((function(t){$(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):j(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function P(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function $(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var M;window.addEventListener("load",(function(){d&&(clearTimeout(d),setTimeout((function(){O.bulk_call_api(!0)}),2e3))})),window.addEventListener("online",(function(){d&&(clearTimeout(d),setTimeout((function(){O.bulk_call_api(!0)}),2e3))}));var A=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,r,i;return t=e,i=[{key:"setEnvProperties",value:function(){M.env_properties={$os:O.os(),$browser:O.browser(),$browser_version:O.browser_version(),$sdk_type:"Browser",$sdk_version:s}}}],(r=[{key:"initialize",value:function(t){var r=O.get_cookie(n);M||(e.ENV_API_KEY=t,M={}),r||(r=O.uuid(),O.set_cookie(n,r)),M.distinct_id=r,this.user=new S(e.ENV_API_KEY,M),e.setEnvProperties()}},{key:"set_super_properties",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=O.get_parsed_local_store_data(o),n=E(E({},t),e);O.set_local_storage_item(o,JSON.stringify(n)),M.env_properties=E(E({},M.env_properties),n)}},{key:"identify",value:function(t){M._user_identified||O.call_api({env:e.ENV_API_KEY,event:"$identify",properties:{$identified_id:t,$anon_id:M.distinct_id}}).then((function(e){e.ok&&(O.set_cookie(n,t),M.distinct_id=t,M._user_identified=!0)}))}},{key:"track",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t){var r=O.get_parsed_local_store_data(o),i=O.format_props(E(E(E(E({},n),M.env_properties),r),{},{$current_url:window.location.href}));O.call_api({event:String(t),distinct_id:M.distinct_id,env:e.ENV_API_KEY,properties:i,$insert_id:O.uuid(),$time:O.epoch_milliseconds()})}}},{key:"reset",value:function(){var t=O.uuid();O.set_cookie(n,t),M={distinct_id:t,_user_identified:!1},O.remove_local_storage_item(o),this.user=new S(e.ENV_API_KEY,M),e.setEnvProperties()}}])&&P(t.prototype,r),i&&P(t,i),e}();$(A,"ENV_API_KEY",void 0);const I=new A;window.suprsend=t}();
1
+ !function(){"use strict";var e={147:function(e){e.exports=JSON.parse('{"name":"@suprsend/web-sdk","version":"0.1.6","description":"This is sdk used to integrate suprsend functionality in javascript applications","main":"dist/cjs_bundle.js","scripts":{"test":"echo \\"Error: no test specified\\" && exit 1","build":"rm -rf dist && webpack --env module_type=commonjs --env filename=cjs_bundle.js && webpack --env module_type=window --env filename=cdn_bundle.js","publish_sdk":"npm run build && npm publish"},"keywords":["suprsend","suprsend-browser","suprsend-browser-sdk"],"author":"Sivaram Katta","license":"ISC","repository":{"type":"git","url":"https://github.com/suprsend/suprsend-browser.git"},"publishConfig":{"access":"public"},"devDependencies":{"@babel/core":"^7.15.0","@babel/preset-env":"^7.15.0","babel-loader":"^8.2.2","webpack":"^5.51.1","webpack-cli":"^4.8.0"}}')}},r={};function t(n){var i=r[n];if(void 0!==i)return i.exports;var o=r[n]={exports:{}};return e[n](o,o.exports,t),o.exports}t.d=function(e,r){for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};!function(){t.r(n),t.d(n,{default:function(){return J},init_at:function(){return V}});var e="_suprsend_dist_id",r="_bulk_api_call",i="event/",o="_suprsend_super_props",a="_suprsend_device_id",s={Edge:["Edge"],"Opera Mini":["Opera Mini"],"Opera Mobile":["Opera Mobi"],Opera:["Opera"],"Internet Explorer":["Trident","MSIE"],Chrome:["Chrome"],Firefox:["Firefox"],Safari:["Safari"],Mozilla:["Mozilla"]},c={Edge:/Edge\/([0-9]+(\.[0-9]+)?)/,"Opera Mini":/Opera Mini\/([0-9]+(\.[0-9]+)?)/,"Opera Mobile":/Version\/([0-9]+(\.[0-9]+)?)/,Opera:/Version\/([0-9]+(\.[0-9]+)?)/,"Internet Explorer":"rv:",Chrome:/Chrome\/([0-9]+(\.[0-9]+)?)/,Firefox:/rv:([0-9]+(\.[0-9]+)?)/,Safari:/Version\/([0-9]+(\.[0-9]+)?)/,Mozilla:/rv:([0-9]+(\.[0-9]+)?)/},u={"Chrome OS":"CrOS","Mac OS":"Macintosh",Windows:"Windows",iOS:"like Mac",Android:"Android",Linux:"Linux"};const l={api_url:"https://collector.suprsend.workers.dev",sdk_version:t(147).version,batch_size:20,service_worker_file:"suprsend_service_worker.js",sw_delay:5e3};function f(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return p(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?p(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==t.return||t.return()}finally{if(s)throw o}}}}function p(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function d(){var e=!0;try{window.localStorage}catch(r){e=!1}return e}function v(e){if(d())return localStorage.getItem(e)}function _(e,r){d()&&localStorage.setItem(e,r)}function b(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=v(e);return t?JSON.parse(t):r}function h(){var e=navigator.userAgent;for(var r in s){var t,n=f(s[r]);try{for(n.s();!(t=n.n()).done;){var i=t.value;if(e.indexOf(i)>=0)return r}}catch(e){n.e(e)}finally{n.f()}}}function g(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"post";return fetch("".concat(l.api_url,"/").concat(e),{method:t,body:JSON.stringify(r),headers:{"Content-Type":"application/json"}})}function y(){var e=b(r,[]);if(e.length){var t=e.slice(0,l.batch_size);g(i,t).then((function(e){if(!e.ok)throw new Error("Error in Fetch");var t=b(r,[]);t.splice(0,l.batch_size),_(r,JSON.stringify(t)),y()})).catch((function(){m(12e4)}))}else m()}function m(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e3;setTimeout((function(){y()}),e)}const w={uuid:function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(r){var t=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==r?t:3&t|8).toString(16)}))},epoch_milliseconds:function(){return Math.round(Date.now())},cookie_enabled:function(){return navigator.cookieEnabled},set_cookie:function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365,n="";if(t){var i=new Date;i.setTime(i.getTime()+24*t*60*60*1e3),n="; expires="+i.toUTCString()}document.cookie=e+"="+(r||"")+n+"; path=/"},get_cookie:function(e){for(var r=e+"=",t=document.cookie.split(";"),n=0;n<t.length;n++){for(var i=t[n];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(r))return i.substring(r.length,i.length)}return null},remove_cookie:function(e){document.cookie=e+"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"},local_storage_enabled:d,get_local_storage_item:v,set_local_storage_item:_,remove_local_storage_item:function(e){d()&&localStorage.removeItem(e)},get_parsed_local_store_data:b,browser:h,browser_version:function(){var e=navigator.userAgent,r=h(),t=c[r];if(t){var n=e.match(t);if(n&&n.length>1)return n[1]}},os:function(){var e=navigator.userAgent;for(var r in u)if(e.indexOf(u[r])>=0)return r},schedule_flush:m,format_props:function(e,r){var t;if(e instanceof Object){t={};for(var n=Object.keys(e),i=0;i<n.length;i++){var o=n[i];void 0!==e[o]&&(t[String(o)]=e[o])}}else null!=r&&(t=function(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}({},String(e),r));return t},urlB64ToUint8Array:function(e){for(var r=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),t=atob(r),n=new Uint8Array(t.length),i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n},batch_or_call:function(e){if(d()){var t=b(r,[]);null==t||t.push(e),_(r,JSON.stringify(t))}else g(i,e)}};function O(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function k(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function x(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}const j=function(){function e(r,t){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),this.env=r,this.instance=t}var r,t;return r=e,(t=[{key:"_call_indetity",value:function(e){w.batch_or_call(function(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?O(Object(t),!0).forEach((function(r){k(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):O(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}({env:this.env,distinct_id:this.instance.distinct_id},e))}},{key:"set",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$set:t})}},{key:"set_once",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$set_once:t})}},{key:"increment",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,t=w.format_props(e,r);if(t){for(var n=Object.keys(t),i=0;i<n.length;i++){var o=n[i],a=Number(t[o]);a||delete t[o]}this._call_indetity({$add:t})}}},{key:"append",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$append:t})}},{key:"remove",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$remove:t})}},{key:"unset",value:function(e){var r;if("string"==typeof e)r=[String(e)];else{if(!(e instanceof Array))return;r=e.map((function(e){return String(e)}))}this._call_indetity({$unset:r})}},{key:"add_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$email",e)}},{key:"remove_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.remove("$email",e)}},{key:"add_sms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$sms",e)}},{key:"add_whatsapp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$whatsapp",e)}},{key:"add_webpush",value:function(){var e,r,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append({$webpush:JSON.stringify(t),$device_id:null===(e=this.instance)||void 0===e||null===(r=e.env_properties)||void 0===r?void 0:r.$device_id})}}])&&x(r.prototype,t),e}();function P(e,r,t,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void t(e)}s.done?r(c):Promise.resolve(c).then(n,i)}function S(e){return function(){var r=this,t=arguments;return new Promise((function(n,i){var o=e.apply(r,t);function a(e){P(o,n,i,a,s,"next",e)}function s(e){P(o,n,i,a,s,"throw",e)}a(void 0)}))}}function E(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function A(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var M;const $=function(){function e(r,t){var n=this;!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),A(this,"_check_push_support",(function(){return!(!("serviceWorker"in navigator)||!("PushManager"in window))})),A(this,"_ask_notification_permission",S(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Notification.requestPermission();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e)})))),A(this,"_register_sw",(function(){return navigator.serviceWorker.register("/".concat(l.service_worker_file)).then((function(e){console.log("Service worker successfully registered."),n._subscribe_push(e)})).catch((function(e){console.error("Unable to register service worker.",e)}))})),A(this,"_get_subscription",(function(){return navigator.serviceWorker.ready.then((function(e){return e.pushManager.getSubscription()})).then(function(){var e=S(regeneratorRuntime.mark((function e(r){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",r);case 3:case"end":return e.stop()}}),e)})));return function(r){return e.apply(this,arguments)}}())})),A(this,"_subscribe_push",function(){var e=S(regeneratorRuntime.mark((function e(r){var t,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return console.log("calling subscribe 1.3"),e.next=3,n._ask_notification_permission();case 3:if("granted"!==e.sent){e.next=18;break}return e.next=7,n._get_subscription();case 7:if(e.sent){e.next=17;break}return console.log("API_CALL: get public vapid from server"),t=w.urlB64ToUint8Array("BADMgGsRZWdjJPH34F0v9OTQfrxHArhk_sVawIACOFHTcaPF_Cfpq1uBX6lOwHByQDjt8f05h3ESK3dldpG3Q9Q"),e.next=13,r.pushManager.subscribe({applicationServerKey:t,userVisibleOnly:!0});case 13:i=e.sent,n.user.add_webpush(i),e.next=18;break;case 17:console.log("Push already subscribed");case 18:case"end":return e.stop()}}),e)})));return function(r){return e.apply(this,arguments)}}()),A(this,"register_push",(function(){n._check_push_support()?(console.log("calling subscribe 1"),n._subscribe_with_delay()):console.log("OOPS, Web Push isn't supported")})),A(this,"is_subscribed",S(regeneratorRuntime.mark((function e(){var r;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._get_subscription();case 2:return r=e.sent,e.abrupt("return",!!r);case 4:case"end":return e.stop()}}),e)})))),this.env=r,this.instance=t,this.user=new j(r,t)}var r,t;return r=e,(t=[{key:"_subscribe_with_delay",value:function(){var e=this,r=new Date-V;r>=l.sw_delay?(console.log("calling subscribe 1.1"),this._subscribe_push()):(console.log("calling subscribe 1.2"),clearTimeout(M),M=setTimeout((function(){e._subscribe_push()}),l.sw_delay-r))}},{key:"update_subscription",value:function(){var e,r,t=this;null===(e=navigator)||void 0===e||null===(r=e.serviceWorker)||void 0===r||r.ready.then((function(e){return e.pushManager.getSubscription()})).then((function(e){e&&(t.user.add_webpush(e),console.log("API_CALL: save subscription",e))}))}}])&&E(r.prototype,t),e}();function T(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function I(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?T(Object(t),!0).forEach((function(r){N(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):T(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function C(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function N(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var D,V,K=function(){function r(){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,r)}var t,n,i;return t=r,i=[{key:"setEnvProperties",value:function(){var e=w.get_local_storage_item(a);e||(e=w.uuid(),w.set_local_storage_item(a,e)),D.env_properties={$os:w.os(),$browser:w.browser(),$browser_version:w.browser_version(),$sdk_type:"Browser",$device_id:e,$sdk_version:l.sdk_version}}}],(n=[{key:"initialize",value:function(t){V=new Date;var n=w.get_cookie(e);D||(r.ENV_API_KEY=t,D={}),n||(n=w.uuid(),w.set_cookie(e,n)),D.distinct_id=n,this.user=new j(r.ENV_API_KEY,D),this.sw=new $(r.ENV_API_KEY,D),this.sw.update_subscription(),r.setEnvProperties(),w.schedule_flush()}},{key:"set_super_properties",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=w.get_parsed_local_store_data(o),t=I(I({},r),e);w.set_local_storage_item(o,JSON.stringify(t)),D.env_properties=I(I({},D.env_properties),t)}},{key:"identify",value:function(t){D._user_identified||(w.batch_or_call({env:r.ENV_API_KEY,event:"$identify",properties:{$identified_id:t,$anon_id:D.distinct_id}}),w.set_cookie(e,t),D.distinct_id=t,D._user_identified=!0)}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=e){var n=w.get_parsed_local_store_data(o),i=w.format_props(I(I(I(I({},t),D.env_properties),n),{},{$current_url:window.location.href}));w.batch_or_call({event:String(e),distinct_id:D.distinct_id,env:r.ENV_API_KEY,properties:i,$insert_id:w.uuid(),$time:w.epoch_milliseconds()})}}},{key:"reset",value:function(){var t=w.uuid();w.set_cookie(e,t),D={distinct_id:t,_user_identified:!1},w.remove_local_storage_item(o),this.user=new j(r.ENV_API_KEY,D),this.sw=new $(r.ENV_API_KEY,D),r.setEnvProperties()}}])&&C(t.prototype,n),i&&C(t,i),r}();N(K,"ENV_API_KEY",void 0);const J=new K}(),window.suprsend=n}();
@@ -1 +1 @@
1
- !function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:function(){return I}});var r="_suprsend_dist_id",n="bulk_api_call",i="event/",o="_suprsend_super_props",a={Edge:["Edge"],"Opera Mini":["Opera Mini"],"Opera Mobile":["Opera Mobi"],Opera:["Opera"],"Internet Explorer":["Trident","MSIE"],Chrome:["Chrome"],Firefox:["Firefox"],Safari:["Safari"],Mozilla:["Mozilla"]},c={Edge:/Edge\/([0-9]+(\.[0-9]+)?)/,"Opera Mini":/Opera Mini\/([0-9]+(\.[0-9]+)?)/,"Opera Mobile":/Version\/([0-9]+(\.[0-9]+)?)/,Opera:/Version\/([0-9]+(\.[0-9]+)?)/,"Internet Explorer":"rv:",Chrome:/Chrome\/([0-9]+(\.[0-9]+)?)/,Firefox:/rv:([0-9]+(\.[0-9]+)?)/,Safari:/Version\/([0-9]+(\.[0-9]+)?)/,Mozilla:/rv:([0-9]+(\.[0-9]+)?)/},l={"Chrome OS":"CrOS","Mac OS":"Macintosh",Windows:"Windows",iOS:"like Mac",Android:"Android",Linux:"Linux"};const u="https://collector.suprsend.workers.dev",s="1.0.0";function f(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return p(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,c=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){c=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(c)throw o}}}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var v;function d(e){return localStorage.getItem(e)}function _(e,t){localStorage.setItem(e,t)}function y(){var e=navigator.userAgent;for(var t in a){var r,n=f(a[t]);try{for(n.s();!(r=n.n()).done;){var i=r.value;if(e.indexOf(i)>=0)return t}}catch(e){n.e(e)}finally{n.f()}}}function g(){var e=d(n)||"[]";return JSON.parse(e)}function b(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"post";return fetch("".concat(u,"/").concat(e),{method:r,body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}function h(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=g();if(t.length){var r=t.slice(0,20);b(i,r).then((function(e){if(!e.ok)throw new Error("Error in Fetch");var t=g();t.splice(0,20),_(n,JSON.stringify(t)),h()})).catch((function(){e&&m()}))}}function m(){v||(v=setInterval((function(){g().length?h():clearInterval(v)}),12e4))}const O={uuid:function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))},epoch_milliseconds:function(){return Math.round(Date.now())},cookie_enabled:function(){return navigator.cookieEnabled},set_cookie:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365,n="";if(r){var i=new Date;i.setTime(i.getTime()+24*r*60*60*1e3),n="; expires="+i.toUTCString()}document.cookie=e+"="+(t||"")+n+"; path=/"},get_cookie:function(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){for(var i=r[n];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(t))return i.substring(t.length,i.length)}return null},remove_cookie:function(e){document.cookie=e+"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"},local_storage_enabled:function(){return!!window.localStorage},get_local_storage_item:d,set_local_storage_item:_,remove_local_storage_item:function(e){localStorage.removeItem(e)},get_parsed_local_store_data:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=d(e);return r?JSON.parse(r):t},browser:y,browser_version:function(){var e=navigator.userAgent,t=y(),r=c[t];if(r){var n=e.match(r);if(n&&n.length>1)return n[1]}},os:function(){var e=navigator.userAgent;for(var t in l)if(e.indexOf(l[t])>=0)return t},call_api:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i;return b(t,e).catch((function(){var t=g();null==t||t.push(e),_(n,JSON.stringify(t)),m()}))},bulk_call_api:h,format_props:function(e,t){var r;if(e instanceof Object){r={};for(var n=Object.keys(e),i=0;i<n.length;i++){var o=n[i];void 0!==e[o]&&(r[String(o)]=e[o])}}else null!=t&&(r=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}({},String(e),t));return r}};function w(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function k(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function x(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}const j=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.env=t,this.instance=r}var t,r;return t=e,(r=[{key:"_call_indetity",value:function(e){O.call_api(function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?w(Object(r),!0).forEach((function(t){k(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):w(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({env:this.env,distinct_id:this.instance.distinct_id},e))}},{key:"set",value:function(e,t){var r=O.format_props(e,t);r&&this._call_indetity({$set:r})}},{key:"set_once",value:function(e,t){var r=O.format_props(e,t);r&&this._call_indetity({$set_once:r})}},{key:"increment",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=O.format_props(e,t);if(r){for(var n=Object.keys(r),i=0;i<n.length;i++){var o=n[i],a=Number(r[o]);a||delete r[o]}this._call_indetity({$add:r})}}},{key:"append",value:function(e,t){var r=O.format_props(e,t);r&&this._call_indetity({$append:r})}},{key:"remove",value:function(e,t){var r=O.format_props(e,t);r&&this._call_indetity({$remove:r})}},{key:"unset",value:function(e){var t;if("string"==typeof e)t=[String(e)];else{if(!(e instanceof Array))return;t=e.map((function(e){return String(e)}))}this._call_indetity({$unset:t})}},{key:"add_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$email",e)}},{key:"remove_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.remove("$email",e)}},{key:"add_sms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$sms",e)}},{key:"add_whatsapp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$whatsapp",e)}}])&&x(t.prototype,r),e}();function S(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function P(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?S(Object(r),!0).forEach((function(t){M(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):S(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function E(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function M(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var $;window.addEventListener("load",(function(){v&&(clearTimeout(v),setTimeout((function(){O.bulk_call_api(!0)}),2e3))})),window.addEventListener("online",(function(){v&&(clearTimeout(v),setTimeout((function(){O.bulk_call_api(!0)}),2e3))}));var A=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,n,i;return t=e,i=[{key:"setEnvProperties",value:function(){$.env_properties={$os:O.os(),$browser:O.browser(),$browser_version:O.browser_version(),$sdk_type:"Browser",$sdk_version:s}}}],(n=[{key:"initialize",value:function(t){var n=O.get_cookie(r);$||(e.ENV_API_KEY=t,$={}),n||(n=O.uuid(),O.set_cookie(r,n)),$.distinct_id=n,this.user=new j(e.ENV_API_KEY,$),e.setEnvProperties()}},{key:"set_super_properties",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=O.get_parsed_local_store_data(o),r=P(P({},t),e);O.set_local_storage_item(o,JSON.stringify(r)),$.env_properties=P(P({},$.env_properties),r)}},{key:"identify",value:function(t){$._user_identified||O.call_api({env:e.ENV_API_KEY,event:"$identify",properties:{$identified_id:t,$anon_id:$.distinct_id}}).then((function(e){e.ok&&(O.set_cookie(r,t),$.distinct_id=t,$._user_identified=!0)}))}},{key:"track",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t){var n=O.get_parsed_local_store_data(o),i=O.format_props(P(P(P(P({},r),$.env_properties),n),{},{$current_url:window.location.href}));O.call_api({event:String(t),distinct_id:$.distinct_id,env:e.ENV_API_KEY,properties:i,$insert_id:O.uuid(),$time:O.epoch_milliseconds()})}}},{key:"reset",value:function(){var t=O.uuid();O.set_cookie(r,t),$={distinct_id:t,_user_identified:!1},O.remove_local_storage_item(o),this.user=new j(e.ENV_API_KEY,$),e.setEnvProperties()}}])&&E(t.prototype,n),i&&E(t,i),e}();M(A,"ENV_API_KEY",void 0);const I=new A;var T=exports;for(var N in t)T[N]=t[N];t.__esModule&&Object.defineProperty(T,"__esModule",{value:!0})}();
1
+ !function(){"use strict";var e={147:function(e){e.exports=JSON.parse('{"name":"@suprsend/web-sdk","version":"0.1.6","description":"This is sdk used to integrate suprsend functionality in javascript applications","main":"dist/cjs_bundle.js","scripts":{"test":"echo \\"Error: no test specified\\" && exit 1","build":"rm -rf dist && webpack --env module_type=commonjs --env filename=cjs_bundle.js && webpack --env module_type=window --env filename=cdn_bundle.js","publish_sdk":"npm run build && npm publish"},"keywords":["suprsend","suprsend-browser","suprsend-browser-sdk"],"author":"Sivaram Katta","license":"ISC","repository":{"type":"git","url":"https://github.com/suprsend/suprsend-browser.git"},"publishConfig":{"access":"public"},"devDependencies":{"@babel/core":"^7.15.0","@babel/preset-env":"^7.15.0","babel-loader":"^8.2.2","webpack":"^5.51.1","webpack-cli":"^4.8.0"}}')}},r={};function t(n){var i=r[n];if(void 0!==i)return i.exports;var o=r[n]={exports:{}};return e[n](o,o.exports,t),o.exports}t.d=function(e,r){for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};!function(){t.r(n),t.d(n,{default:function(){return J},init_at:function(){return V}});var e="_suprsend_dist_id",r="_bulk_api_call",i="event/",o="_suprsend_super_props",a="_suprsend_device_id",s={Edge:["Edge"],"Opera Mini":["Opera Mini"],"Opera Mobile":["Opera Mobi"],Opera:["Opera"],"Internet Explorer":["Trident","MSIE"],Chrome:["Chrome"],Firefox:["Firefox"],Safari:["Safari"],Mozilla:["Mozilla"]},c={Edge:/Edge\/([0-9]+(\.[0-9]+)?)/,"Opera Mini":/Opera Mini\/([0-9]+(\.[0-9]+)?)/,"Opera Mobile":/Version\/([0-9]+(\.[0-9]+)?)/,Opera:/Version\/([0-9]+(\.[0-9]+)?)/,"Internet Explorer":"rv:",Chrome:/Chrome\/([0-9]+(\.[0-9]+)?)/,Firefox:/rv:([0-9]+(\.[0-9]+)?)/,Safari:/Version\/([0-9]+(\.[0-9]+)?)/,Mozilla:/rv:([0-9]+(\.[0-9]+)?)/},u={"Chrome OS":"CrOS","Mac OS":"Macintosh",Windows:"Windows",iOS:"like Mac",Android:"Android",Linux:"Linux"};const l={api_url:"https://collector.suprsend.workers.dev",sdk_version:t(147).version,batch_size:20,service_worker_file:"suprsend_service_worker.js",sw_delay:5e3};function f(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return p(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?p(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==t.return||t.return()}finally{if(s)throw o}}}}function p(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function d(){var e=!0;try{window.localStorage}catch(r){e=!1}return e}function v(e){if(d())return localStorage.getItem(e)}function _(e,r){d()&&localStorage.setItem(e,r)}function b(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=v(e);return t?JSON.parse(t):r}function h(){var e=navigator.userAgent;for(var r in s){var t,n=f(s[r]);try{for(n.s();!(t=n.n()).done;){var i=t.value;if(e.indexOf(i)>=0)return r}}catch(e){n.e(e)}finally{n.f()}}}function g(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"post";return fetch("".concat(l.api_url,"/").concat(e),{method:t,body:JSON.stringify(r),headers:{"Content-Type":"application/json"}})}function y(){var e=b(r,[]);if(e.length){var t=e.slice(0,l.batch_size);g(i,t).then((function(e){if(!e.ok)throw new Error("Error in Fetch");var t=b(r,[]);t.splice(0,l.batch_size),_(r,JSON.stringify(t)),y()})).catch((function(){m(12e4)}))}else m()}function m(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e3;setTimeout((function(){y()}),e)}const w={uuid:function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(r){var t=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==r?t:3&t|8).toString(16)}))},epoch_milliseconds:function(){return Math.round(Date.now())},cookie_enabled:function(){return navigator.cookieEnabled},set_cookie:function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365,n="";if(t){var i=new Date;i.setTime(i.getTime()+24*t*60*60*1e3),n="; expires="+i.toUTCString()}document.cookie=e+"="+(r||"")+n+"; path=/"},get_cookie:function(e){for(var r=e+"=",t=document.cookie.split(";"),n=0;n<t.length;n++){for(var i=t[n];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(r))return i.substring(r.length,i.length)}return null},remove_cookie:function(e){document.cookie=e+"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"},local_storage_enabled:d,get_local_storage_item:v,set_local_storage_item:_,remove_local_storage_item:function(e){d()&&localStorage.removeItem(e)},get_parsed_local_store_data:b,browser:h,browser_version:function(){var e=navigator.userAgent,r=h(),t=c[r];if(t){var n=e.match(t);if(n&&n.length>1)return n[1]}},os:function(){var e=navigator.userAgent;for(var r in u)if(e.indexOf(u[r])>=0)return r},schedule_flush:m,format_props:function(e,r){var t;if(e instanceof Object){t={};for(var n=Object.keys(e),i=0;i<n.length;i++){var o=n[i];void 0!==e[o]&&(t[String(o)]=e[o])}}else null!=r&&(t=function(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}({},String(e),r));return t},urlB64ToUint8Array:function(e){for(var r=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),t=atob(r),n=new Uint8Array(t.length),i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n},batch_or_call:function(e){if(d()){var t=b(r,[]);null==t||t.push(e),_(r,JSON.stringify(t))}else g(i,e)}};function O(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function k(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function x(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}const j=function(){function e(r,t){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),this.env=r,this.instance=t}var r,t;return r=e,(t=[{key:"_call_indetity",value:function(e){w.batch_or_call(function(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?O(Object(t),!0).forEach((function(r){k(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):O(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}({env:this.env,distinct_id:this.instance.distinct_id},e))}},{key:"set",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$set:t})}},{key:"set_once",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$set_once:t})}},{key:"increment",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,t=w.format_props(e,r);if(t){for(var n=Object.keys(t),i=0;i<n.length;i++){var o=n[i],a=Number(t[o]);a||delete t[o]}this._call_indetity({$add:t})}}},{key:"append",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$append:t})}},{key:"remove",value:function(e,r){var t=w.format_props(e,r);t&&this._call_indetity({$remove:t})}},{key:"unset",value:function(e){var r;if("string"==typeof e)r=[String(e)];else{if(!(e instanceof Array))return;r=e.map((function(e){return String(e)}))}this._call_indetity({$unset:r})}},{key:"add_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$email",e)}},{key:"remove_email",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.remove("$email",e)}},{key:"add_sms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$sms",e)}},{key:"add_whatsapp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append("$whatsapp",e)}},{key:"add_webpush",value:function(){var e,r,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.append({$webpush:JSON.stringify(t),$device_id:null===(e=this.instance)||void 0===e||null===(r=e.env_properties)||void 0===r?void 0:r.$device_id})}}])&&x(r.prototype,t),e}();function P(e,r,t,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void t(e)}s.done?r(c):Promise.resolve(c).then(n,i)}function S(e){return function(){var r=this,t=arguments;return new Promise((function(n,i){var o=e.apply(r,t);function a(e){P(o,n,i,a,s,"next",e)}function s(e){P(o,n,i,a,s,"throw",e)}a(void 0)}))}}function E(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function A(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var M;const $=function(){function e(r,t){var n=this;!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),A(this,"_check_push_support",(function(){return!(!("serviceWorker"in navigator)||!("PushManager"in window))})),A(this,"_ask_notification_permission",S(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Notification.requestPermission();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e)})))),A(this,"_register_sw",(function(){return navigator.serviceWorker.register("/".concat(l.service_worker_file)).then((function(e){console.log("Service worker successfully registered."),n._subscribe_push(e)})).catch((function(e){console.error("Unable to register service worker.",e)}))})),A(this,"_get_subscription",(function(){return navigator.serviceWorker.ready.then((function(e){return e.pushManager.getSubscription()})).then(function(){var e=S(regeneratorRuntime.mark((function e(r){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",r);case 3:case"end":return e.stop()}}),e)})));return function(r){return e.apply(this,arguments)}}())})),A(this,"_subscribe_push",function(){var e=S(regeneratorRuntime.mark((function e(r){var t,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return console.log("calling subscribe 1.3"),e.next=3,n._ask_notification_permission();case 3:if("granted"!==e.sent){e.next=18;break}return e.next=7,n._get_subscription();case 7:if(e.sent){e.next=17;break}return console.log("API_CALL: get public vapid from server"),t=w.urlB64ToUint8Array("BADMgGsRZWdjJPH34F0v9OTQfrxHArhk_sVawIACOFHTcaPF_Cfpq1uBX6lOwHByQDjt8f05h3ESK3dldpG3Q9Q"),e.next=13,r.pushManager.subscribe({applicationServerKey:t,userVisibleOnly:!0});case 13:i=e.sent,n.user.add_webpush(i),e.next=18;break;case 17:console.log("Push already subscribed");case 18:case"end":return e.stop()}}),e)})));return function(r){return e.apply(this,arguments)}}()),A(this,"register_push",(function(){n._check_push_support()?(console.log("calling subscribe 1"),n._subscribe_with_delay()):console.log("OOPS, Web Push isn't supported")})),A(this,"is_subscribed",S(regeneratorRuntime.mark((function e(){var r;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._get_subscription();case 2:return r=e.sent,e.abrupt("return",!!r);case 4:case"end":return e.stop()}}),e)})))),this.env=r,this.instance=t,this.user=new j(r,t)}var r,t;return r=e,(t=[{key:"_subscribe_with_delay",value:function(){var e=this,r=new Date-V;r>=l.sw_delay?(console.log("calling subscribe 1.1"),this._subscribe_push()):(console.log("calling subscribe 1.2"),clearTimeout(M),M=setTimeout((function(){e._subscribe_push()}),l.sw_delay-r))}},{key:"update_subscription",value:function(){var e,r,t=this;null===(e=navigator)||void 0===e||null===(r=e.serviceWorker)||void 0===r||r.ready.then((function(e){return e.pushManager.getSubscription()})).then((function(e){e&&(t.user.add_webpush(e),console.log("API_CALL: save subscription",e))}))}}])&&E(r.prototype,t),e}();function T(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function I(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?T(Object(t),!0).forEach((function(r){N(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):T(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function C(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function N(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var D,V,K=function(){function r(){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,r)}var t,n,i;return t=r,i=[{key:"setEnvProperties",value:function(){var e=w.get_local_storage_item(a);e||(e=w.uuid(),w.set_local_storage_item(a,e)),D.env_properties={$os:w.os(),$browser:w.browser(),$browser_version:w.browser_version(),$sdk_type:"Browser",$device_id:e,$sdk_version:l.sdk_version}}}],(n=[{key:"initialize",value:function(t){V=new Date;var n=w.get_cookie(e);D||(r.ENV_API_KEY=t,D={}),n||(n=w.uuid(),w.set_cookie(e,n)),D.distinct_id=n,this.user=new j(r.ENV_API_KEY,D),this.sw=new $(r.ENV_API_KEY,D),this.sw.update_subscription(),r.setEnvProperties(),w.schedule_flush()}},{key:"set_super_properties",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=w.get_parsed_local_store_data(o),t=I(I({},r),e);w.set_local_storage_item(o,JSON.stringify(t)),D.env_properties=I(I({},D.env_properties),t)}},{key:"identify",value:function(t){D._user_identified||(w.batch_or_call({env:r.ENV_API_KEY,event:"$identify",properties:{$identified_id:t,$anon_id:D.distinct_id}}),w.set_cookie(e,t),D.distinct_id=t,D._user_identified=!0)}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=e){var n=w.get_parsed_local_store_data(o),i=w.format_props(I(I(I(I({},t),D.env_properties),n),{},{$current_url:window.location.href}));w.batch_or_call({event:String(e),distinct_id:D.distinct_id,env:r.ENV_API_KEY,properties:i,$insert_id:w.uuid(),$time:w.epoch_milliseconds()})}}},{key:"reset",value:function(){var t=w.uuid();w.set_cookie(e,t),D={distinct_id:t,_user_identified:!1},w.remove_local_storage_item(o),this.user=new j(r.ENV_API_KEY,D),this.sw=new $(r.ENV_API_KEY,D),r.setEnvProperties()}}])&&C(t.prototype,n),i&&C(t,i),r}();N(K,"ENV_API_KEY",void 0);const J=new K}();var i=exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})}();
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@suprsend/web-sdk",
3
- "version": "0.1.3",
3
+ "version": "0.1.7",
4
4
  "description": "This is sdk used to integrate suprsend functionality in javascript applications",
5
5
  "main": "dist/cjs_bundle.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1",
8
- "build": "rm -rf dist && webpack --env module_type=commonjs --env filename=cjs_bundle.js && webpack --env module_type=window --env filename=cdn_bundle.js"
8
+ "build": "rm -rf dist && webpack --env module_type=commonjs --env filename=cjs_bundle.js && webpack --env module_type=window --env filename=cdn_bundle.js",
9
+ "publish_sdk": "npm run build && npm publish"
9
10
  },
10
11
  "keywords": [
11
12
  "suprsend",
package/src/config.js CHANGED
@@ -1,7 +1,12 @@
1
+ const package_data = require("../package.json");
2
+
1
3
  // suprsend sdk related config
2
4
  const config = {
3
- api_url: "https://hub.relayroad.com",
4
- sdk_version: "1.0.0",
5
+ api_url: "https://collector.suprsend.workers.dev",
6
+ sdk_version: package_data.version,
7
+ batch_size: 20,
8
+ service_worker_file: "suprsend_service_worker.js",
9
+ sw_delay: 5000, //in ms
5
10
  };
6
11
 
7
12
  export default config;
package/src/constants.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // suprsend sdk related constants
2
2
  export const constants = {
3
3
  distinct_id: "_suprsend_dist_id",
4
- bulk_events_key: "bulk_api_call",
4
+ bulk_events_key: "_bulk_api_call",
5
5
  api_events_route: "event/",
6
6
  super_properties_key: "_suprsend_super_props",
7
+ device_id_key: "_suprsend_device_id",
7
8
  };
8
9
 
9
10
  export const browser_useragent_map = {
package/src/index.js CHANGED
@@ -1,42 +1,33 @@
1
- import utils, { timerID } from "./utils";
1
+ import utils from "./utils";
2
2
  import config from "./config";
3
3
  import User from "./user";
4
+ import ServiceWorker from "./service_worker";
4
5
  import { constants } from "./constants";
5
6
 
6
7
  var suprSendInstance;
7
-
8
- window.addEventListener("load", () => {
9
- if (timerID) {
10
- clearTimeout(timerID);
11
- setTimeout(() => {
12
- utils.bulk_call_api(true);
13
- }, 2000);
14
- }
15
- });
16
-
17
- window.addEventListener("online", () => {
18
- if (timerID) {
19
- clearTimeout(timerID);
20
- setTimeout(() => {
21
- utils.bulk_call_api(true);
22
- }, 2000);
23
- }
24
- });
8
+ export var init_at;
25
9
 
26
10
  class SuprSend {
27
11
  static ENV_API_KEY;
28
12
 
29
13
  static setEnvProperties() {
14
+ let device_id = utils.get_local_storage_item(constants.device_id_key);
15
+ if (!device_id) {
16
+ device_id = utils.uuid();
17
+ utils.set_local_storage_item(constants.device_id_key, device_id);
18
+ }
30
19
  suprSendInstance.env_properties = {
31
20
  $os: utils.os(),
32
21
  $browser: utils.browser(),
33
22
  $browser_version: utils.browser_version(),
34
23
  $sdk_type: "Browser",
24
+ $device_id: device_id,
35
25
  $sdk_version: config.sdk_version,
36
26
  };
37
27
  }
38
28
 
39
29
  initialize(ENV_API_KEY) {
30
+ init_at = new Date();
40
31
  var distinct_id = utils.get_cookie(constants.distinct_id);
41
32
  if (!suprSendInstance) {
42
33
  SuprSend.ENV_API_KEY = ENV_API_KEY;
@@ -48,7 +39,10 @@ class SuprSend {
48
39
  }
49
40
  suprSendInstance.distinct_id = distinct_id;
50
41
  this.user = new User(SuprSend.ENV_API_KEY, suprSendInstance);
42
+ this.sw = new ServiceWorker(SuprSend.ENV_API_KEY, suprSendInstance);
43
+ this.sw.update_subscription();
51
44
  SuprSend.setEnvProperties();
45
+ utils.schedule_flush();
52
46
  }
53
47
 
54
48
  set_super_properties(props = {}) {
@@ -68,22 +62,17 @@ class SuprSend {
68
62
 
69
63
  identify(unique_id) {
70
64
  if (!suprSendInstance._user_identified) {
71
- utils
72
- .call_api({
73
- env: SuprSend.ENV_API_KEY,
74
- event: "$identify",
75
- properties: {
76
- $identified_id: unique_id,
77
- $anon_id: suprSendInstance.distinct_id,
78
- },
79
- })
80
- .then((res) => {
81
- if (res.ok) {
82
- utils.set_cookie(constants.distinct_id, unique_id);
83
- suprSendInstance.distinct_id = unique_id;
84
- suprSendInstance._user_identified = true;
85
- }
86
- });
65
+ utils.batch_or_call({
66
+ env: SuprSend.ENV_API_KEY,
67
+ event: "$identify",
68
+ properties: {
69
+ $identified_id: unique_id,
70
+ $anon_id: suprSendInstance.distinct_id,
71
+ },
72
+ });
73
+ utils.set_cookie(constants.distinct_id, unique_id);
74
+ suprSendInstance.distinct_id = unique_id;
75
+ suprSendInstance._user_identified = true;
87
76
  }
88
77
  }
89
78
 
@@ -98,7 +87,7 @@ class SuprSend {
98
87
  ...super_props,
99
88
  $current_url: window.location.href,
100
89
  });
101
- utils.call_api({
90
+ utils.batch_or_call({
102
91
  event: String(event),
103
92
  distinct_id: suprSendInstance.distinct_id,
104
93
  env: SuprSend.ENV_API_KEY,
@@ -118,6 +107,7 @@ class SuprSend {
118
107
  };
119
108
  utils.remove_local_storage_item(constants.super_properties_key);
120
109
  this.user = new User(SuprSend.ENV_API_KEY, suprSendInstance);
110
+ this.sw = new ServiceWorker(SuprSend.ENV_API_KEY, suprSendInstance);
121
111
  SuprSend.setEnvProperties();
122
112
  }
123
113
  }
@@ -0,0 +1,124 @@
1
+ import utils from "./utils";
2
+ import config from "./config";
3
+ import User from "./user";
4
+ import { init_at } from "./index";
5
+
6
+ var notification_timer;
7
+ class ServiceWorker {
8
+ constructor(env_key, instance) {
9
+ this.env = env_key;
10
+ this.instance = instance;
11
+ this.user = new User(env_key, instance);
12
+ }
13
+
14
+ _check_push_support = () => {
15
+ return !!("serviceWorker" in navigator && "PushManager" in window);
16
+ };
17
+
18
+ _ask_notification_permission = async () =>
19
+ await Notification.requestPermission();
20
+
21
+ _register_sw = () => {
22
+ return navigator.serviceWorker
23
+ .register(`/${config.service_worker_file}`)
24
+ .then((registration) => {
25
+ console.log("Service worker successfully registered.");
26
+ this._subscribe_push(registration);
27
+ })
28
+ .catch((err) => {
29
+ console.error("Unable to register service worker.", err);
30
+ });
31
+ };
32
+
33
+ _get_subscription = () => {
34
+ return navigator.serviceWorker.ready
35
+ .then((registration) => {
36
+ return registration.pushManager.getSubscription();
37
+ })
38
+ .then(async (subscription) => {
39
+ if (!subscription) {
40
+ return;
41
+ }
42
+ return subscription;
43
+ });
44
+ };
45
+
46
+ // this method make sure there is a given delay, as calling notification permission just after load is not good UX practice
47
+ _subscribe_with_delay() {
48
+ const now = new Date();
49
+ const delay = now - init_at;
50
+ const has_delay = delay >= config.sw_delay;
51
+ if (has_delay) {
52
+ this._subscribe_push();
53
+ } else {
54
+ clearTimeout(notification_timer);
55
+ notification_timer = setTimeout(() => {
56
+ this._subscribe_push();
57
+ }, config.sw_delay - delay);
58
+ }
59
+ }
60
+
61
+ // 1. ask permission.
62
+ // 2. if permission is granted then check if its already subscribed.
63
+ // 3. if not subscribed already then subscribe to push.
64
+ _subscribe_push = async (reg) => {
65
+ const permission = await this._ask_notification_permission();
66
+ if (permission === "granted") {
67
+ const subscription = await this._get_subscription();
68
+ if (!subscription) {
69
+ console.log("API_CALL: get public vapid from server");
70
+ const applicationServerKey = utils.urlB64ToUint8Array(
71
+ "BADMgGsRZWdjJPH34F0v9OTQfrxHArhk_sVawIACOFHTcaPF_Cfpq1uBX6lOwHByQDjt8f05h3ESK3dldpG3Q9Q"
72
+ );
73
+ const subscription = await reg.pushManager.subscribe({
74
+ applicationServerKey,
75
+ userVisibleOnly: true,
76
+ });
77
+ this.user.add_webpush(subscription);
78
+ } else {
79
+ console.log("Push already subscribed");
80
+ }
81
+ }
82
+ };
83
+
84
+ update_subscription() {
85
+ navigator?.serviceWorker?.ready
86
+ .then((registration) => {
87
+ return registration.pushManager.getSubscription();
88
+ })
89
+ .then((subscription) => {
90
+ if (!subscription) {
91
+ return;
92
+ }
93
+ this.user.add_webpush(subscription);
94
+ console.log("API_CALL: save subscription", subscription);
95
+ });
96
+ }
97
+
98
+ register_push = () => {
99
+ if (this._check_push_support()) {
100
+ this._subscribe_with_delay();
101
+ } else {
102
+ console.log("OOPS, Web Push isn't supported");
103
+ }
104
+ };
105
+
106
+ is_subscribed = async () => {
107
+ const subscription = await this._get_subscription();
108
+ return !!subscription;
109
+ };
110
+
111
+ // unsubscribe_push = () => {
112
+ // navigator.serviceWorker.ready
113
+ // .then((registration) => {
114
+ // return registration.pushManager.getSubscription();
115
+ // })
116
+ // .then((subscription) => {
117
+ // return subscription.unsubscribe().then(() => {
118
+ // console.log("API_CALL: unsubscription");
119
+ // });
120
+ // });
121
+ // };
122
+ }
123
+
124
+ export default ServiceWorker;
package/src/user.js CHANGED
@@ -7,7 +7,7 @@ class User {
7
7
  }
8
8
 
9
9
  _call_indetity(properties) {
10
- utils.call_api({
10
+ utils.batch_or_call({
11
11
  env: this.env,
12
12
  distinct_id: this.instance.distinct_id,
13
13
  ...properties,
@@ -84,6 +84,13 @@ class User {
84
84
  add_whatsapp(mobile = "") {
85
85
  this.append("$whatsapp", mobile);
86
86
  }
87
+
88
+ add_webpush(push = "") {
89
+ this.append({
90
+ $webpush: JSON.stringify(push),
91
+ $device_id: this.instance?.env_properties?.$device_id,
92
+ });
93
+ }
87
94
  }
88
95
 
89
96
  export default User;
package/src/utils.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  } from "./constants";
7
7
  import config from "./config";
8
8
 
9
- export let timerID;
9
+ let timerID;
10
10
 
11
11
  function uuid() {
12
12
  var dt = new Date().getTime();
@@ -55,19 +55,31 @@ function remove_cookie(name) {
55
55
  }
56
56
 
57
57
  function local_storage_enabled() {
58
- return !!window.localStorage;
58
+ let enabled = true;
59
+ try {
60
+ !!window.localStorage;
61
+ } catch (err) {
62
+ enabled = false;
63
+ }
64
+ return enabled;
59
65
  }
60
66
 
61
67
  function get_local_storage_item(key) {
62
- return localStorage.getItem(key);
68
+ if (local_storage_enabled()) {
69
+ return localStorage.getItem(key);
70
+ }
63
71
  }
64
72
 
65
73
  function set_local_storage_item(key, value) {
66
- localStorage.setItem(key, value);
74
+ if (local_storage_enabled()) {
75
+ localStorage.setItem(key, value);
76
+ }
67
77
  }
68
78
 
69
79
  function remove_local_storage_item(key) {
70
- localStorage.removeItem(key);
80
+ if (local_storage_enabled()) {
81
+ localStorage.removeItem(key);
82
+ }
71
83
  }
72
84
 
73
85
  function get_parsed_local_store_data(key, default_value = {}) {
@@ -108,12 +120,6 @@ function os() {
108
120
  }
109
121
  }
110
122
 
111
- function get_bulk_events() {
112
- let data = get_local_storage_item(constants.bulk_events_key) || "[]";
113
- data = JSON.parse(data);
114
- return data;
115
- }
116
-
117
123
  function api(route, body, method = "post") {
118
124
  return fetch(`${config.api_url}/${route}`, {
119
125
  method: method,
@@ -122,17 +128,23 @@ function api(route, body, method = "post") {
122
128
  });
123
129
  }
124
130
 
125
- function bulk_call_api(handleCatch = false) {
126
- const items = get_bulk_events();
131
+ /*
132
+ 1. get data from local storage
133
+ 2. if data is present create first batch data and call api else schedule next flush
134
+ 3. if the above api call is success call next api call with next set of data if it exists
135
+ 4. If there is any error in api call then schedule flush after 2min
136
+ */
137
+ function bulk_call_api() {
138
+ const items = get_parsed_local_store_data(constants.bulk_events_key, []);
127
139
  if (items.length) {
128
- const batch = items.slice(0, 20);
140
+ const batch = items.slice(0, config.batch_size);
129
141
  api(constants.api_events_route, batch)
130
142
  .then((res) => {
131
143
  if (!res.ok) {
132
144
  throw new Error("Error in Fetch");
133
145
  }
134
- let items = get_bulk_events();
135
- items.splice(0, 20);
146
+ let items = get_parsed_local_store_data(constants.bulk_events_key, []);
147
+ items.splice(0, config.batch_size);
136
148
  set_local_storage_item(
137
149
  constants.bulk_events_key,
138
150
  JSON.stringify(items)
@@ -140,35 +152,39 @@ function bulk_call_api(handleCatch = false) {
140
152
  bulk_call_api();
141
153
  })
142
154
  .catch(() => {
143
- if (handleCatch) {
144
- handle_event_timer();
145
- }
155
+ schedule_flush(2 * 60 * 1000);
146
156
  });
157
+ } else {
158
+ schedule_flush();
147
159
  }
148
160
  }
149
161
 
150
- function call_api(body, route = constants.api_events_route) {
151
- return api(route, body).catch(() => {
152
- let parsed_data = get_bulk_events();
162
+ /*
163
+ schedule the flush in some time future
164
+ */
165
+ function schedule_flush(delay = 5000) {
166
+ timerID = setTimeout(() => {
167
+ bulk_call_api();
168
+ }, delay);
169
+ }
170
+
171
+ /*
172
+ local storage enabled => add it to local storage which will be picked by continuous flusher
173
+ local storage disabled => call the api directly
174
+ */
175
+ function batch_or_call(body) {
176
+ if (local_storage_enabled()) {
177
+ let parsed_data = get_parsed_local_store_data(
178
+ constants.bulk_events_key,
179
+ []
180
+ );
153
181
  parsed_data?.push(body);
154
182
  set_local_storage_item(
155
183
  constants.bulk_events_key,
156
184
  JSON.stringify(parsed_data)
157
185
  );
158
- handle_event_timer();
159
- });
160
- }
161
-
162
- function handle_event_timer() {
163
- if (!timerID) {
164
- timerID = setInterval(() => {
165
- const items = get_bulk_events();
166
- if (items.length) {
167
- bulk_call_api();
168
- } else {
169
- clearInterval(timerID);
170
- }
171
- }, 2 * 60 * 1000);
186
+ } else {
187
+ api(constants.api_events_route, body);
172
188
  }
173
189
  }
174
190
 
@@ -189,6 +205,19 @@ function format_props(key, value) {
189
205
  return formatted_data;
190
206
  }
191
207
 
208
+ function urlB64ToUint8Array(base64String) {
209
+ const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
210
+ const base64 = (base64String + padding)
211
+ .replace(/\-/g, "+")
212
+ .replace(/_/g, "/");
213
+ const rawData = atob(base64);
214
+ const outputArray = new Uint8Array(rawData.length);
215
+ for (let i = 0; i < rawData.length; ++i) {
216
+ outputArray[i] = rawData.charCodeAt(i);
217
+ }
218
+ return outputArray;
219
+ }
220
+
192
221
  export default {
193
222
  uuid,
194
223
  epoch_milliseconds,
@@ -204,7 +233,8 @@ export default {
204
233
  browser,
205
234
  browser_version,
206
235
  os,
207
- call_api,
208
- bulk_call_api,
236
+ schedule_flush,
209
237
  format_props,
238
+ urlB64ToUint8Array,
239
+ batch_or_call,
210
240
  };