@carter-rmn/cpix-js 1.0.0-alpha.3 → 1.0.0-alpha.4
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/dist/cpix.cjs +1 -1
- package/dist/cpix.iife.js +1 -1
- package/dist/cpix.js +73 -64
- package/dist/cpix.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/cpix.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var E=(o,e,t)=>e in o?v(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var a=(o,e,t)=>(E(o,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x="@carter-rmn/cpix-js",S="1.0.0-alpha.3",b="module",P=["dist"],A="dist/cpix.umd.cjs",_="dist/cpix.js",U="dist/cpix.d.ts",T={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},D={dev:"vite",build:"tsc && vite build",preview:"vite preview"},C={picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},I={"vite-plugin-dts":"^3.8.1"},p={name:x,version:S,type:b,files:P,main:A,module:_,types:U,exports:T,scripts:D,devDependencies:C,dependencies:I},c={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:p.version,package:p.name},l={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},k=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],n=function(){const o=()=>c.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){o()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(n.debug("Consuming event:",i),Promise.resolve())}){super();a(this,"dataQueue");a(this,"retryQueue");a(this,"maxRetries");a(this,"initialDelay");a(this,"publishEvent");a(this,"retryEvent");a(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){n.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){n.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(s){n.error("Failed to publish event:",s),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){n.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){n.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(s){n.error("Failed to publish event:",s),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var s,u,h,f,g;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(s=e.match(/chrome\/(\d+)/i))==null?void 0:s[1]):/firefox/i.test(e)?(t="Firefox",i=(u=e.match(/firefox\/(\d+)/i))==null?void 0:u[1]):/safari/i.test(e)?(t="Safari",i=(h=e.match(/version\/(\d+)/i))==null?void 0:h[1]):/edge/i.test(e)?(t="Edge",i=(f=e.match(/edge\/(\d+)/i))==null?void 0:f[1]):/trident/i.test(e)?(t="Internet Explorer",i=(g=e.match(/rv:(\d+)/i))==null?void 0:g[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${c.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return n.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${c.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:c.package,version:c.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw n.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class d{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return p.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return d.isPresent(e)===!1?"":typeof e=="object"?d.optionalData(JSON.stringify(e)):typeof e=="function"?d.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class w{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const s=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return s?s[2]?decodeURIComponent(s[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class r{static prefix(){return`__${c.TRACKER_FUNC_NAME}__`}static get(e){const t=`${r.prefix()}${e}`,i=document.cookie.split("; ").find(s=>s.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const s=`${r.prefix()}${e}`,u=new Date;u.setTime(u.getTime()+i*60*1e3),document.cookie=`${s}=${t}; expires=${u.toUTCString()}; path=/`}static delete(e){const t=`${r.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(r.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!r.get(e)}static setUtms(){const e=k;let t=!1;for(let i=0;i<e.length;i++){const s=e[i];if(d.isPresent(w.getParameterByName(s,window.location.href))){t=!0;break}}if(t){let i="";const s={};for(let u=0;u<e.length;u++){const h=e[u];i=w.getParameterByName(h,window.location.href),d.isPresent(i)&&(s[h]=i),s[h]=i}r.set(l.UTM,JSON.stringify(s),30)}}static getUtms(){const e=r.get(l.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){r.exists(l.SESSION)||r.set(l.SESSION,d.guid(),30*24*60),r.setUtms()}}class R{constructor(){a(this,"instances",[]);a(this,"initialized",!1);a(this,"accessToken","");a(this,"metaParameters",{});a(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new N({maxRetries:c.QUEUE_MAX_RETRIES,initialDelay:c.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(r.exists(l.SESSION)||r.createSession(),r.exists(l.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{r.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(r.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");this.instances=e,r.exists(l.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),r.set(l.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,n.info("CPIX Initialized"),n.debug("Carter Analytics SDK initialized with options:",this.instances),c.DEBUG=this.instances[0].options.debug===!0,c.API_URL=this.instances[0].options.tracker_server_url,this.metaParameters.client_id=this.instances[0].client_id,r.set("metaParameters",JSON.stringify(this.metaParameters),60*24),this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};n.debug("Publishing event:",t),this.queue.publish(t)}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{session:r.get(l.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:document.referrer,utm_params:r.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${c.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.get(l.ACCESS_TOKEN)}`}});if(!t.ok)throw new Error("[CPIX] Failed to publish event");const i=await t.json();n.debug("Event published:",i)}catch(t){throw n.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const y=new R;typeof window<"u"&&(window.cpix=y);exports.CarterAnalytics=y;
|
|
1
|
+
"use strict";var v=Object.defineProperty;var E=(c,e,t)=>e in c?v(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var a=(c,e,t)=>(E(c,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S="@carter-rmn/cpix-js",x="1.0.0-alpha.4",b="module",A=["dist"],P="dist/cpix.umd.cjs",T="dist/cpix.js",_="dist/cpix.d.ts",U={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},D={dev:"vite",build:"tsc && vite build",preview:"vite preview"},k={picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},C={"vite-plugin-dts":"^3.8.1"},p={name:S,version:x,type:b,files:A,main:P,module:T,types:_,exports:U,scripts:D,devDependencies:k,dependencies:C},u={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:p.version,package:p.name},o={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},I=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],n=function(){const c=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){c()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(n.debug("Consuming event:",i),Promise.resolve())}){super();a(this,"dataQueue");a(this,"retryQueue");a(this,"maxRetries");a(this,"initialDelay");a(this,"publishEvent");a(this,"retryEvent");a(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){n.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){n.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){n.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){n.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){n.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){n.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var r,l,h,f,g;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(r=e.match(/chrome\/(\d+)/i))==null?void 0:r[1]):/firefox/i.test(e)?(t="Firefox",i=(l=e.match(/firefox\/(\d+)/i))==null?void 0:l[1]):/safari/i.test(e)?(t="Safari",i=(h=e.match(/version\/(\d+)/i))==null?void 0:h[1]):/edge/i.test(e)?(t="Edge",i=(f=e.match(/edge\/(\d+)/i))==null?void 0:f[1]):/trident/i.test(e)?(t="Internet Explorer",i=(g=e.match(/rv:(\d+)/i))==null?void 0:g[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${u.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return n.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${u.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:u.package,version:u.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw n.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class d{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return p.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return d.isPresent(e)===!1?"":typeof e=="object"?d.optionalData(JSON.stringify(e)):typeof e=="function"?d.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class w{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const r=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${u.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const r=`${s.prefix()}${e}`,l=new Date;l.setTime(l.getTime()+i*60*1e3),document.cookie=`${r}=${t}; expires=${l.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=I;let t=!1;for(let i=0;i<e.length;i++){const r=e[i];if(d.isPresent(w.getParameterByName(r,window.location.href))){t=!0;break}}if(t){let i="";const r={};for(let l=0;l<e.length;l++){const h=e[l];i=w.getParameterByName(h,window.location.href),d.isPresent(i)&&(r[h]=i),r[h]=i}s.set(o.UTM,JSON.stringify(r),30)}}static getUtms(){const e=s.get(o.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,d.guid(),30*24*60),s.setUtms()}}class M{constructor(){a(this,"instances",[]);a(this,"initialized",!1);a(this,"accessToken","");a(this,"metaParameters",{});a(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new N({maxRetries:u.QUEUE_MAX_RETRIES,initialDelay:u.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(o.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,n.debug("CPIX Initialized"),n.debug("Carter Analytics SDK initialized with options:",this.instances),u.DEBUG=this.instances[0].options.debug===!0,u.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};n.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(o.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(o.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(o.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${u.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(o.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");const i=await t.json();n.debug("Event published:",i)}catch(t){throw n.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const y=new M;typeof window<"u"&&(window.cpix=y);exports.CarterAnalytics=y;
|
package/dist/cpix.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var tracker=function(l){"use strict";var A=Object.defineProperty;var _=(l,d,m)=>d in l?A(l,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[d]=m;var a=(l,d,m)=>(_(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.3",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},o={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},c={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},S=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],s=function(){const g=()=>o.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(s.debug("Consuming event:",i),Promise.resolve())}){super();a(this,"dataQueue");a(this,"retryQueue");a(this,"maxRetries");a(this,"initialDelay");a(this,"publishEvent");a(this,"retryEvent");a(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){s.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){s.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){s.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){s.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){s.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){s.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class f{static getBrowserInfo(){var n,u,p,E,x;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(u=e.match(/firefox\/(\d+)/i))==null?void 0:u[1]):/safari/i.test(e)?(t="Safari",i=(p=e.match(/version\/(\d+)/i))==null?void 0:p[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(x=e.match(/rv:(\d+)/i))==null?void 0:x[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${o.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return s.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${o.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:o.package,version:o.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw s.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class r{static prefix(){return`__${o.TRACKER_FUNC_NAME}__`}static get(e){const t=`${r.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${r.prefix()}${e}`,u=new Date;u.setTime(u.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${u.toUTCString()}; path=/`}static delete(e){const t=`${r.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(r.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!r.get(e)}static setUtms(){const e=S;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParameterByName(n,window.location.href))){t=!0;break}}if(t){let i="";const n={};for(let u=0;u<e.length;u++){const p=e[u];i=y.getParameterByName(p,window.location.href),h.isPresent(i)&&(n[p]=i),n[p]=i}r.set(c.UTM,JSON.stringify(n),30)}}static getUtms(){const e=r.get(c.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){r.exists(c.SESSION)||r.set(c.SESSION,h.guid(),43200),r.setUtms()}}class P{constructor(){a(this,"instances",[]);a(this,"initialized",!1);a(this,"accessToken","");a(this,"metaParameters",{});a(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:o.QUEUE_MAX_RETRIES,initialDelay:o.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(r.exists(c.SESSION)||r.createSession(),r.exists(c.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{r.set("metaParameters",JSON.stringify(t),1440)}),this.metaParameters=JSON.parse(r.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");this.instances=e,r.exists(c.ACCESS_TOKEN)||(this.accessToken=await f.aquireAccessToken(this.instances[0].client_id),r.set(c.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,s.info("CPIX Initialized"),s.debug("Carter Analytics SDK initialized with options:",this.instances),o.DEBUG=this.instances[0].options.debug===!0,o.API_URL=this.instances[0].options.tracker_server_url,this.metaParameters.client_id=this.instances[0].client_id,r.set("metaParameters",JSON.stringify(this.metaParameters),1440),this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};s.debug("Publishing event:",t),this.queue.publish(t)}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await f.getDeviceNetworkParameters();return{session:r.get(c.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:f.getDeviceCategory(),brand:f.getDeviceManufacturer(),ip_address:e.ip_address,platform:f.getDevicePlatform()},referrer:document.referrer,utm_params:r.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${o.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.get(c.ACCESS_TOKEN)}`}});if(!t.ok)throw new Error("[CPIX] Failed to publish event");const i=await t.json();s.debug("Event published:",i)}catch(t){throw s.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new P;return typeof window<"u"&&(window.cpix=v),l.CarterAnalytics=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});
|
|
1
|
+
var tracker=function(l){"use strict";var P=Object.defineProperty;var T=(l,d,m)=>d in l?P(l,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[d]=m;var o=(l,d,m)=>(T(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.4",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},c={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},a={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},x=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],r=function(){const g=()=>c.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();o(this,"dataQueue");o(this,"retryQueue");o(this,"maxRetries");o(this,"initialDelay");o(this,"publishEvent");o(this,"retryEvent");o(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class p{static getBrowserInfo(){var n,u,f,E,S;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(u=e.match(/firefox\/(\d+)/i))==null?void 0:u[1]):/safari/i.test(e)?(t="Safari",i=(f=e.match(/version\/(\d+)/i))==null?void 0:f[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(S=e.match(/rv:(\d+)/i))==null?void 0:S[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${c.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${c.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:c.package,version:c.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${c.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,u=new Date;u.setTime(u.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${u.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=x;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParameterByName(n,window.location.href))){t=!0;break}}if(t){let i="";const n={};for(let u=0;u<e.length;u++){const f=e[u];i=y.getParameterByName(f,window.location.href),h.isPresent(i)&&(n[f]=i),n[f]=i}s.set(a.UTM,JSON.stringify(n),30)}}static getUtms(){const e=s.get(a.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(a.SESSION)||s.set(a.SESSION,h.guid(),43200),s.setUtms()}}class A{constructor(){o(this,"instances",[]);o(this,"initialized",!1);o(this,"accessToken","");o(this,"metaParameters",{});o(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:c.QUEUE_MAX_RETRIES,initialDelay:c.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(a.SESSION)||s.createSession(),s.exists(a.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),1440)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(a.ACCESS_TOKEN)||(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),c.DEBUG=this.instances[0].options.debug===!0,c.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(a.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(a.META_PARAMETERS,JSON.stringify(this.metaParameters),1440)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await p.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(a.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:p.getDeviceCategory(),brand:p.getDeviceManufacturer(),ip_address:e.ip_address,platform:p.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${c.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(a.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,240)),new Error("[CPIX] Failed to publish event");const i=await t.json();r.debug("Event published:",i)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;return typeof window<"u"&&(window.cpix=v),l.CarterAnalytics=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});
|
package/dist/cpix.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
var y = Object.defineProperty;
|
|
2
|
-
var v = (
|
|
3
|
-
var a = (
|
|
4
|
-
const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.
|
|
2
|
+
var v = (c, e, t) => e in c ? y(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t;
|
|
3
|
+
var a = (c, e, t) => (v(c, typeof e != "symbol" ? e + "" : e, t), t);
|
|
4
|
+
const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.4", S = "module", b = [
|
|
5
5
|
"dist"
|
|
6
|
-
],
|
|
6
|
+
], A = "dist/cpix.umd.cjs", P = "dist/cpix.js", T = "dist/cpix.d.ts", _ = {
|
|
7
7
|
".": {
|
|
8
8
|
import: "./dist/cpix.js",
|
|
9
9
|
require: "./dist/cpix.umd.cjs"
|
|
10
10
|
}
|
|
11
|
-
},
|
|
11
|
+
}, U = {
|
|
12
12
|
dev: "vite",
|
|
13
13
|
build: "tsc && vite build",
|
|
14
14
|
preview: "vite preview"
|
|
@@ -18,21 +18,21 @@ const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.3", S = "module", b = [
|
|
|
18
18
|
typescript: "^5.2.2",
|
|
19
19
|
vite: "^5.2.0",
|
|
20
20
|
"vite-plugin-progress": "^0.0.7"
|
|
21
|
-
},
|
|
21
|
+
}, k = {
|
|
22
22
|
"vite-plugin-dts": "^3.8.1"
|
|
23
23
|
}, p = {
|
|
24
24
|
name: E,
|
|
25
25
|
version: x,
|
|
26
26
|
type: S,
|
|
27
27
|
files: b,
|
|
28
|
-
main:
|
|
29
|
-
module:
|
|
30
|
-
types:
|
|
31
|
-
exports:
|
|
32
|
-
scripts:
|
|
28
|
+
main: A,
|
|
29
|
+
module: P,
|
|
30
|
+
types: T,
|
|
31
|
+
exports: _,
|
|
32
|
+
scripts: U,
|
|
33
33
|
devDependencies: D,
|
|
34
|
-
dependencies:
|
|
35
|
-
},
|
|
34
|
+
dependencies: k
|
|
35
|
+
}, u = {
|
|
36
36
|
DEBUG: !1,
|
|
37
37
|
TRACKER_FUNC_NAME: "cpix",
|
|
38
38
|
API_URL: "https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",
|
|
@@ -40,12 +40,12 @@ const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.3", S = "module", b = [
|
|
|
40
40
|
QUEUE_INITIAL_DELAY: 1e4,
|
|
41
41
|
version: p.version,
|
|
42
42
|
package: p.name
|
|
43
|
-
},
|
|
43
|
+
}, o = {
|
|
44
44
|
SESSION: "cpix_session",
|
|
45
45
|
META_PARAMETERS: "cpix_meta_parameters",
|
|
46
46
|
ACCESS_TOKEN: "cpix_access_token",
|
|
47
47
|
UTM: "cpix_utm"
|
|
48
|
-
},
|
|
48
|
+
}, C = [
|
|
49
49
|
"utm_source",
|
|
50
50
|
"utm_medium",
|
|
51
51
|
"utm_term",
|
|
@@ -55,20 +55,20 @@ const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.3", S = "module", b = [
|
|
|
55
55
|
"utm_creative_format",
|
|
56
56
|
"utm_marketing_tactic"
|
|
57
57
|
], n = /* @__PURE__ */ function() {
|
|
58
|
-
const
|
|
58
|
+
const c = () => u.DEBUG;
|
|
59
59
|
return {
|
|
60
60
|
info: function(...e) {
|
|
61
61
|
console.log(...e);
|
|
62
62
|
},
|
|
63
63
|
debug: function(...e) {
|
|
64
|
-
|
|
64
|
+
c() && console.log(...e);
|
|
65
65
|
},
|
|
66
66
|
error: function(...e) {
|
|
67
67
|
console.error(...e);
|
|
68
68
|
}
|
|
69
69
|
};
|
|
70
70
|
}();
|
|
71
|
-
class
|
|
71
|
+
class I extends EventTarget {
|
|
72
72
|
constructor(t = {
|
|
73
73
|
maxRetries: 3,
|
|
74
74
|
initialDelay: 1e4,
|
|
@@ -100,8 +100,8 @@ class k extends EventTarget {
|
|
|
100
100
|
const t = this.dataQueue.shift(), { data: i = {} } = t;
|
|
101
101
|
try {
|
|
102
102
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
103
|
-
} catch (
|
|
104
|
-
n.error("Failed to publish event:",
|
|
103
|
+
} catch (r) {
|
|
104
|
+
n.error("Failed to publish event:", r), this.scheduleRetry(t);
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
107
|
});
|
|
@@ -128,8 +128,8 @@ class k extends EventTarget {
|
|
|
128
128
|
const t = this.retryQueue.shift(), { data: i = {} } = t;
|
|
129
129
|
try {
|
|
130
130
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
131
|
-
} catch (
|
|
132
|
-
n.error("Failed to publish event:",
|
|
131
|
+
} catch (r) {
|
|
132
|
+
n.error("Failed to publish event:", r), this.scheduleRetry(t);
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
135
|
});
|
|
@@ -137,10 +137,10 @@ class k extends EventTarget {
|
|
|
137
137
|
}
|
|
138
138
|
class m {
|
|
139
139
|
static getBrowserInfo() {
|
|
140
|
-
var
|
|
140
|
+
var r, l, h, f, g;
|
|
141
141
|
const e = navigator.userAgent || "";
|
|
142
142
|
let t, i;
|
|
143
|
-
return /chrome/i.test(e) ? (t = "Chrome", i = (
|
|
143
|
+
return /chrome/i.test(e) ? (t = "Chrome", i = (r = e.match(/chrome\/(\d+)/i)) == null ? void 0 : r[1]) : /firefox/i.test(e) ? (t = "Firefox", i = (l = e.match(/firefox\/(\d+)/i)) == null ? void 0 : l[1]) : /safari/i.test(e) ? (t = "Safari", i = (h = e.match(/version\/(\d+)/i)) == null ? void 0 : h[1]) : /edge/i.test(e) ? (t = "Edge", i = (f = e.match(/edge\/(\d+)/i)) == null ? void 0 : f[1]) : /trident/i.test(e) ? (t = "Internet Explorer", i = (g = e.match(/rv:(\d+)/i)) == null ? void 0 : g[1]) : (t = "Unknown", i = "Unknown"), `${t} ${i}`;
|
|
144
144
|
}
|
|
145
145
|
static getDeviceCategory() {
|
|
146
146
|
const e = navigator.userAgent;
|
|
@@ -157,7 +157,7 @@ class m {
|
|
|
157
157
|
}
|
|
158
158
|
static async getDeviceNetworkParameters() {
|
|
159
159
|
try {
|
|
160
|
-
const e = await fetch(`${
|
|
160
|
+
const e = await fetch(`${u.API_URL}/api/geolocation`), { data: t } = await e.json();
|
|
161
161
|
return {
|
|
162
162
|
city: t.city || "Unknown",
|
|
163
163
|
region: t.region || "Unknown",
|
|
@@ -179,7 +179,7 @@ class m {
|
|
|
179
179
|
}
|
|
180
180
|
static async aquireAccessToken(e) {
|
|
181
181
|
try {
|
|
182
|
-
return (await (await fetch(`${
|
|
182
|
+
return (await (await fetch(`${u.API_URL}/api/authenticate`, {
|
|
183
183
|
method: "POST",
|
|
184
184
|
headers: {
|
|
185
185
|
"Content-Type": "application/json"
|
|
@@ -187,8 +187,8 @@ class m {
|
|
|
187
187
|
body: JSON.stringify({
|
|
188
188
|
accountId: e,
|
|
189
189
|
metadata: {
|
|
190
|
-
sdk:
|
|
191
|
-
version:
|
|
190
|
+
sdk: u.package,
|
|
191
|
+
version: u.version,
|
|
192
192
|
hostname: window.location.hostname
|
|
193
193
|
}
|
|
194
194
|
})
|
|
@@ -222,8 +222,8 @@ class d {
|
|
|
222
222
|
class w {
|
|
223
223
|
static getParameterByName(e, t) {
|
|
224
224
|
t || (t = window.location.href), e = e.replace(/[[\]]/g, "\\$&");
|
|
225
|
-
const
|
|
226
|
-
return
|
|
225
|
+
const r = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)", "i").exec(t);
|
|
226
|
+
return r ? r[2] ? decodeURIComponent(r[2].replace(/\+/g, " ")) : "" : null;
|
|
227
227
|
}
|
|
228
228
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
229
229
|
static externalHost(e) {
|
|
@@ -231,57 +231,57 @@ class w {
|
|
|
231
231
|
return e.hostname != location.hostname && ((t = e == null ? void 0 : e.protocol) == null ? void 0 : t.indexOf("http")) === 0;
|
|
232
232
|
}
|
|
233
233
|
}
|
|
234
|
-
class
|
|
234
|
+
class s {
|
|
235
235
|
static prefix() {
|
|
236
|
-
return `__${
|
|
236
|
+
return `__${u.TRACKER_FUNC_NAME}__`;
|
|
237
237
|
}
|
|
238
238
|
static get(e) {
|
|
239
|
-
const t = `${
|
|
239
|
+
const t = `${s.prefix()}${e}`, i = document.cookie.split("; ").find((r) => r.startsWith(`${t}=`));
|
|
240
240
|
return i ? i.split("=")[1] : void 0;
|
|
241
241
|
}
|
|
242
242
|
static set(e, t, i) {
|
|
243
|
-
const
|
|
244
|
-
|
|
243
|
+
const r = `${s.prefix()}${e}`, l = /* @__PURE__ */ new Date();
|
|
244
|
+
l.setTime(l.getTime() + i * 60 * 1e3), document.cookie = `${r}=${t}; expires=${l.toUTCString()}; path=/`;
|
|
245
245
|
}
|
|
246
246
|
static delete(e) {
|
|
247
|
-
const t = `${
|
|
247
|
+
const t = `${s.prefix()}${e}`;
|
|
248
248
|
document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
|
|
249
249
|
}
|
|
250
250
|
static clear() {
|
|
251
|
-
document.cookie.split("; ").filter((e) => e.startsWith(
|
|
251
|
+
document.cookie.split("; ").filter((e) => e.startsWith(s.prefix())).forEach((e) => {
|
|
252
252
|
const t = e.split("=")[0];
|
|
253
253
|
document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
|
|
254
254
|
});
|
|
255
255
|
}
|
|
256
256
|
static exists(e) {
|
|
257
|
-
return !!
|
|
257
|
+
return !!s.get(e);
|
|
258
258
|
}
|
|
259
259
|
static setUtms() {
|
|
260
|
-
const e =
|
|
260
|
+
const e = C;
|
|
261
261
|
let t = !1;
|
|
262
262
|
for (let i = 0; i < e.length; i++) {
|
|
263
|
-
const
|
|
264
|
-
if (d.isPresent(w.getParameterByName(
|
|
263
|
+
const r = e[i];
|
|
264
|
+
if (d.isPresent(w.getParameterByName(r, window.location.href))) {
|
|
265
265
|
t = !0;
|
|
266
266
|
break;
|
|
267
267
|
}
|
|
268
268
|
}
|
|
269
269
|
if (t) {
|
|
270
270
|
let i = "";
|
|
271
|
-
const
|
|
272
|
-
for (let
|
|
273
|
-
const h = e[
|
|
274
|
-
i = w.getParameterByName(h, window.location.href), d.isPresent(i) && (
|
|
271
|
+
const r = {};
|
|
272
|
+
for (let l = 0; l < e.length; l++) {
|
|
273
|
+
const h = e[l];
|
|
274
|
+
i = w.getParameterByName(h, window.location.href), d.isPresent(i) && (r[h] = i), r[h] = i;
|
|
275
275
|
}
|
|
276
|
-
|
|
276
|
+
s.set(o.UTM, JSON.stringify(r), 30);
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
279
|
static getUtms() {
|
|
280
|
-
const e =
|
|
280
|
+
const e = s.get(o.UTM);
|
|
281
281
|
return d.isPresent(e) ? JSON.parse(e) : {};
|
|
282
282
|
}
|
|
283
283
|
static createSession() {
|
|
284
|
-
|
|
284
|
+
s.exists(o.SESSION) || s.set(o.SESSION, d.guid(), 30 * 24 * 60), s.setUtms();
|
|
285
285
|
}
|
|
286
286
|
}
|
|
287
287
|
class N {
|
|
@@ -295,10 +295,10 @@ class N {
|
|
|
295
295
|
throw new Error(
|
|
296
296
|
"[CPIX] CarterAnalytics SDK can only be used in a browser environment"
|
|
297
297
|
);
|
|
298
|
-
this.queue = new
|
|
299
|
-
maxRetries:
|
|
300
|
-
initialDelay:
|
|
301
|
-
consumerHandler: this.publishEventToServer
|
|
298
|
+
this.queue = new I({
|
|
299
|
+
maxRetries: u.QUEUE_MAX_RETRIES,
|
|
300
|
+
initialDelay: u.QUEUE_INITIAL_DELAY,
|
|
301
|
+
consumerHandler: this.publishEventToServer.bind(this)
|
|
302
302
|
});
|
|
303
303
|
}
|
|
304
304
|
/**
|
|
@@ -310,20 +310,20 @@ class N {
|
|
|
310
310
|
throw new Error(
|
|
311
311
|
"[CPIX] At least one instance configuration is required for initialization"
|
|
312
312
|
);
|
|
313
|
-
if (
|
|
314
|
-
|
|
315
|
-
}), this.metaParameters = JSON.parse(
|
|
313
|
+
if (this.instances = e, s.exists(o.SESSION) || s.createSession(), s.exists(o.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
|
|
314
|
+
s.set("metaParameters", JSON.stringify(t), 60 * 24);
|
|
315
|
+
}), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
|
|
316
316
|
throw new Error(
|
|
317
317
|
"[CPIX] CarterAnalytics SDK has already been initialized"
|
|
318
318
|
);
|
|
319
319
|
if (!this.metaParameters)
|
|
320
320
|
throw new Error("[CPIX] Meta parameters have not been generated");
|
|
321
|
-
|
|
321
|
+
s.exists(o.ACCESS_TOKEN) || (this.accessToken = await m.aquireAccessToken(
|
|
322
322
|
this.instances[0].client_id
|
|
323
|
-
),
|
|
323
|
+
), s.set(o.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, n.debug("CPIX Initialized"), n.debug(
|
|
324
324
|
"Carter Analytics SDK initialized with options:",
|
|
325
325
|
this.instances
|
|
326
|
-
),
|
|
326
|
+
), u.DEBUG = this.instances[0].options.debug === !0, u.API_URL = this.instances[0].options.tracker_server_url, this.publish({
|
|
327
327
|
event: "init",
|
|
328
328
|
...this.metaParameters
|
|
329
329
|
}), this.publish({
|
|
@@ -349,7 +349,13 @@ class N {
|
|
|
349
349
|
...e,
|
|
350
350
|
...this.metaParameters
|
|
351
351
|
};
|
|
352
|
-
n.debug("Publishing event:", t), this.queue.publish(t)
|
|
352
|
+
n.debug("Publishing event:", t), this.queue.publish(t), e.event === "logout" && (s.delete(o.SESSION), s.createSession(), this.generateMetaParameters().then((i) => {
|
|
353
|
+
this.metaParameters = i, s.set(
|
|
354
|
+
o.META_PARAMETERS,
|
|
355
|
+
JSON.stringify(this.metaParameters),
|
|
356
|
+
60 * 24
|
|
357
|
+
);
|
|
358
|
+
}));
|
|
353
359
|
}
|
|
354
360
|
/**
|
|
355
361
|
* Generates meta parameters that is attached to every event before publishing.
|
|
@@ -361,7 +367,8 @@ class N {
|
|
|
361
367
|
);
|
|
362
368
|
const e = await m.getDeviceNetworkParameters();
|
|
363
369
|
return {
|
|
364
|
-
|
|
370
|
+
client_id: this.instances[0].client_id,
|
|
371
|
+
session: s.get(o.SESSION),
|
|
365
372
|
location: {
|
|
366
373
|
city: e.city,
|
|
367
374
|
region: e.region,
|
|
@@ -376,7 +383,7 @@ class N {
|
|
|
376
383
|
platform: m.getDevicePlatform()
|
|
377
384
|
},
|
|
378
385
|
referrer: document.referrer,
|
|
379
|
-
utm_params:
|
|
386
|
+
utm_params: s.getUtms()
|
|
380
387
|
};
|
|
381
388
|
}
|
|
382
389
|
/**
|
|
@@ -386,16 +393,18 @@ class N {
|
|
|
386
393
|
async publishEventToServer(e) {
|
|
387
394
|
try {
|
|
388
395
|
e.timestamp = Date.now();
|
|
389
|
-
const t = await fetch(`${
|
|
396
|
+
const t = await fetch(`${u.API_URL}/api/event`, {
|
|
390
397
|
method: "POST",
|
|
391
398
|
body: JSON.stringify({ event_data: e }),
|
|
392
399
|
headers: {
|
|
393
400
|
"Content-Type": "application/json",
|
|
394
|
-
Authorization: `Bearer ${
|
|
401
|
+
Authorization: `Bearer ${s.get(o.ACCESS_TOKEN)}`
|
|
395
402
|
}
|
|
396
403
|
});
|
|
397
404
|
if (!t.ok)
|
|
398
|
-
throw
|
|
405
|
+
throw t.status === 401 && (this.accessToken = await m.aquireAccessToken(
|
|
406
|
+
this.instances[0].client_id
|
|
407
|
+
), s.set(o.ACCESS_TOKEN, this.accessToken, 60 * 4)), new Error("[CPIX] Failed to publish event");
|
|
399
408
|
const i = await t.json();
|
|
400
409
|
n.debug("Event published:", i);
|
|
401
410
|
} catch (t) {
|
package/dist/cpix.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(o,c){typeof exports=="object"&&typeof module<"u"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(o=typeof globalThis<"u"?globalThis:o||self,c(o.tracker={}))})(this,function(o){"use strict";var A=Object.defineProperty;var T=(o,c,p)=>c in o?A(o,c,{enumerable:!0,configurable:!0,writable:!0,value:p}):o[c]=p;var a=(o,c,p)=>(T(o,typeof c!="symbol"?c+"":c,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.3",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},u={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},l={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},S=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],r=function(){const g=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();a(this,"dataQueue");a(this,"retryQueue");a(this,"maxRetries");a(this,"initialDelay");a(this,"publishEvent");a(this,"retryEvent");a(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(s){r.error("Failed to publish event:",s),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(s){r.error("Failed to publish event:",s),this.scheduleRetry(t)}}})}}class f{static getBrowserInfo(){var s,d,m,E,x;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(s=e.match(/chrome\/(\d+)/i))==null?void 0:s[1]):/firefox/i.test(e)?(t="Firefox",i=(d=e.match(/firefox\/(\d+)/i))==null?void 0:d[1]):/safari/i.test(e)?(t="Safari",i=(m=e.match(/version\/(\d+)/i))==null?void 0:m[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(x=e.match(/rv:(\d+)/i))==null?void 0:x[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${u.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${u.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:u.package,version:u.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const s=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return s?s[2]?decodeURIComponent(s[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class n{static prefix(){return`__${u.TRACKER_FUNC_NAME}__`}static get(e){const t=`${n.prefix()}${e}`,i=document.cookie.split("; ").find(s=>s.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const s=`${n.prefix()}${e}`,d=new Date;d.setTime(d.getTime()+i*60*1e3),document.cookie=`${s}=${t}; expires=${d.toUTCString()}; path=/`}static delete(e){const t=`${n.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(n.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!n.get(e)}static setUtms(){const e=S;let t=!1;for(let i=0;i<e.length;i++){const s=e[i];if(h.isPresent(y.getParameterByName(s,window.location.href))){t=!0;break}}if(t){let i="";const s={};for(let d=0;d<e.length;d++){const m=e[d];i=y.getParameterByName(m,window.location.href),h.isPresent(i)&&(s[m]=i),s[m]=i}n.set(l.UTM,JSON.stringify(s),30)}}static getUtms(){const e=n.get(l.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){n.exists(l.SESSION)||n.set(l.SESSION,h.guid(),30*24*60),n.setUtms()}}class P{constructor(){a(this,"instances",[]);a(this,"initialized",!1);a(this,"accessToken","");a(this,"metaParameters",{});a(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:u.QUEUE_MAX_RETRIES,initialDelay:u.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(n.exists(l.SESSION)||n.createSession(),n.exists(l.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{n.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(n.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");this.instances=e,n.exists(l.ACCESS_TOKEN)||(this.accessToken=await f.aquireAccessToken(this.instances[0].client_id),n.set(l.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,r.info("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),u.DEBUG=this.instances[0].options.debug===!0,u.API_URL=this.instances[0].options.tracker_server_url,this.metaParameters.client_id=this.instances[0].client_id,n.set("metaParameters",JSON.stringify(this.metaParameters),60*24),this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};r.debug("Publishing event:",t),this.queue.publish(t)}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await f.getDeviceNetworkParameters();return{session:n.get(l.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:f.getDeviceCategory(),brand:f.getDeviceManufacturer(),ip_address:e.ip_address,platform:f.getDevicePlatform()},referrer:document.referrer,utm_params:n.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${u.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.get(l.ACCESS_TOKEN)}`}});if(!t.ok)throw new Error("[CPIX] Failed to publish event");const i=await t.json();r.debug("Event published:",i)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new P;typeof window<"u"&&(window.cpix=v),o.CarterAnalytics=v,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(c,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(c=typeof globalThis<"u"?globalThis:c||self,u(c.tracker={}))})(this,function(c){"use strict";var P=Object.defineProperty;var T=(c,u,p)=>u in c?P(c,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):c[u]=p;var o=(c,u,p)=>(T(c,typeof u!="symbol"?u+"":u,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.4",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},l={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},a={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},S=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],r=function(){const g=()=>l.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();o(this,"dataQueue");o(this,"retryQueue");o(this,"maxRetries");o(this,"initialDelay");o(this,"publishEvent");o(this,"retryEvent");o(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var n,d,f,E,x;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(d=e.match(/firefox\/(\d+)/i))==null?void 0:d[1]):/safari/i.test(e)?(t="Safari",i=(f=e.match(/version\/(\d+)/i))==null?void 0:f[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(x=e.match(/rv:(\d+)/i))==null?void 0:x[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${l.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${l.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:l.package,version:l.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${l.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,d=new Date;d.setTime(d.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${d.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=S;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParameterByName(n,window.location.href))){t=!0;break}}if(t){let i="";const n={};for(let d=0;d<e.length;d++){const f=e[d];i=y.getParameterByName(f,window.location.href),h.isPresent(i)&&(n[f]=i),n[f]=i}s.set(a.UTM,JSON.stringify(n),30)}}static getUtms(){const e=s.get(a.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(a.SESSION)||s.set(a.SESSION,h.guid(),30*24*60),s.setUtms()}}class A{constructor(){o(this,"instances",[]);o(this,"initialized",!1);o(this,"accessToken","");o(this,"metaParameters",{});o(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:l.QUEUE_MAX_RETRIES,initialDelay:l.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(a.SESSION)||s.createSession(),s.exists(a.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(a.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),l.DEBUG=this.instances[0].options.debug===!0,l.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(a.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(a.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(a.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${l.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(a.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");const i=await t.json();r.debug("Event published:",i)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;typeof window<"u"&&(window.cpix=v),c.CarterAnalytics=v,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|