@carter-rmn/cpix-js 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cpix.js ADDED
@@ -0,0 +1,411 @@
1
+ var y = Object.defineProperty;
2
+ var v = (o, e, t) => e in o ? y(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var a = (o, e, t) => (v(o, typeof e != "symbol" ? e + "" : e, t), t);
4
+ const E = "@carter-analytics/cpix", x = "0.0.0", S = "module", b = [
5
+ "dist"
6
+ ], P = "dist/cpix.umd.cjs", A = "dist/cpix.js", _ = "dist/cpix.d.ts", U = {
7
+ ".": {
8
+ import: "./dist/cpix.js",
9
+ require: "./dist/cpix.umd.cjs"
10
+ }
11
+ }, T = {
12
+ dev: "vite",
13
+ build: "tsc && vite build",
14
+ preview: "vite preview"
15
+ }, D = {
16
+ picocolors: "^1.0.0",
17
+ "rollup-plugin-visualizer": "^5.12.0",
18
+ typescript: "^5.2.2",
19
+ vite: "^5.2.0",
20
+ "vite-plugin-progress": "^0.0.7"
21
+ }, C = {
22
+ "vite-plugin-dts": "^3.8.1"
23
+ }, p = {
24
+ name: E,
25
+ private: !0,
26
+ version: x,
27
+ type: S,
28
+ files: b,
29
+ main: P,
30
+ module: A,
31
+ types: _,
32
+ exports: U,
33
+ scripts: T,
34
+ devDependencies: D,
35
+ dependencies: C
36
+ }, c = {
37
+ DEBUG: !1,
38
+ TRACKER_FUNC_NAME: "cpix",
39
+ API_URL: "https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",
40
+ QUEUE_MAX_RETRIES: 3,
41
+ QUEUE_INITIAL_DELAY: 1e4,
42
+ version: p.version,
43
+ package: p.name
44
+ }, l = {
45
+ SESSION: "cpix_session",
46
+ META_PARAMETERS: "cpix_meta_parameters",
47
+ ACCESS_TOKEN: "cpix_access_token",
48
+ UTM: "cpix_utm"
49
+ }, I = [
50
+ "utm_source",
51
+ "utm_medium",
52
+ "utm_term",
53
+ "utm_content",
54
+ "utm_campaign",
55
+ "utm_source_platform",
56
+ "utm_creative_format",
57
+ "utm_marketing_tactic"
58
+ ], n = /* @__PURE__ */ function() {
59
+ const o = () => c.DEBUG;
60
+ return {
61
+ info: function(...e) {
62
+ console.log(...e);
63
+ },
64
+ debug: function(...e) {
65
+ o() && console.log(...e);
66
+ },
67
+ error: function(...e) {
68
+ console.error(...e);
69
+ }
70
+ };
71
+ }();
72
+ class k extends EventTarget {
73
+ constructor(t = {
74
+ maxRetries: 3,
75
+ initialDelay: 1e4,
76
+ consumerHandler: (i) => (n.debug("Consuming event:", i), Promise.resolve())
77
+ }) {
78
+ super();
79
+ a(this, "dataQueue");
80
+ a(this, "retryQueue");
81
+ a(this, "maxRetries");
82
+ a(this, "initialDelay");
83
+ a(this, "publishEvent");
84
+ a(this, "retryEvent");
85
+ a(this, "handler");
86
+ 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();
87
+ }
88
+ publish(t) {
89
+ n.debug("publishing event");
90
+ const i = {
91
+ data: t,
92
+ id: `${Date.now() + Math.random()}`,
93
+ retryCount: 0,
94
+ retryDelay: this.initialDelay
95
+ };
96
+ this.dataQueue.push(i), this.dispatchEvent(this.publishEvent);
97
+ }
98
+ consume() {
99
+ n.debug("Started Consumer Queue"), this.addEventListener("eventPublished", async () => {
100
+ for (; this.dataQueue.length > 0; ) {
101
+ const t = this.dataQueue.shift(), { data: i = {} } = t;
102
+ try {
103
+ await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
104
+ } catch (s) {
105
+ n.error("Failed to publish event:", s), this.scheduleRetry(t);
106
+ }
107
+ }
108
+ });
109
+ }
110
+ scheduleRetry(t) {
111
+ if (t.retryCount >= this.maxRetries) {
112
+ n.error("Max retries reached for message:", t);
113
+ return;
114
+ }
115
+ setTimeout(() => {
116
+ this.retryQueue.push({
117
+ ...t,
118
+ retryCount: t.retryCount + 1,
119
+ retryDelay: t.retryDelay * 2
120
+ }), this.dispatchEvent(this.retryEvent);
121
+ }, t.retryDelay);
122
+ }
123
+ acknowledge(t) {
124
+ this.dataQueue = this.dataQueue.filter((i) => i.id !== t);
125
+ }
126
+ retry() {
127
+ n.debug("Started Retry Queue"), this.addEventListener("retryMessage", async () => {
128
+ for (; this.retryQueue.length > 0; ) {
129
+ const t = this.retryQueue.shift(), { data: i = {} } = t;
130
+ try {
131
+ await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
132
+ } catch (s) {
133
+ n.error("Failed to publish event:", s), this.scheduleRetry(t);
134
+ }
135
+ }
136
+ });
137
+ }
138
+ }
139
+ class m {
140
+ static getBrowserInfo() {
141
+ var s, u, h, f, g;
142
+ const e = navigator.userAgent || "";
143
+ let t, i;
144
+ 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}`;
145
+ }
146
+ static getDeviceCategory() {
147
+ const e = navigator.userAgent;
148
+ return /mobile/i.test(e) ? "Mobile" : /tablet/i.test(e) ? "Tablet" : "Desktop";
149
+ }
150
+ static getDevicePlatform() {
151
+ const e = navigator.userAgent;
152
+ 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";
153
+ }
154
+ static getDeviceManufacturer() {
155
+ const e = navigator.userAgent;
156
+ let t;
157
+ 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;
158
+ }
159
+ static async getDeviceNetworkParameters() {
160
+ try {
161
+ const e = await fetch(`${c.API_URL}/api/geolocation`), { data: t } = await e.json();
162
+ return {
163
+ city: t.city || "Unknown",
164
+ region: t.region || "Unknown",
165
+ country: t.country || "Unknown",
166
+ timezone: t.timezone || "Unknown",
167
+ loc: t.loc || "Unknown",
168
+ ip_address: t.ip_address || "Unknown"
169
+ };
170
+ } catch (e) {
171
+ return n.error("Error retrieving device network parameters:", e), {
172
+ city: "Unknown",
173
+ region: "Unknown",
174
+ country: "Unknown",
175
+ timezone: "Unknown",
176
+ loc: "Unknown",
177
+ ip_address: "Unknown"
178
+ };
179
+ }
180
+ }
181
+ static async aquireAccessToken(e) {
182
+ try {
183
+ return (await (await fetch(`${c.API_URL}/api/authenticate`, {
184
+ method: "POST",
185
+ headers: {
186
+ "Content-Type": "application/json"
187
+ },
188
+ body: JSON.stringify({
189
+ accountId: e,
190
+ metadata: {
191
+ sdk: c.package,
192
+ version: c.version,
193
+ hostname: window.location.hostname
194
+ }
195
+ })
196
+ })).json()).accessToken;
197
+ } catch (t) {
198
+ throw n.error("Error acquiring access token:", t), new Error("[CPIX] Authentication error");
199
+ }
200
+ }
201
+ }
202
+ class d {
203
+ static isPresent(e) {
204
+ return typeof e < "u" && e !== null && e !== "";
205
+ }
206
+ static now() {
207
+ return 1 * (/* @__PURE__ */ new Date()).getTime();
208
+ }
209
+ static guid() {
210
+ return p.version + "-xxxxxxxx-".replace(/[x]/g, function(e) {
211
+ const t = Math.random() * 36 | 0;
212
+ return (e == "x" ? t : t & 3 | 8).toString(36);
213
+ }) + (1 * (/* @__PURE__ */ new Date()).getTime()).toString(36);
214
+ }
215
+ // reduces all optional data down to a string
216
+ static optionalData(e) {
217
+ return d.isPresent(e) === !1 ? "" : typeof e == "object" ? d.optionalData(JSON.stringify(e)) : typeof e == "function" ? d.optionalData(e()) : String(e);
218
+ }
219
+ static sleep(e) {
220
+ return new Promise((t) => setTimeout(t, e));
221
+ }
222
+ }
223
+ class w {
224
+ static getParameterByName(e, t) {
225
+ t || (t = window.location.href), e = e.replace(/[[\]]/g, "\\$&");
226
+ const s = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)", "i").exec(t);
227
+ return s ? s[2] ? decodeURIComponent(s[2].replace(/\+/g, " ")) : "" : null;
228
+ }
229
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
230
+ static externalHost(e) {
231
+ var t;
232
+ return e.hostname != location.hostname && ((t = e == null ? void 0 : e.protocol) == null ? void 0 : t.indexOf("http")) === 0;
233
+ }
234
+ }
235
+ class r {
236
+ static prefix() {
237
+ return `__${c.TRACKER_FUNC_NAME}__`;
238
+ }
239
+ static get(e) {
240
+ const t = `${r.prefix()}${e}`, i = document.cookie.split("; ").find((s) => s.startsWith(`${t}=`));
241
+ return i ? i.split("=")[1] : void 0;
242
+ }
243
+ static set(e, t, i) {
244
+ const s = `${r.prefix()}${e}`, u = /* @__PURE__ */ new Date();
245
+ u.setTime(u.getTime() + i * 60 * 1e3), document.cookie = `${s}=${t}; expires=${u.toUTCString()}; path=/`;
246
+ }
247
+ static delete(e) {
248
+ const t = `${r.prefix()}${e}`;
249
+ document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
250
+ }
251
+ static clear() {
252
+ document.cookie.split("; ").filter((e) => e.startsWith(r.prefix())).forEach((e) => {
253
+ const t = e.split("=")[0];
254
+ document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
255
+ });
256
+ }
257
+ static exists(e) {
258
+ return !!r.get(e);
259
+ }
260
+ static setUtms() {
261
+ const e = I;
262
+ let t = !1;
263
+ for (let i = 0; i < e.length; i++) {
264
+ const s = e[i];
265
+ if (d.isPresent(w.getParameterByName(s, window.location.href))) {
266
+ t = !0;
267
+ break;
268
+ }
269
+ }
270
+ if (t) {
271
+ let i = "";
272
+ const s = {};
273
+ for (let u = 0; u < e.length; u++) {
274
+ const h = e[u];
275
+ i = w.getParameterByName(h, window.location.href), d.isPresent(i) && (s[h] = i), s[h] = i;
276
+ }
277
+ r.set(l.UTM, JSON.stringify(s), 30);
278
+ }
279
+ }
280
+ static getUtms() {
281
+ const e = r.get(l.UTM);
282
+ return d.isPresent(e) ? JSON.parse(e) : {};
283
+ }
284
+ static createSession() {
285
+ r.exists(l.SESSION) || r.set(l.SESSION, d.guid(), 30 * 24 * 60), r.setUtms();
286
+ }
287
+ }
288
+ class N {
289
+ constructor() {
290
+ a(this, "instances", []);
291
+ a(this, "initialized", !1);
292
+ a(this, "accessToken", "");
293
+ a(this, "metaParameters", {});
294
+ a(this, "queue");
295
+ if (!window)
296
+ throw new Error(
297
+ "[CPIX] CarterAnalytics SDK can only be used in a browser environment"
298
+ );
299
+ this.queue = new k({
300
+ maxRetries: c.QUEUE_MAX_RETRIES,
301
+ initialDelay: c.QUEUE_INITIAL_DELAY,
302
+ consumerHandler: this.publishEventToServer
303
+ });
304
+ }
305
+ /**
306
+ * Initializes the CarterAnalytics SDK with the provided configuration options.
307
+ * @param options - The configuration options for initializing the SDK.
308
+ */
309
+ async initialize(e) {
310
+ if (!e || e.length === 0)
311
+ throw new Error(
312
+ "[CPIX] At least one instance configuration is required for initialization"
313
+ );
314
+ if (r.exists(l.SESSION) || r.createSession(), r.exists(l.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
315
+ r.set("metaParameters", JSON.stringify(t), 60 * 24);
316
+ }), this.metaParameters = JSON.parse(r.get("metaParameters")), this.initialized)
317
+ throw new Error(
318
+ "[CPIX] CarterAnalytics SDK has already been initialized"
319
+ );
320
+ if (!this.metaParameters)
321
+ throw new Error("[CPIX] Meta parameters have not been generated");
322
+ this.instances = e, r.exists(l.ACCESS_TOKEN) || (this.accessToken = await m.aquireAccessToken(
323
+ this.instances[0].client_id
324
+ ), r.set(l.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, n.info("CPIX Initialized"), n.debug(
325
+ "Carter Analytics SDK initialized with options:",
326
+ this.instances
327
+ ), 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({
328
+ event: "init",
329
+ ...this.metaParameters
330
+ }), this.publish({
331
+ event: "page_view",
332
+ event_properties: {
333
+ title: document.title,
334
+ page: window.location.pathname,
335
+ url: window.location.href
336
+ },
337
+ ...this.metaParameters
338
+ });
339
+ }
340
+ /**
341
+ * Publishes an event to the analytics queue.
342
+ * @param event - The event to be published.
343
+ */
344
+ publish(e) {
345
+ if (!this.initialized)
346
+ throw new Error(
347
+ "[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events."
348
+ );
349
+ const t = {
350
+ ...e,
351
+ ...this.metaParameters
352
+ };
353
+ n.debug("Publishing event:", t), this.queue.publish(t);
354
+ }
355
+ /**
356
+ * Generates meta parameters that is attached to every event before publishing.
357
+ */
358
+ async generateMetaParameters() {
359
+ if (!window)
360
+ throw new Error(
361
+ "[CPIX] Meta parameters can only be generated in a browser environment"
362
+ );
363
+ const e = await m.getDeviceNetworkParameters();
364
+ return {
365
+ session: r.get(l.SESSION),
366
+ location: {
367
+ city: e.city,
368
+ region: e.region,
369
+ loc: e.loc,
370
+ timezone: e.timezone,
371
+ country: e.country
372
+ },
373
+ device: {
374
+ category: m.getDeviceCategory(),
375
+ brand: m.getDeviceManufacturer(),
376
+ ip_address: e.ip_address,
377
+ platform: m.getDevicePlatform()
378
+ },
379
+ referrer: document.referrer,
380
+ utm_params: r.getUtms()
381
+ };
382
+ }
383
+ /**
384
+ * Publishes an event to the analytics server.
385
+ * @param message - The event to be published.
386
+ */
387
+ async publishEventToServer(e) {
388
+ try {
389
+ e.timestamp = Date.now();
390
+ const t = await fetch(`${c.API_URL}/api/event`, {
391
+ method: "POST",
392
+ body: JSON.stringify({ event_data: e }),
393
+ headers: {
394
+ "Content-Type": "application/json",
395
+ Authorization: `Bearer ${r.get(l.ACCESS_TOKEN)}`
396
+ }
397
+ });
398
+ if (!t.ok)
399
+ throw new Error("[CPIX] Failed to publish event");
400
+ const i = await t.json();
401
+ n.debug("Event published:", i);
402
+ } catch (t) {
403
+ throw n.error("Failed to publish event:", t), new Error("[CPIX] Failed to publish event");
404
+ }
405
+ }
406
+ }
407
+ const R = new N();
408
+ typeof window < "u" && (window.cpix = R);
409
+ export {
410
+ R as CarterAnalytics
411
+ };
@@ -0,0 +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-analytics/cpix",private:!0,version:"0.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:"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"],s=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=>(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(r){s.error("Failed to publish event:",r),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(r){s.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}}class f{static getBrowserInfo(){var r,d,m,E,x;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=(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 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(`${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 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 r=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class n{static prefix(){return`__${u.TRACKER_FUNC_NAME}__`}static get(e){const t=`${n.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=`${n.prefix()}${e}`,d=new Date;d.setTime(d.getTime()+i*60*1e3),document.cookie=`${r}=${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 r=e[i];if(h.isPresent(y.getParameterByName(r,window.location.href))){t=!0;break}}if(t){let i="";const r={};for(let d=0;d<e.length;d++){const m=e[d];i=y.getParameterByName(m,window.location.href),h.isPresent(i)&&(r[m]=i),r[m]=i}n.set(l.UTM,JSON.stringify(r),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,s.info("CPIX Initialized"),s.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};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: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();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;typeof window<"u"&&(window.cpix=v),o.CarterAnalytics=v,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/dist/logo.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/dist/main.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { default as CarterAnalytics } from './modules/carter-analytics';
@@ -0,0 +1,34 @@
1
+ import { Event, Init } from '../types/common.types';
2
+
3
+ /**
4
+ * The `CarterAnalytics` class is responsible for initializing and publishing events to the analytics server.
5
+ */
6
+ declare class CarterAnalytics {
7
+ private instances;
8
+ private initialized;
9
+ private accessToken;
10
+ private metaParameters;
11
+ private queue;
12
+ constructor();
13
+ /**
14
+ * Initializes the CarterAnalytics SDK with the provided configuration options.
15
+ * @param options - The configuration options for initializing the SDK.
16
+ */
17
+ initialize(options: Init[]): Promise<void>;
18
+ /**
19
+ * Publishes an event to the analytics queue.
20
+ * @param event - The event to be published.
21
+ */
22
+ publish(event: Event): void;
23
+ /**
24
+ * Generates meta parameters that is attached to every event before publishing.
25
+ */
26
+ private generateMetaParameters;
27
+ /**
28
+ * Publishes an event to the analytics server.
29
+ * @param message - The event to be published.
30
+ */
31
+ private publishEventToServer;
32
+ }
33
+ declare const analytics: CarterAnalytics;
34
+ export default analytics;
@@ -0,0 +1,152 @@
1
+ import * as commonType from './common.types';
2
+ /**
3
+ * Represents the properties required to start a checkout.
4
+ */
5
+ export interface CheckoutStartProperties {
6
+ /**
7
+ * The token associated with the checkout.
8
+ */
9
+ token: string;
10
+ /**
11
+ * The total amount of the checkout.
12
+ */
13
+ amount: number;
14
+ /**
15
+ * The tax amount of the checkout.
16
+ */
17
+ tax: number;
18
+ /**
19
+ * The currency of the checkout.
20
+ */
21
+ currency: string;
22
+ /**
23
+ * The items in the checkout.
24
+ */
25
+ items: Array<commonType.CartProperties>;
26
+ /**
27
+ * The billing addresses associated with the checkout.
28
+ */
29
+ billing_address: Array<commonType.AddressProperties>;
30
+ /**
31
+ * The shipping addresses associated with the checkout.
32
+ */
33
+ shipping_address: Array<commonType.AddressProperties>;
34
+ /**
35
+ * The discounts applied to the checkout.
36
+ */
37
+ discount: Array<commonType.DiscountProperties>;
38
+ /**
39
+ * The delivery method of the checkout.
40
+ */
41
+ delivery_method: string;
42
+ /**
43
+ * The payment method of the checkout.
44
+ */
45
+ payment_method: string;
46
+ }
47
+ /**
48
+ * Represents the properties of a completed checkout.
49
+ */
50
+ export interface CheckoutCompletedProperties {
51
+ /**
52
+ * The token associated with the checkout.
53
+ */
54
+ token: string;
55
+ /**
56
+ * The order ID of the completed checkout.
57
+ */
58
+ order_id: string;
59
+ /**
60
+ * The total amount of the completed checkout.
61
+ */
62
+ amount: number;
63
+ /**
64
+ * The tax amount of the completed checkout.
65
+ */
66
+ tax: number;
67
+ /**
68
+ * The currency of the completed checkout.
69
+ */
70
+ currency: string;
71
+ /**
72
+ * The items in the completed checkout.
73
+ */
74
+ items: Array<commonType.CartProperties>;
75
+ /**
76
+ * The billing addresses associated with the completed checkout.
77
+ */
78
+ billing_address: Array<commonType.AddressProperties>;
79
+ /**
80
+ * The shipping addresses associated with the completed checkout.
81
+ */
82
+ shipping_address: Array<commonType.AddressProperties>;
83
+ /**
84
+ * The discounts applied to the completed checkout.
85
+ */
86
+ discount: Array<commonType.DiscountProperties>;
87
+ /**
88
+ * The delivery method of the completed checkout.
89
+ */
90
+ delivery_method: string;
91
+ /**
92
+ * The payment method of the completed checkout.
93
+ */
94
+ payment_method: string;
95
+ /**
96
+ * The transaction ID of the completed checkout.
97
+ */
98
+ transaction_id: string;
99
+ }
100
+ /**
101
+ * Represents the properties of a cancelled checkout.
102
+ */
103
+ export interface CheckoutCancelledProperties {
104
+ /**
105
+ * The token associated with the checkout.
106
+ */
107
+ token: string;
108
+ /**
109
+ * The total amount of the cancelled checkout.
110
+ */
111
+ amount: number;
112
+ /**
113
+ * The tax amount of the cancelled checkout.
114
+ */
115
+ tax: number;
116
+ /**
117
+ * The currency of the cancelled checkout.
118
+ */
119
+ currency: string;
120
+ /**
121
+ * The items in the cancelled checkout.
122
+ */
123
+ items: Array<commonType.CartProperties>;
124
+ /**
125
+ * The billing addresses associated with the cancelled checkout.
126
+ */
127
+ billing_address: Array<commonType.AddressProperties>;
128
+ /**
129
+ * The shipping addresses associated with the cancelled checkout.
130
+ */
131
+ shipping_address: Array<commonType.AddressProperties>;
132
+ /**
133
+ * The discounts applied to the cancelled checkout.
134
+ */
135
+ discount: Array<commonType.DiscountProperties>;
136
+ /**
137
+ * The delivery method of the cancelled checkout.
138
+ */
139
+ delivery_method: string;
140
+ /**
141
+ * The payment method of the cancelled checkout.
142
+ */
143
+ payment_method: string;
144
+ /**
145
+ * The transaction ID of the cancelled checkout.
146
+ */
147
+ transaction_id: string;
148
+ /**
149
+ * The reason for the cancellation of the checkout.
150
+ */
151
+ reason: string;
152
+ }