@carter-rmn/cpix-js 1.0.0-alpha.5 → 1.0.0
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/README.md +1 -1
- package/dist/cpix.cjs +1 -1
- package/dist/cpix.iife.js +1 -1
- package/dist/cpix.js +4 -4
- package/dist/cpix.umd.cjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
package/dist/cpix.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var E=(u,e,t)=>e in u?v(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var o=(u,e,t)=>(E(u,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.5",b="module",A=["dist"],P="dist/cpix.umd.cjs",T="dist/cpix.js",U="dist/cpix.d.ts",_={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},C={dev:"vite",build:"tsc && vite build",preview:"vite preview"},D={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:S,version:x,type:b,files:A,main:P,module:T,types:U,exports:_,scripts:C,devDependencies:D,dependencies:I},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:p.version,package:p.name},c={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"],a=function(){const u=()=>l.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){u()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(a.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){a.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(){a.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){a.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){a.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(){a.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){a.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class h{static getBrowserInfo(){var n,r,m,f,g;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=(r=e.match(/firefox\/(\d+)/i))==null?void 0:r[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=(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(`${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 a.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 a.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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let r;for(;(r=i.exec(t))!==null;)r[2]&&n.push(decodeURIComponent(r[2].replace(/\+/g," ")));return n.length>0?n: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}`,r=new Date;r.setTime(r.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${r.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=k;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(d.isPresent(w.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let r=0;r<e.length;r++){const m=e[r];i=w.getParametersByName(m,window.location.href),n.push({[m]:i})}s.set(c.UTM,JSON.stringify(n),14*24*60)}}static getUtms(){const e=s.get(c.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(c.SESSION)||s.set(c.SESSION,d.guid(),14*24*60),s.setUtms()}}class R{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 N({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(c.SESSION)||s.createSession(),s.exists(c.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),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(c.ACCESS_TOKEN)||(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,a.debug("CPIX Initialized"),a.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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),a.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(c.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(c.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 h.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(c.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:h.getDeviceCategory(),brand:h.getDeviceManufacturer(),ip_address:e.ip_address,platform:h.getDevicePlatform()},referrer:encodeURIComponent(document.referrer)}}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(c.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");a.debug("Event published:",t.ok)}catch(t){throw a.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=(u,e,t)=>e in u?v(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var o=(u,e,t)=>(E(u,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S="@carter-rmn/cpix-js",x="1.0.0",b="module",A=["dist"],P="dist/cpix.umd.cjs",T="dist/cpix.js",U="dist/cpix.d.ts",_={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},C={dev:"vite",build:"tsc && vite build",preview:"vite preview"},D={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:S,version:x,type:b,files:A,main:P,module:T,types:U,exports:_,scripts:C,devDependencies:D,dependencies:I},l={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:p.version,package:p.name},c={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"],a=function(){const u=()=>l.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){u()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(a.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){a.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(){a.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){a.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){a.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(){a.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){a.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}}class h{static getBrowserInfo(){var r,n,m,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=(n=e.match(/firefox\/(\d+)/i))==null?void 0:n[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=(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(`${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 a.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 a.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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),r=[];let n;for(;(n=i.exec(t))!==null;)n[2]&&r.push(decodeURIComponent(n[2].replace(/\+/g," ")));return r.length>0?r: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(r=>r.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const r=`${s.prefix()}${e}`,n=new Date;n.setTime(n.getTime()+i*60*1e3),document.cookie=`${r}=${t}; expires=${n.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=k;let t=!1;for(let i=0;i<e.length;i++){const r=e[i];if(d.isPresent(w.getParametersByName(r,window.location.href))){t=!0;break}}if(t){let i;const r=[];for(let n=0;n<e.length;n++){const m=e[n];i=w.getParametersByName(m,window.location.href),r.push({[m]:i})}s.set(c.UTM,JSON.stringify(r),14*24*60)}}static getUtms(){const e=s.get(c.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(c.SESSION)||s.set(c.SESSION,d.guid(),14*24*60),s.setUtms()}}class R{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 N({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,l.API_URL=this.instances[0].options.tracker_server_url,s.exists(c.SESSION)||s.createSession(),s.exists(c.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),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(c.ACCESS_TOKEN)||(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,a.debug("CPIX Initialized"),a.debug("Carter Analytics SDK initialized with options:",this.instances),l.DEBUG=this.instances[0].options.debug===!0,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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),a.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(c.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(c.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 h.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(c.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:h.getDeviceCategory(),brand:h.getDeviceManufacturer(),ip_address:e.ip_address,platform:h.getDevicePlatform()},referrer:encodeURIComponent(document.referrer)}}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(c.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");a.debug("Event published:",t.ok)}catch(t){throw a.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;
|
package/dist/cpix.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 c=(l,d,m)=>(T(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.5",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},o={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"],r=function(){const f=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&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();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(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,a,g,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=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[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(`${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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n: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(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.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.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),20160)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),20160),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(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.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=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),1440)}),s.setUtms(),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 p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,r.debug("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.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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.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),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(o.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:encodeURIComponent(document.referrer)}}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 p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),new Error("[CPIX] Failed to publish event");r.debug("Event published:",t.ok)}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}({});
|
|
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 c=(l,d,m)=>(T(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0",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:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},o={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"],r=function(){const f=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&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();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(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,a,g,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=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[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(`${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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n: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(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.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.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),20160)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),20160),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(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.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,u.API_URL=this.instances[0].options.tracker_server_url,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),1440)}),s.setUtms(),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 p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),u.DEBUG=this.instances[0].options.debug===!0,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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.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),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(o.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:encodeURIComponent(document.referrer)}}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 p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),new Error("[CPIX] Failed to publish event");r.debug("Event published:",t.ok)}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,7 +1,7 @@
|
|
|
1
1
|
var y = Object.defineProperty;
|
|
2
2
|
var v = (u, e, t) => e in u ? y(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
3
3
|
var o = (u, e, t) => (v(u, typeof e != "symbol" ? e + "" : e, t), t);
|
|
4
|
-
const E = "@carter-rmn/cpix-js", S = "1.0.0
|
|
4
|
+
const E = "@carter-rmn/cpix-js", S = "1.0.0", x = "module", b = [
|
|
5
5
|
"dist"
|
|
6
6
|
], A = "dist/cpix.umd.cjs", P = "dist/cpix.js", T = "dist/cpix.d.ts", U = {
|
|
7
7
|
".": {
|
|
@@ -35,7 +35,7 @@ const E = "@carter-rmn/cpix-js", S = "1.0.0-alpha.5", x = "module", b = [
|
|
|
35
35
|
}, l = {
|
|
36
36
|
DEBUG: !1,
|
|
37
37
|
TRACKER_FUNC_NAME: "cpix",
|
|
38
|
-
API_URL: "
|
|
38
|
+
API_URL: "",
|
|
39
39
|
QUEUE_MAX_RETRIES: 3,
|
|
40
40
|
QUEUE_INITIAL_DELAY: 1e4,
|
|
41
41
|
version: p.version,
|
|
@@ -312,7 +312,7 @@ class N {
|
|
|
312
312
|
throw new Error(
|
|
313
313
|
"[CPIX] At least one instance configuration is required for initialization"
|
|
314
314
|
);
|
|
315
|
-
if (this.instances = e, s.exists(c.SESSION) || s.createSession(), s.exists(c.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
|
|
315
|
+
if (this.instances = e, l.API_URL = this.instances[0].options.tracker_server_url, s.exists(c.SESSION) || s.createSession(), s.exists(c.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
|
|
316
316
|
this.metaParameters = t, s.set("metaParameters", JSON.stringify(t), 60 * 24);
|
|
317
317
|
}), s.setUtms(), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
|
|
318
318
|
throw new Error(
|
|
@@ -325,7 +325,7 @@ class N {
|
|
|
325
325
|
), s.set(c.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, a.debug("CPIX Initialized"), a.debug(
|
|
326
326
|
"Carter Analytics SDK initialized with options:",
|
|
327
327
|
this.instances
|
|
328
|
-
), l.DEBUG = this.instances[0].options.debug === !0,
|
|
328
|
+
), l.DEBUG = this.instances[0].options.debug === !0, this.publish({
|
|
329
329
|
event: "init",
|
|
330
330
|
...this.metaParameters
|
|
331
331
|
}), this.publish({
|
package/dist/cpix.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.tracker={}))})(this,function(u){"use strict";var P=Object.defineProperty;var T=(u,l,p)=>l in u?P(u,l,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[l]=p;var c=(u,l,p)=>(T(u,typeof l!="symbol"?l+"":l,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.5",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"}},d={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},o={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"],r=function(){const f=()=>d.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&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();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(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,a,g,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=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[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(`${d.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(`${d.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:d.package,version:d.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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n: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`__${d.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}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.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.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),14*24*60)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),14*24*60),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:d.QUEUE_MAX_RETRIES,initialDelay:d.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=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),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,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),d.DEBUG=this.instances[0].options.debug===!0,d.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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.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:encodeURIComponent(document.referrer)}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${d.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");r.debug("Event published:",t.ok)}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),u.CarterAnalytics=v,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.tracker={}))})(this,function(u){"use strict";var P=Object.defineProperty;var T=(u,l,p)=>l in u?P(u,l,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[l]=p;var c=(u,l,p)=>(T(u,typeof l!="symbol"?l+"":l,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0",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"}},d={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},o={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"],r=function(){const f=()=>d.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&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();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(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,a,g,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=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[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(`${d.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(`${d.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:d.package,version:d.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 getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n: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`__${d.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}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.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.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),14*24*60)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),14*24*60),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:d.QUEUE_MAX_RETRIES,initialDelay:d.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,d.API_URL=this.instances[0].options.tracker_server_url,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),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,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),d.DEBUG=this.instances[0].options.debug===!0,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};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.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:encodeURIComponent(document.referrer)}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${d.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");r.debug("Event published:",t.ok)}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),u.CarterAnalytics=v,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
|