aurea-tracking-sdk 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/index.ts
20
20
  var index_exports = {};
21
21
  __export(index_exports, {
22
+ AureaSDK: () => AureaSDK,
22
23
  getAurea: () => getAurea,
23
24
  identifyUser: () => identifyUser,
24
25
  initAurea: () => initAurea,
@@ -45,6 +46,13 @@ var AureaSDK = class {
45
46
  fcp: false,
46
47
  ttfb: false
47
48
  };
49
+ // NEW: Funnel tracking
50
+ this.currentStage = "awareness";
51
+ this.stageHistory = [];
52
+ this.microConversions = [];
53
+ this.isInCheckout = false;
54
+ // NEW: Event categorization tracking
55
+ this.eventCategoryStats = /* @__PURE__ */ new Map();
48
56
  this.config = {
49
57
  apiUrl: "http://localhost:3000/api",
50
58
  debug: false,
@@ -98,11 +106,13 @@ var AureaSDK = class {
98
106
  this.startPurchasePolling();
99
107
  this.trackWebVitals();
100
108
  this.trackSessionTiming();
109
+ this.initializeFunnelTracking();
101
110
  if (this.config.debug) {
102
111
  console.log("[Aurea SDK] Initialized", {
103
112
  sessionId: this.sessionId,
104
113
  anonymousId: this.anonymousId,
105
- userId: this.userId
114
+ userId: this.userId,
115
+ currentStage: this.currentStage
106
116
  });
107
117
  }
108
118
  }
@@ -180,6 +190,360 @@ var AureaSDK = class {
180
190
  console.log("[Aurea SDK] Conversion tracked:", data);
181
191
  }
182
192
  }
193
+ /**
194
+ * Register custom event categories
195
+ * Allows users to define their own event categorization and auto-stage progression
196
+ *
197
+ * @example
198
+ * aurea.registerEventCategories({
199
+ * 'video_started': {
200
+ * category: 'engagement',
201
+ * advanceTo: 'interest',
202
+ * value: 30,
203
+ * description: 'User started watching sales video'
204
+ * },
205
+ * 'pricing_viewed': {
206
+ * category: 'intent',
207
+ * advanceTo: 'desire',
208
+ * value: 60
209
+ * },
210
+ * 'buy_button_clicked': {
211
+ * category: 'conversion',
212
+ * value: 90
213
+ * }
214
+ * })
215
+ */
216
+ registerEventCategories(categories) {
217
+ if (!this.config.eventCategories) {
218
+ this.config.eventCategories = {};
219
+ }
220
+ this.config.eventCategories = {
221
+ ...this.config.eventCategories,
222
+ ...categories
223
+ };
224
+ if (this.config.debug) {
225
+ console.log("[Aurea SDK] Event categories registered:", categories);
226
+ }
227
+ }
228
+ /**
229
+ * Track a categorized event with automatic stage progression
230
+ * This is the recommended way to track events - user defines their own event names
231
+ *
232
+ * @param eventName - User-defined event name (e.g., 'video_started', 'pricing_clicked')
233
+ * @param properties - Additional event properties
234
+ * @param options - Override category/value/stage for this specific event
235
+ *
236
+ * @example
237
+ * // Using pre-registered category
238
+ * aurea.trackEvent('video_started', { duration: 120 })
239
+ *
240
+ * // One-off event with inline category
241
+ * aurea.trackEvent('custom_action', { foo: 'bar' }, {
242
+ * category: 'engagement',
243
+ * value: 40,
244
+ * advanceTo: 'interest'
245
+ * })
246
+ */
247
+ trackEvent(eventName, properties, options) {
248
+ const categoryConfig = this.config.eventCategories?.[eventName];
249
+ const category = options?.category || categoryConfig?.category || "custom";
250
+ const value = options?.value ?? categoryConfig?.value ?? 50;
251
+ const advanceTo = options?.advanceTo || categoryConfig?.advanceTo;
252
+ const description = options?.description || categoryConfig?.description;
253
+ this.eventCategoryStats.set(
254
+ category,
255
+ (this.eventCategoryStats.get(category) || 0) + 1
256
+ );
257
+ const autoAdvance = this.config.autoAdvanceStages !== false;
258
+ if (autoAdvance && advanceTo && advanceTo !== this.currentStage) {
259
+ this.enterStage(advanceTo);
260
+ }
261
+ this.track(eventName, {
262
+ ...properties,
263
+ // Add categorization metadata
264
+ _category: category,
265
+ _value: value,
266
+ _description: description,
267
+ _currentStage: this.currentStage,
268
+ _categoryStats: Object.fromEntries(this.eventCategoryStats)
269
+ });
270
+ if (this.config.debug) {
271
+ console.log(`[Aurea SDK] Event tracked: ${eventName} [${category}] (value: ${value}, stage: ${this.currentStage})`);
272
+ }
273
+ }
274
+ /**
275
+ * Get current event category statistics
276
+ */
277
+ getCategoryStats() {
278
+ return Object.fromEntries(this.eventCategoryStats);
279
+ }
280
+ /**
281
+ * Get current funnel stage
282
+ */
283
+ getCurrentStage() {
284
+ return this.currentStage;
285
+ }
286
+ /**
287
+ * Get stage history
288
+ */
289
+ getStageHistory() {
290
+ return this.stageHistory.map((entry, index) => {
291
+ const nextEntry = this.stageHistory[index + 1];
292
+ const durationMs = nextEntry ? nextEntry.enteredAt - entry.enteredAt : Date.now() - entry.enteredAt;
293
+ return {
294
+ stage: entry.stage,
295
+ enteredAt: entry.enteredAt,
296
+ durationMs
297
+ };
298
+ });
299
+ }
300
+ /**
301
+ * Enter a new funnel stage
302
+ */
303
+ enterStage(stage) {
304
+ const previousStage = this.currentStage;
305
+ this.currentStage = stage;
306
+ this.stageHistory.push({
307
+ stage,
308
+ enteredAt: Date.now()
309
+ });
310
+ this.track("funnel_stage_entered", {
311
+ stage,
312
+ previousStage,
313
+ stageHistory: this.stageHistory,
314
+ timeInPreviousStage: this.getTimeInCurrentStage(previousStage)
315
+ });
316
+ if (this.config.debug) {
317
+ console.log(`[Aurea SDK] Entered funnel stage: ${previousStage} \u2192 ${stage}`);
318
+ }
319
+ }
320
+ /**
321
+ * Track micro-conversion (engagement signals)
322
+ *
323
+ * @deprecated Use trackEvent() instead for more flexibility
324
+ * This method is kept for backward compatibility
325
+ *
326
+ * @param type - Type of micro-conversion (e.g., 'video_played', 'faq_opened')
327
+ * @param value - Impact score 0-100 (how strong this signal is)
328
+ * @param properties - Additional metadata
329
+ * @param autoAdvanceStage - Whether to automatically advance funnel stage (default: true)
330
+ */
331
+ trackMicroConversion(type, value = 50, properties, autoAdvanceStage = true) {
332
+ const microConversion = {
333
+ type,
334
+ value,
335
+ properties
336
+ };
337
+ this.microConversions.push(microConversion);
338
+ const categoryConfig = this.config.eventCategories?.[type];
339
+ if (autoAdvanceStage) {
340
+ if (categoryConfig?.advanceTo && categoryConfig.advanceTo !== this.currentStage) {
341
+ this.enterStage(categoryConfig.advanceTo);
342
+ } else {
343
+ const suggestedStage = this.getSuggestedStageFromMicroConversion(type, value);
344
+ if (suggestedStage && suggestedStage !== this.currentStage) {
345
+ this.enterStage(suggestedStage);
346
+ }
347
+ }
348
+ }
349
+ this.track("micro_conversion", {
350
+ microConversionType: type,
351
+ value,
352
+ category: categoryConfig?.category || "custom",
353
+ currentStage: this.currentStage,
354
+ totalMicroConversions: this.microConversions.length,
355
+ ...properties
356
+ });
357
+ if (this.config.debug) {
358
+ console.log(`[Aurea SDK] Micro-conversion: ${type} (value: ${value}, stage: ${this.currentStage})`);
359
+ }
360
+ }
361
+ /**
362
+ * Determine suggested funnel stage based on micro-conversion type
363
+ * This uses common patterns to automatically progress users through the funnel
364
+ */
365
+ getSuggestedStageFromMicroConversion(type, value) {
366
+ const currentStageIndex = this.getFunnelStageOrder().indexOf(this.currentStage);
367
+ const interestSignals = [
368
+ "video_played",
369
+ "video_started",
370
+ "video_25_percent",
371
+ "video_50_percent",
372
+ "scroll_depth_25",
373
+ "scroll_depth_50",
374
+ "page_section_viewed",
375
+ "testimonial_viewed",
376
+ "feature_section_viewed"
377
+ ];
378
+ const desireSignals = [
379
+ "video_75_percent",
380
+ "video_completed",
381
+ "faq_opened",
382
+ "pricing_viewed",
383
+ "cta_section_viewed",
384
+ "scroll_depth_75",
385
+ "comparison_table_viewed",
386
+ "guarantee_section_viewed",
387
+ "bonus_section_viewed"
388
+ ];
389
+ const checkoutIntentSignals = [
390
+ "buy_button_hovered",
391
+ "checkout_button_clicked",
392
+ "add_to_cart",
393
+ "pricing_tier_selected"
394
+ ];
395
+ if (interestSignals.includes(type) && currentStageIndex < 1) {
396
+ return "interest";
397
+ }
398
+ if (desireSignals.includes(type) && currentStageIndex < 2) {
399
+ return "desire";
400
+ }
401
+ if (checkoutIntentSignals.includes(type) && currentStageIndex < 3) {
402
+ if (this.config.debug) {
403
+ console.log(`[Aurea SDK] High checkout intent detected: ${type}`);
404
+ }
405
+ }
406
+ if (value >= 80 && currentStageIndex < 2) {
407
+ return "desire";
408
+ }
409
+ return null;
410
+ }
411
+ /**
412
+ * Get funnel stage order for comparison
413
+ */
414
+ getFunnelStageOrder() {
415
+ return ["awareness", "interest", "desire", "checkout", "purchase", "abandoned"];
416
+ }
417
+ /**
418
+ * Track checkout started (user clicked buy button)
419
+ * This DOES NOT end the session - preserves context for when user returns
420
+ */
421
+ checkoutStarted(product) {
422
+ this.isInCheckout = true;
423
+ this.checkoutStartedAt = Date.now();
424
+ this.enterStage("checkout");
425
+ const checkoutContext = {
426
+ originalSessionId: this.sessionId,
427
+ anonymousId: this.anonymousId,
428
+ checkoutStartedAt: this.checkoutStartedAt,
429
+ product,
430
+ currentStage: this.currentStage,
431
+ priorStages: this.stageHistory.map((h) => h.stage),
432
+ utmSource: this.getUTMParam("utm_source"),
433
+ utmCampaign: this.getUTMParam("utm_campaign"),
434
+ utmMedium: this.getUTMParam("utm_medium")
435
+ };
436
+ if (typeof localStorage !== "undefined") {
437
+ localStorage.setItem("aurea_checkout_context", JSON.stringify(checkoutContext));
438
+ }
439
+ this.track("checkout_started", {
440
+ productId: product.productId,
441
+ productName: product.productName,
442
+ price: product.price,
443
+ currency: product.currency || "USD",
444
+ quantity: product.quantity || 1,
445
+ variant: product.variant,
446
+ sessionDurationSoFar: Math.floor((Date.now() - this.sessionStartTime) / 1e3),
447
+ microConversionsCount: this.microConversions.length,
448
+ priorStages: this.stageHistory.map((h) => h.stage)
449
+ });
450
+ if (this.config.debug) {
451
+ console.log("[Aurea SDK] Checkout started:", product);
452
+ console.log("[Aurea SDK] Session context preserved for return journey");
453
+ }
454
+ }
455
+ /**
456
+ * Track checkout completed (purchase successful)
457
+ * Links back to original session if user returned from external checkout
458
+ */
459
+ checkoutCompleted(data) {
460
+ let checkoutContext = null;
461
+ let checkoutDuration;
462
+ if (typeof localStorage !== "undefined") {
463
+ const stored = localStorage.getItem("aurea_checkout_context");
464
+ if (stored) {
465
+ try {
466
+ checkoutContext = JSON.parse(stored);
467
+ checkoutDuration = Math.floor((Date.now() - checkoutContext.checkoutStartedAt) / 1e3);
468
+ localStorage.removeItem("aurea_checkout_context");
469
+ } catch (e) {
470
+ console.error("[Aurea SDK] Failed to parse checkout context:", e);
471
+ }
472
+ }
473
+ }
474
+ this.enterStage("purchase");
475
+ this.track("checkout_completed", {
476
+ orderId: data.orderId,
477
+ revenue: data.revenue,
478
+ currency: data.currency || "USD",
479
+ paymentMethod: data.paymentMethod,
480
+ products: data.products,
481
+ // Link to original session if available
482
+ originalSessionId: checkoutContext?.originalSessionId,
483
+ checkoutDuration,
484
+ totalSessionDuration: Math.floor((Date.now() - this.sessionStartTime) / 1e3),
485
+ // Attribution data from original session
486
+ originalUtmSource: checkoutContext?.utmSource,
487
+ originalUtmCampaign: checkoutContext?.utmCampaign,
488
+ originalUtmMedium: checkoutContext?.utmMedium,
489
+ priorStages: checkoutContext?.priorStages || this.stageHistory.map((h) => h.stage),
490
+ // Engagement data
491
+ microConversionsCount: this.microConversions.length,
492
+ microConversions: this.microConversions
493
+ });
494
+ this.conversion({
495
+ type: "purchase",
496
+ revenue: data.revenue,
497
+ currency: data.currency,
498
+ orderId: data.orderId
499
+ });
500
+ if (this.config.debug) {
501
+ console.log("[Aurea SDK] Checkout completed:", data);
502
+ if (checkoutContext) {
503
+ console.log("[Aurea SDK] Session bridged - linked to original session:", checkoutContext.originalSessionId);
504
+ }
505
+ }
506
+ }
507
+ /**
508
+ * Track checkout abandoned (user left without completing)
509
+ */
510
+ checkoutAbandoned(reason) {
511
+ if (!this.isInCheckout) {
512
+ return;
513
+ }
514
+ const checkoutDuration = this.checkoutStartedAt ? Math.floor((Date.now() - this.checkoutStartedAt) / 1e3) : void 0;
515
+ this.enterStage("abandoned");
516
+ this.track("checkout_abandoned", {
517
+ reason: reason || "unknown",
518
+ checkoutDuration,
519
+ sessionDuration: Math.floor((Date.now() - this.sessionStartTime) / 1e3),
520
+ microConversionsCount: this.microConversions.length,
521
+ priorStages: this.stageHistory.map((h) => h.stage)
522
+ });
523
+ this.isInCheckout = false;
524
+ if (this.config.debug) {
525
+ console.log("[Aurea SDK] Checkout abandoned:", reason);
526
+ }
527
+ }
528
+ /**
529
+ * Get time spent in a specific stage (in seconds)
530
+ */
531
+ getTimeInCurrentStage(stage) {
532
+ const stageEntries = this.stageHistory.filter((h) => h.stage === stage);
533
+ if (stageEntries.length === 0) return 0;
534
+ const lastEntry = stageEntries[stageEntries.length - 1];
535
+ const nextEntry = this.stageHistory.find((h) => h.enteredAt > lastEntry.enteredAt);
536
+ const endTime = nextEntry ? nextEntry.enteredAt : Date.now();
537
+ return Math.floor((endTime - lastEntry.enteredAt) / 1e3);
538
+ }
539
+ /**
540
+ * Get UTM parameter from current URL
541
+ */
542
+ getUTMParam(param) {
543
+ if (typeof window === "undefined") return void 0;
544
+ const urlParams = new URLSearchParams(window.location.search);
545
+ return urlParams.get(param) || void 0;
546
+ }
183
547
  /**
184
548
  * Get or create session ID
185
549
  */
@@ -581,6 +945,9 @@ var AureaSDK = class {
581
945
  window.addEventListener("touchstart", resetInactivityTimer, { passive: true });
582
946
  window.addEventListener("beforeunload", () => {
583
947
  const now = Date.now();
948
+ if (this.isInCheckout && this.currentStage === "checkout") {
949
+ this.checkoutAbandoned("page_close");
950
+ }
584
951
  if (this.isPageVisible) {
585
952
  this.activeTime += now - this.lastActiveTimestamp;
586
953
  }
@@ -627,6 +994,53 @@ var AureaSDK = class {
627
994
  console.log("[Aurea SDK] Session timing tracking enabled");
628
995
  }
629
996
  }
997
+ /**
998
+ * Initialize funnel tracking
999
+ * Checks for returning checkout users and sets initial stage
1000
+ */
1001
+ initializeFunnelTracking() {
1002
+ if (typeof window === "undefined") return;
1003
+ if (typeof localStorage !== "undefined") {
1004
+ const checkoutContext = localStorage.getItem("aurea_checkout_context");
1005
+ if (checkoutContext) {
1006
+ try {
1007
+ const context = JSON.parse(checkoutContext);
1008
+ const urlParams = new URLSearchParams(window.location.search);
1009
+ const purchased = urlParams.get("purchased") === "true";
1010
+ if (purchased) {
1011
+ if (this.config.debug) {
1012
+ console.log(
1013
+ "[Aurea SDK] Returning from successful checkout - awaiting checkoutCompleted() call"
1014
+ );
1015
+ }
1016
+ } else {
1017
+ const timeSinceCheckout = Date.now() - context.checkoutStartedAt;
1018
+ const fifteenMinutes = 15 * 60 * 1e3;
1019
+ if (timeSinceCheckout > fifteenMinutes) {
1020
+ if (this.config.debug) {
1021
+ console.log(
1022
+ "[Aurea SDK] Checkout abandoned (15+ min elapsed)"
1023
+ );
1024
+ }
1025
+ }
1026
+ }
1027
+ } catch (err) {
1028
+ console.error(
1029
+ "[Aurea SDK] Failed to parse checkout context:",
1030
+ err
1031
+ );
1032
+ localStorage.removeItem("aurea_checkout_context");
1033
+ }
1034
+ }
1035
+ }
1036
+ this.stageHistory.push({
1037
+ stage: "awareness",
1038
+ enteredAt: Date.now()
1039
+ });
1040
+ if (this.config.debug) {
1041
+ console.log("[Aurea SDK] Funnel tracking initialized - Stage: awareness");
1042
+ }
1043
+ }
630
1044
  /**
631
1045
  * Generate unique ID
632
1046
  */
@@ -690,6 +1104,7 @@ function trackPage(name, properties) {
690
1104
  }
691
1105
  // Annotate the CommonJS export names for ESM import in node:
692
1106
  0 && (module.exports = {
1107
+ AureaSDK,
693
1108
  getAurea,
694
1109
  identifyUser,
695
1110
  initAurea,