@carter-rmn/cpix-js 1.0.0-alpha.3 → 1.0.0-alpha.5
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/common/url.d.ts +1 -1
- package/dist/cpix.cjs +1 -1
- package/dist/cpix.iife.js +1 -1
- package/dist/cpix.js +107 -98
- package/dist/cpix.umd.cjs +1 -1
- package/dist/main.d.ts +1 -0
- package/dist/types/index.d.ts +4 -0
- package/package.json +7 -7
- package/LICENCE +0 -32
package/dist/common/url.d.ts
CHANGED
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=(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;
|
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 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}({});
|
package/dist/cpix.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
var y = Object.defineProperty;
|
|
2
|
-
var v = (
|
|
3
|
-
var
|
|
4
|
-
const E = "@carter-rmn/cpix-js",
|
|
2
|
+
var v = (u, e, t) => e in u ? y(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
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-alpha.5", 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
|
".": {
|
|
8
8
|
import: "./dist/cpix.js",
|
|
9
9
|
require: "./dist/cpix.umd.cjs"
|
|
10
10
|
}
|
|
11
|
-
},
|
|
11
|
+
}, _ = {
|
|
12
12
|
dev: "vite",
|
|
13
13
|
build: "tsc && vite build",
|
|
14
14
|
preview: "vite preview"
|
|
15
|
-
},
|
|
15
|
+
}, C = {
|
|
16
16
|
picocolors: "^1.0.0",
|
|
17
17
|
"rollup-plugin-visualizer": "^5.12.0",
|
|
18
18
|
typescript: "^5.2.2",
|
|
19
19
|
vite: "^5.2.0",
|
|
20
20
|
"vite-plugin-progress": "^0.0.7"
|
|
21
|
-
},
|
|
21
|
+
}, D = {
|
|
22
22
|
"vite-plugin-dts": "^3.8.1"
|
|
23
23
|
}, p = {
|
|
24
24
|
name: E,
|
|
25
|
-
version:
|
|
26
|
-
type:
|
|
25
|
+
version: S,
|
|
26
|
+
type: x,
|
|
27
27
|
files: b,
|
|
28
|
-
main:
|
|
29
|
-
module:
|
|
30
|
-
types:
|
|
28
|
+
main: A,
|
|
29
|
+
module: P,
|
|
30
|
+
types: T,
|
|
31
31
|
exports: U,
|
|
32
|
-
scripts:
|
|
33
|
-
devDependencies:
|
|
34
|
-
dependencies:
|
|
35
|
-
},
|
|
32
|
+
scripts: _,
|
|
33
|
+
devDependencies: C,
|
|
34
|
+
dependencies: D
|
|
35
|
+
}, l = {
|
|
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,7 +40,7 @@ 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
|
+
}, c = {
|
|
44
44
|
SESSION: "cpix_session",
|
|
45
45
|
META_PARAMETERS: "cpix_meta_parameters",
|
|
46
46
|
ACCESS_TOKEN: "cpix_access_token",
|
|
@@ -50,18 +50,15 @@ const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.3", S = "module", b = [
|
|
|
50
50
|
"utm_medium",
|
|
51
51
|
"utm_term",
|
|
52
52
|
"utm_content",
|
|
53
|
-
"utm_campaign"
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
"utm_marketing_tactic"
|
|
57
|
-
], n = /* @__PURE__ */ function() {
|
|
58
|
-
const o = () => c.DEBUG;
|
|
53
|
+
"utm_campaign"
|
|
54
|
+
], a = /* @__PURE__ */ function() {
|
|
55
|
+
const u = () => l.DEBUG;
|
|
59
56
|
return {
|
|
60
57
|
info: function(...e) {
|
|
61
58
|
console.log(...e);
|
|
62
59
|
},
|
|
63
60
|
debug: function(...e) {
|
|
64
|
-
|
|
61
|
+
u() && console.log(...e);
|
|
65
62
|
},
|
|
66
63
|
error: function(...e) {
|
|
67
64
|
console.error(...e);
|
|
@@ -72,20 +69,20 @@ class k extends EventTarget {
|
|
|
72
69
|
constructor(t = {
|
|
73
70
|
maxRetries: 3,
|
|
74
71
|
initialDelay: 1e4,
|
|
75
|
-
consumerHandler: (i) => (
|
|
72
|
+
consumerHandler: (i) => (a.debug("Consuming event:", i), Promise.resolve())
|
|
76
73
|
}) {
|
|
77
74
|
super();
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
75
|
+
o(this, "dataQueue");
|
|
76
|
+
o(this, "retryQueue");
|
|
77
|
+
o(this, "maxRetries");
|
|
78
|
+
o(this, "initialDelay");
|
|
79
|
+
o(this, "publishEvent");
|
|
80
|
+
o(this, "retryEvent");
|
|
81
|
+
o(this, "handler");
|
|
85
82
|
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();
|
|
86
83
|
}
|
|
87
84
|
publish(t) {
|
|
88
|
-
|
|
85
|
+
a.debug("publishing event");
|
|
89
86
|
const i = {
|
|
90
87
|
data: t,
|
|
91
88
|
id: `${Date.now() + Math.random()}`,
|
|
@@ -95,20 +92,20 @@ class k extends EventTarget {
|
|
|
95
92
|
this.dataQueue.push(i), this.dispatchEvent(this.publishEvent);
|
|
96
93
|
}
|
|
97
94
|
consume() {
|
|
98
|
-
|
|
95
|
+
a.debug("Started Consumer Queue"), this.addEventListener("eventPublished", async () => {
|
|
99
96
|
for (; this.dataQueue.length > 0; ) {
|
|
100
97
|
const t = this.dataQueue.shift(), { data: i = {} } = t;
|
|
101
98
|
try {
|
|
102
99
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
103
|
-
} catch (
|
|
104
|
-
|
|
100
|
+
} catch (n) {
|
|
101
|
+
a.error("Failed to publish event:", n), this.scheduleRetry(t);
|
|
105
102
|
}
|
|
106
103
|
}
|
|
107
104
|
});
|
|
108
105
|
}
|
|
109
106
|
scheduleRetry(t) {
|
|
110
107
|
if (t.retryCount >= this.maxRetries) {
|
|
111
|
-
|
|
108
|
+
a.error("Max retries reached for message:", t);
|
|
112
109
|
return;
|
|
113
110
|
}
|
|
114
111
|
setTimeout(() => {
|
|
@@ -123,24 +120,24 @@ class k extends EventTarget {
|
|
|
123
120
|
this.dataQueue = this.dataQueue.filter((i) => i.id !== t);
|
|
124
121
|
}
|
|
125
122
|
retry() {
|
|
126
|
-
|
|
123
|
+
a.debug("Started Retry Queue"), this.addEventListener("retryMessage", async () => {
|
|
127
124
|
for (; this.retryQueue.length > 0; ) {
|
|
128
125
|
const t = this.retryQueue.shift(), { data: i = {} } = t;
|
|
129
126
|
try {
|
|
130
127
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
131
|
-
} catch (
|
|
132
|
-
|
|
128
|
+
} catch (n) {
|
|
129
|
+
a.error("Failed to publish event:", n), this.scheduleRetry(t);
|
|
133
130
|
}
|
|
134
131
|
}
|
|
135
132
|
});
|
|
136
133
|
}
|
|
137
134
|
}
|
|
138
|
-
class
|
|
135
|
+
class h {
|
|
139
136
|
static getBrowserInfo() {
|
|
140
|
-
var
|
|
137
|
+
var n, r, m, f, g;
|
|
141
138
|
const e = navigator.userAgent || "";
|
|
142
139
|
let t, i;
|
|
143
|
-
return /chrome/i.test(e) ? (t = "Chrome", i = (
|
|
140
|
+
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}`;
|
|
144
141
|
}
|
|
145
142
|
static getDeviceCategory() {
|
|
146
143
|
const e = navigator.userAgent;
|
|
@@ -157,7 +154,7 @@ class m {
|
|
|
157
154
|
}
|
|
158
155
|
static async getDeviceNetworkParameters() {
|
|
159
156
|
try {
|
|
160
|
-
const e = await fetch(`${
|
|
157
|
+
const e = await fetch(`${l.API_URL}/api/geolocation`), { data: t } = await e.json();
|
|
161
158
|
return {
|
|
162
159
|
city: t.city || "Unknown",
|
|
163
160
|
region: t.region || "Unknown",
|
|
@@ -167,7 +164,7 @@ class m {
|
|
|
167
164
|
ip_address: t.ip_address || "Unknown"
|
|
168
165
|
};
|
|
169
166
|
} catch (e) {
|
|
170
|
-
return
|
|
167
|
+
return a.error("Error retrieving device network parameters:", e), {
|
|
171
168
|
city: "Unknown",
|
|
172
169
|
region: "Unknown",
|
|
173
170
|
country: "Unknown",
|
|
@@ -179,7 +176,7 @@ class m {
|
|
|
179
176
|
}
|
|
180
177
|
static async aquireAccessToken(e) {
|
|
181
178
|
try {
|
|
182
|
-
return (await (await fetch(`${
|
|
179
|
+
return (await (await fetch(`${l.API_URL}/api/authenticate`, {
|
|
183
180
|
method: "POST",
|
|
184
181
|
headers: {
|
|
185
182
|
"Content-Type": "application/json"
|
|
@@ -187,14 +184,14 @@ class m {
|
|
|
187
184
|
body: JSON.stringify({
|
|
188
185
|
accountId: e,
|
|
189
186
|
metadata: {
|
|
190
|
-
sdk:
|
|
191
|
-
version:
|
|
187
|
+
sdk: l.package,
|
|
188
|
+
version: l.version,
|
|
192
189
|
hostname: window.location.hostname
|
|
193
190
|
}
|
|
194
191
|
})
|
|
195
192
|
})).json()).accessToken;
|
|
196
193
|
} catch (t) {
|
|
197
|
-
throw
|
|
194
|
+
throw a.error("Error acquiring access token:", t), new Error("[CPIX] Authentication error");
|
|
198
195
|
}
|
|
199
196
|
}
|
|
200
197
|
}
|
|
@@ -220,10 +217,13 @@ class d {
|
|
|
220
217
|
}
|
|
221
218
|
}
|
|
222
219
|
class w {
|
|
223
|
-
static
|
|
220
|
+
static getParametersByName(e, t) {
|
|
224
221
|
t || (t = window.location.href), e = e.replace(/[[\]]/g, "\\$&");
|
|
225
|
-
const
|
|
226
|
-
|
|
222
|
+
const i = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)", "gi"), n = [];
|
|
223
|
+
let r;
|
|
224
|
+
for (; (r = i.exec(t)) !== null; )
|
|
225
|
+
r[2] && n.push(decodeURIComponent(r[2].replace(/\+/g, " ")));
|
|
226
|
+
return n.length > 0 ? n : null;
|
|
227
227
|
}
|
|
228
228
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
229
229
|
static externalHost(e) {
|
|
@@ -231,74 +231,76 @@ 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 `__${l.TRACKER_FUNC_NAME}__`;
|
|
237
237
|
}
|
|
238
238
|
static get(e) {
|
|
239
|
-
const t = `${
|
|
239
|
+
const t = `${s.prefix()}${e}`, i = document.cookie.split("; ").find((n) => n.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 n = `${s.prefix()}${e}`, r = /* @__PURE__ */ new Date();
|
|
244
|
+
r.setTime(r.getTime() + i * 60 * 1e3), document.cookie = `${n}=${t}; expires=${r.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
260
|
const e = I;
|
|
261
261
|
let t = !1;
|
|
262
262
|
for (let i = 0; i < e.length; i++) {
|
|
263
|
-
const
|
|
264
|
-
if (d.isPresent(w.
|
|
263
|
+
const n = e[i];
|
|
264
|
+
if (d.isPresent(w.getParametersByName(n, window.location.href))) {
|
|
265
265
|
t = !0;
|
|
266
266
|
break;
|
|
267
267
|
}
|
|
268
268
|
}
|
|
269
269
|
if (t) {
|
|
270
|
-
let i
|
|
271
|
-
const
|
|
272
|
-
for (let
|
|
273
|
-
const
|
|
274
|
-
i = w.
|
|
270
|
+
let i;
|
|
271
|
+
const n = [];
|
|
272
|
+
for (let r = 0; r < e.length; r++) {
|
|
273
|
+
const m = e[r];
|
|
274
|
+
i = w.getParametersByName(m, window.location.href), n.push({
|
|
275
|
+
[m]: i
|
|
276
|
+
});
|
|
275
277
|
}
|
|
276
|
-
|
|
278
|
+
s.set(c.UTM, JSON.stringify(n), 14 * 24 * 60);
|
|
277
279
|
}
|
|
278
280
|
}
|
|
279
281
|
static getUtms() {
|
|
280
|
-
const e =
|
|
282
|
+
const e = s.get(c.UTM);
|
|
281
283
|
return d.isPresent(e) ? JSON.parse(e) : {};
|
|
282
284
|
}
|
|
283
285
|
static createSession() {
|
|
284
|
-
|
|
286
|
+
s.exists(c.SESSION) || s.set(c.SESSION, d.guid(), 14 * 24 * 60), s.setUtms();
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
class N {
|
|
288
290
|
constructor() {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
291
|
+
o(this, "instances", []);
|
|
292
|
+
o(this, "initialized", !1);
|
|
293
|
+
o(this, "accessToken", "");
|
|
294
|
+
o(this, "metaParameters", {});
|
|
295
|
+
o(this, "queue");
|
|
294
296
|
if (!window)
|
|
295
297
|
throw new Error(
|
|
296
298
|
"[CPIX] CarterAnalytics SDK can only be used in a browser environment"
|
|
297
299
|
);
|
|
298
300
|
this.queue = new k({
|
|
299
|
-
maxRetries:
|
|
300
|
-
initialDelay:
|
|
301
|
-
consumerHandler: this.publishEventToServer
|
|
301
|
+
maxRetries: l.QUEUE_MAX_RETRIES,
|
|
302
|
+
initialDelay: l.QUEUE_INITIAL_DELAY,
|
|
303
|
+
consumerHandler: this.publishEventToServer.bind(this)
|
|
302
304
|
});
|
|
303
305
|
}
|
|
304
306
|
/**
|
|
@@ -310,20 +312,20 @@ class N {
|
|
|
310
312
|
throw new Error(
|
|
311
313
|
"[CPIX] At least one instance configuration is required for initialization"
|
|
312
314
|
);
|
|
313
|
-
if (
|
|
314
|
-
|
|
315
|
-
}), this.metaParameters = JSON.parse(
|
|
315
|
+
if (this.instances = e, s.exists(c.SESSION) || s.createSession(), s.exists(c.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
|
|
316
|
+
this.metaParameters = t, s.set("metaParameters", JSON.stringify(t), 60 * 24);
|
|
317
|
+
}), s.setUtms(), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
|
|
316
318
|
throw new Error(
|
|
317
319
|
"[CPIX] CarterAnalytics SDK has already been initialized"
|
|
318
320
|
);
|
|
319
321
|
if (!this.metaParameters)
|
|
320
322
|
throw new Error("[CPIX] Meta parameters have not been generated");
|
|
321
|
-
|
|
323
|
+
s.exists(c.ACCESS_TOKEN) || (this.accessToken = await h.aquireAccessToken(
|
|
322
324
|
this.instances[0].client_id
|
|
323
|
-
),
|
|
325
|
+
), s.set(c.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, a.debug("CPIX Initialized"), a.debug(
|
|
324
326
|
"Carter Analytics SDK initialized with options:",
|
|
325
327
|
this.instances
|
|
326
|
-
),
|
|
328
|
+
), l.DEBUG = this.instances[0].options.debug === !0, l.API_URL = this.instances[0].options.tracker_server_url, this.publish({
|
|
327
329
|
event: "init",
|
|
328
330
|
...this.metaParameters
|
|
329
331
|
}), this.publish({
|
|
@@ -349,7 +351,13 @@ class N {
|
|
|
349
351
|
...e,
|
|
350
352
|
...this.metaParameters
|
|
351
353
|
};
|
|
352
|
-
|
|
354
|
+
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) => {
|
|
355
|
+
this.metaParameters = i, s.set(
|
|
356
|
+
c.META_PARAMETERS,
|
|
357
|
+
JSON.stringify(this.metaParameters),
|
|
358
|
+
60 * 24
|
|
359
|
+
);
|
|
360
|
+
}));
|
|
353
361
|
}
|
|
354
362
|
/**
|
|
355
363
|
* Generates meta parameters that is attached to every event before publishing.
|
|
@@ -359,9 +367,10 @@ class N {
|
|
|
359
367
|
throw new Error(
|
|
360
368
|
"[CPIX] Meta parameters can only be generated in a browser environment"
|
|
361
369
|
);
|
|
362
|
-
const e = await
|
|
370
|
+
const e = await h.getDeviceNetworkParameters();
|
|
363
371
|
return {
|
|
364
|
-
|
|
372
|
+
client_id: this.instances[0].client_id,
|
|
373
|
+
session: s.get(c.SESSION),
|
|
365
374
|
location: {
|
|
366
375
|
city: e.city,
|
|
367
376
|
region: e.region,
|
|
@@ -370,13 +379,12 @@ class N {
|
|
|
370
379
|
country: e.country
|
|
371
380
|
},
|
|
372
381
|
device: {
|
|
373
|
-
category:
|
|
374
|
-
brand:
|
|
382
|
+
category: h.getDeviceCategory(),
|
|
383
|
+
brand: h.getDeviceManufacturer(),
|
|
375
384
|
ip_address: e.ip_address,
|
|
376
|
-
platform:
|
|
385
|
+
platform: h.getDevicePlatform()
|
|
377
386
|
},
|
|
378
|
-
referrer: document.referrer
|
|
379
|
-
utm_params: r.getUtms()
|
|
387
|
+
referrer: encodeURIComponent(document.referrer)
|
|
380
388
|
};
|
|
381
389
|
}
|
|
382
390
|
/**
|
|
@@ -386,20 +394,21 @@ class N {
|
|
|
386
394
|
async publishEventToServer(e) {
|
|
387
395
|
try {
|
|
388
396
|
e.timestamp = Date.now();
|
|
389
|
-
const t = await fetch(`${
|
|
397
|
+
const t = await fetch(`${l.API_URL}/api/event`, {
|
|
390
398
|
method: "POST",
|
|
391
399
|
body: JSON.stringify({ event_data: e }),
|
|
392
400
|
headers: {
|
|
393
401
|
"Content-Type": "application/json",
|
|
394
|
-
Authorization: `Bearer ${
|
|
402
|
+
Authorization: `Bearer ${s.get(c.ACCESS_TOKEN)}`
|
|
395
403
|
}
|
|
396
404
|
});
|
|
397
405
|
if (!t.ok)
|
|
398
|
-
throw
|
|
399
|
-
|
|
400
|
-
|
|
406
|
+
throw t.status === 401 && (this.accessToken = await h.aquireAccessToken(
|
|
407
|
+
this.instances[0].client_id
|
|
408
|
+
), s.set(c.ACCESS_TOKEN, this.accessToken, 60 * 4)), new Error("[CPIX] Failed to publish event");
|
|
409
|
+
a.debug("Event published:", t.ok);
|
|
401
410
|
} catch (t) {
|
|
402
|
-
throw
|
|
411
|
+
throw a.error("Failed to publish event:", t), new Error("[CPIX] Failed to publish event");
|
|
403
412
|
}
|
|
404
413
|
}
|
|
405
414
|
}
|
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(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"})});
|
package/dist/main.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@carter-rmn/cpix-js",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
"require": "./dist/cpix.umd.cjs"
|
|
15
15
|
}
|
|
16
16
|
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"dev": "vite",
|
|
19
|
+
"build": "tsc && vite build",
|
|
20
|
+
"preview": "vite preview"
|
|
21
|
+
},
|
|
17
22
|
"devDependencies": {
|
|
18
23
|
"picocolors": "^1.0.0",
|
|
19
24
|
"rollup-plugin-visualizer": "^5.12.0",
|
|
@@ -23,10 +28,5 @@
|
|
|
23
28
|
},
|
|
24
29
|
"dependencies": {
|
|
25
30
|
"vite-plugin-dts": "^3.8.1"
|
|
26
|
-
},
|
|
27
|
-
"scripts": {
|
|
28
|
-
"dev": "vite",
|
|
29
|
-
"build": "tsc && vite build",
|
|
30
|
-
"preview": "vite preview"
|
|
31
31
|
}
|
|
32
|
-
}
|
|
32
|
+
}
|
package/LICENCE
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
Proprietary License
|
|
2
|
-
|
|
3
|
-
This software is licensed under the terms of this Proprietary License (the "License"). By using this software, you agree to comply with the terms of this License.
|
|
4
|
-
|
|
5
|
-
1. Grant of License
|
|
6
|
-
This software is licensed, not sold, to you by Carter Analytics for use only under the terms of this License. Carter Analytics retains ownership of the software itself and reserves all rights not expressly granted to you.
|
|
7
|
-
|
|
8
|
-
2. Permitted Use
|
|
9
|
-
You are granted a non-exclusive, non-transferable, limited license to use the software solely for your personal or internal business purposes, provided you have an active subscription to Carter Analytics's paid supporting service.
|
|
10
|
-
|
|
11
|
-
3. Restrictions
|
|
12
|
-
You may not:
|
|
13
|
-
a. Redistribute, sell, lease, sublicense, or otherwise transfer the software or any portion thereof.
|
|
14
|
-
b. Modify, adapt, translate, reverse engineer, decompile, or disassemble the software.
|
|
15
|
-
c. Remove or alter any proprietary notices or labels on the software.
|
|
16
|
-
|
|
17
|
-
4. Intellectual Property
|
|
18
|
-
All intellectual property rights in and to the software are and shall remain the exclusive property of Carter Analytics.
|
|
19
|
-
|
|
20
|
-
5. Disclaimer of Warranties
|
|
21
|
-
The software is provided "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose.
|
|
22
|
-
|
|
23
|
-
6. Limitation of Liability
|
|
24
|
-
In no event shall Carter Analytics be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use this software, even if Carter Analytics has been advised of the possibility of such damages.
|
|
25
|
-
|
|
26
|
-
7. Termination
|
|
27
|
-
This License is effective until terminated. Your rights under this License will terminate automatically without notice from Carter Analytics if you fail to comply with any term(s) of this License. Upon termination, you shall cease all use of the software and destroy all copies, full or partial, of the software.
|
|
28
|
-
|
|
29
|
-
8. Governing Law
|
|
30
|
-
This License shall be governed by and construed in accordance with the laws of [Your Jurisdiction].
|
|
31
|
-
|
|
32
|
-
By using this software, you acknowledge that you have read this License, understand it, and agree to be bound by its terms and conditions.
|