@vulcantech/analytics 0.1.2 → 0.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/src/tracker.ts CHANGED
@@ -32,7 +32,68 @@ function getSessionId(): string {
32
32
  }
33
33
  }
34
34
 
35
- /** Extract UTM params from the current URL. */
35
+ /**
36
+ * Ad-referral cookie written by `@vulcantech/forms`' `AdReferralTracker`.
37
+ *
38
+ * Read by NAME rather than by importing that package: this tracker's whole
39
+ * selling point is that it pulls in nothing, and importing the forms entry
40
+ * point would drag formik, yup and Radix into every page. The cookie name and
41
+ * its JSON shape are the contract — keep them in step with
42
+ * `packages/forms/src/tracking/adReferral.ts`.
43
+ */
44
+ const AD_REFERRAL_COOKIE = "vt_ad_ref";
45
+
46
+ /**
47
+ * Campaign context for the visit, as UTM keys, or null when this visitor
48
+ * never arrived on a tagged ad click (or the site mounts no AdReferralTracker).
49
+ *
50
+ * `source`/`medium` drive the CMS source classification; `campaign` feeds its
51
+ * per-campaign conversion rollup. The cookie's `"(not set)"` placeholder (an
52
+ * auto-tagged click with no utm_campaign) is dropped so the CMS can name it
53
+ * itself. Term, content, click id and landing data stay in the cookie — the
54
+ * lead carries those.
55
+ */
56
+ function getAdReferralUtm(): Record<string, string> | null {
57
+ if (typeof document === "undefined") return null;
58
+ for (const cookie of document.cookie.split(";")) {
59
+ const sep = cookie.indexOf("=");
60
+ if (sep === -1) continue;
61
+ if (cookie.slice(0, sep).trim() !== AD_REFERRAL_COOKIE) continue;
62
+ try {
63
+ const parsed = JSON.parse(decodeURIComponent(cookie.slice(sep + 1)));
64
+ if (!parsed || typeof parsed !== "object") return null;
65
+ const utm: Record<string, string> = {};
66
+ if (typeof parsed.source === "string" && parsed.source) {
67
+ utm.utm_source = parsed.source;
68
+ }
69
+ if (typeof parsed.medium === "string" && parsed.medium) {
70
+ utm.utm_medium = parsed.medium;
71
+ }
72
+ if (
73
+ Object.keys(utm).length > 0 &&
74
+ typeof parsed.campaign === "string" &&
75
+ parsed.campaign &&
76
+ parsed.campaign !== "(not set)"
77
+ ) {
78
+ utm.utm_campaign = parsed.campaign;
79
+ }
80
+ return Object.keys(utm).length > 0 ? utm : null;
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Extract campaign params from the current URL.
90
+ *
91
+ * Click ids are read alongside the UTMs because Google Ads auto-tagging is on
92
+ * by default and adds NO utm_* params — without them an auto-tagged pageview
93
+ * would carry no structured campaign data at all, and the CMS would classify
94
+ * it by its google.com referrer as organic. `gad_source`/`gad_campaignid` are
95
+ * read too: Safari's tracking protection strips `gclid` but leaves them.
96
+ */
36
97
  function getUtmParams(): Record<string, string> {
37
98
  if (typeof window === "undefined") return {};
38
99
  const params = new URLSearchParams(window.location.search);
@@ -43,6 +104,13 @@ function getUtmParams(): Record<string, string> {
43
104
  "utm_campaign",
44
105
  "utm_term",
45
106
  "utm_content",
107
+ "gclid",
108
+ "gbraid",
109
+ "wbraid",
110
+ "gad_source",
111
+ "gad_campaignid",
112
+ "fbclid",
113
+ "msclkid",
46
114
  ]) {
47
115
  const val = params.get(key);
48
116
  if (val) utms[key] = val;
@@ -50,6 +118,58 @@ function getUtmParams(): Record<string, string> {
50
118
  return utms;
51
119
  }
52
120
 
121
+ const SESSION_CAMPAIGN_KEY = "__vt_utm";
122
+
123
+ /** A session's campaign goes stale after this long with no pageview (GA's default). */
124
+ const SESSION_CAMPAIGN_IDLE_MS = 30 * 60 * 1000;
125
+
126
+ /**
127
+ * The campaign params this tab session landed with, or null.
128
+ *
129
+ * Only the LANDING URL carries `gclid`/`utm_*`; the next page's URL is clean
130
+ * while `document.referrer` still says google.com, so without this every
131
+ * pageview after an ad landing classified as organic search. Kept in
132
+ * `sessionStorage` (no cookies, gone with the tab) and dropped after 30
133
+ * minutes idle, so a later organic return in the same tab isn't credited to
134
+ * the ad. Never throws.
135
+ */
136
+ function getSessionCampaign(): Record<string, string> | null {
137
+ try {
138
+ const raw = sessionStorage.getItem(SESSION_CAMPAIGN_KEY);
139
+ if (!raw) return null;
140
+ const parsed = JSON.parse(raw);
141
+ if (
142
+ !parsed ||
143
+ typeof parsed.at !== "number" ||
144
+ Date.now() - parsed.at > SESSION_CAMPAIGN_IDLE_MS ||
145
+ !parsed.utm ||
146
+ typeof parsed.utm !== "object"
147
+ ) {
148
+ sessionStorage.removeItem(SESSION_CAMPAIGN_KEY);
149
+ return null;
150
+ }
151
+ const utm: Record<string, string> = {};
152
+ for (const [k, v] of Object.entries(parsed.utm)) {
153
+ if (typeof v === "string" && v) utm[k] = v;
154
+ }
155
+ return Object.keys(utm).length > 0 ? utm : null;
156
+ } catch {
157
+ return null;
158
+ }
159
+ }
160
+
161
+ /** Store (or refresh the idle clock on) this session's campaign. Never throws. */
162
+ function setSessionCampaign(utm: Record<string, string>): void {
163
+ try {
164
+ sessionStorage.setItem(
165
+ SESSION_CAMPAIGN_KEY,
166
+ JSON.stringify({ utm, at: Date.now() }),
167
+ );
168
+ } catch {
169
+ // Storage blocked — later pageviews fall back to referrer classification.
170
+ }
171
+ }
172
+
53
173
  /**
54
174
  * One analytics event as sent to `/api/a` and forwarded to the CMS.
55
175
  *
@@ -72,7 +192,8 @@ export interface AnalyticsEvent {
72
192
  /**
73
193
  * `document.referrer` on pageviews, `""` on custom events. Truncated to
74
194
  * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
75
- * traffic-source classification — so custom events carry no attribution.
195
+ * traffic-source classification; custom events have no referrer, so their
196
+ * attribution rides entirely on {@link AnalyticsEvent.utm}.
76
197
  */
77
198
  ref: string;
78
199
  /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
@@ -86,7 +207,14 @@ export interface AnalyticsEvent {
86
207
  vh: number;
87
208
  /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
88
209
  ts: number;
89
- /** Pageviews only, and only for UTM params actually present in the URL. */
210
+ /**
211
+ * Campaign context. On pageviews: the `utm_*` params and click ids present
212
+ * in the URL, or — on later pages of the same visit — the ones the visit
213
+ * landed with (see {@link getSessionCampaign}). The CMS tells a landing from
214
+ * a later page by whether `url` itself carries them. On custom events:
215
+ * `utm_source`/`utm_medium`/`utm_campaign` from the 30-day ad-referral
216
+ * cookie, else the session's landing params.
217
+ */
90
218
  utm?: Record<string, string>;
91
219
  /**
92
220
  * Custom events only. Truncated to 128 chars.
@@ -156,7 +284,16 @@ function send(event: AnalyticsEvent): void {
156
284
  /** Track a page view. */
157
285
  export function trackPageView(): void {
158
286
  if (typeof window === "undefined") return;
159
- const utms = getUtmParams();
287
+ let utms = getUtmParams();
288
+ if (Object.keys(utms).length > 0) {
289
+ setSessionCampaign(utms);
290
+ } else {
291
+ const session = getSessionCampaign();
292
+ if (session) {
293
+ utms = session;
294
+ setSessionCampaign(session);
295
+ }
296
+ }
160
297
  send({
161
298
  type: "pageview",
162
299
  url: window.location.pathname + window.location.search,
@@ -185,6 +322,18 @@ export function trackEvent(
185
322
  props?: Record<string, string | number | boolean>,
186
323
  ): void {
187
324
  if (typeof window === "undefined") return;
325
+
326
+ // Carry the visit's campaign context onto the conversion.
327
+ //
328
+ // Custom events send no referrer (there isn't one — the visitor is already
329
+ // on the site), and the CMS derives traffic source from referrer + utm. So
330
+ // without this EVERY conversion classified as "direct", which both lost the
331
+ // attribution and inflated the direct bucket in the source breakdown by one
332
+ // per phone tap, mail click and form submit. The 30-day cookie wins (it
333
+ // credits a conversion days after the ad click); the session's landing
334
+ // params cover sites that mount no AdReferralTracker.
335
+ const utm = getAdReferralUtm() ?? getSessionCampaign();
336
+
188
337
  send({
189
338
  type: "event",
190
339
  url: window.location.pathname,
@@ -193,6 +342,7 @@ export function trackEvent(
193
342
  vw: window.innerWidth,
194
343
  vh: window.innerHeight,
195
344
  ts: Date.now(),
345
+ ...(utm ? { utm } : {}),
196
346
  name,
197
347
  props,
198
348
  });
@@ -238,6 +388,56 @@ export function trackFormSubmit(
238
388
  */
239
389
  export function trackPhoneClick(phoneNumber?: string): void {
240
390
  trackEvent("phone_click", { phone: phoneNumber ?? "" });
391
+ sendGooglePhoneClick(phoneNumber ?? "");
392
+ }
393
+
394
+ /**
395
+ * Mirror a phone tap to Google: a GA4 `phone_click` event and, when `CMSTags`
396
+ * published a `phoneConversionSendTo` label, a Google Ads conversion. No-op
397
+ * without `gtag`; never throws.
398
+ */
399
+ function sendGooglePhoneClick(phoneNumber: string): void {
400
+ if (typeof window === "undefined") return;
401
+ const w = window as unknown as {
402
+ gtag?: (...args: unknown[]) => void;
403
+ __vtPhoneConversionSendTo?: unknown;
404
+ };
405
+ if (typeof w.gtag !== "function") return;
406
+ try {
407
+ const sendTo = w.__vtPhoneConversionSendTo;
408
+ if (typeof sendTo === "string" && sendTo.trim() !== "") {
409
+ w.gtag("event", "conversion", { send_to: sendTo.trim() });
410
+ }
411
+ w.gtag("event", "phone_click", { link_url: `tel:${phoneNumber}` });
412
+ } catch {
413
+ // Analytics must never break a tap.
414
+ }
415
+ }
416
+
417
+ /** sessionStorage key marking that this session already sent `phone_swap`. */
418
+ const PHONE_SWAP_SENT_KEY = "vt_phone_swap_sent";
419
+
420
+ /**
421
+ * Record that Google's forwarding-number swap showed this visitor a call
422
+ * tracking number — i.e. an ad visitor was eligible to place a tracked call.
423
+ *
424
+ * Fired automatically (see the registration block below) when `CMSTags`'
425
+ * swap callback dispatches `vt-phone`; once per session, since gtag runs the
426
+ * callback on every full page load. The calls themselves never reach us —
427
+ * they go Google → shop — so this is the first-party half of call tracking.
428
+ *
429
+ * @param formatted The forwarding number as Google formatted it.
430
+ */
431
+ export function trackPhoneSwap(formatted?: string): void {
432
+ if (typeof window === "undefined") return;
433
+ try {
434
+ if (window.sessionStorage.getItem(PHONE_SWAP_SENT_KEY)) return;
435
+ window.sessionStorage.setItem(PHONE_SWAP_SENT_KEY, "1");
436
+ } catch {
437
+ // Storage blocked (private mode): send anyway — an occasional duplicate
438
+ // beats never counting the swap.
439
+ }
440
+ trackEvent("phone_swap", { phone: formatted ?? "" });
241
441
  }
242
442
 
243
443
  /**
@@ -253,20 +453,23 @@ export function trackEmailClick(email?: string): void {
253
453
  /**
254
454
  * Track a 404 page.
255
455
  *
256
- * Client-only. Unlike the other trackers, this dereferences `window` while
257
- * building its argument, so calling it during SSR throws a ReferenceError —
258
- * call it from a client component (or an effect), or pass `url` explicitly.
456
+ * `url` defaults to the current pathname. No-ops during SSR and on dev
457
+ * hostnames, and never throws — like every other tracker in this module.
458
+ *
459
+ * @param url Optional path to report instead of the current pathname.
259
460
  */
260
461
  export function track404(url?: string): void {
261
- trackEvent("404", { url: url ?? window?.location?.pathname ?? "" });
462
+ const path =
463
+ url ?? (typeof window === "undefined" ? "" : window.location.pathname);
464
+ trackEvent("404", { url: path });
262
465
  }
263
466
 
264
467
  /* ------------------------------------------------------------------ */
265
468
  /* Global hook registration */
266
469
  /* ------------------------------------------------------------------ */
267
470
 
268
- // TWO IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which
269
- // AnalyticsTracker does) is enough to activate both — integrators get them
471
+ // THREE IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which
472
+ // AnalyticsTracker does) is enough to activate all three — integrators get them
270
473
  // whether or not they ask.
271
474
  //
272
475
  // 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.
@@ -286,6 +489,18 @@ if (typeof window !== "undefined") {
286
489
  trackPhoneClick,
287
490
  trackEmailClick,
288
491
  };
492
+ // 3. Google's number swap (CMSTags) stores the forwarding number on
493
+ // `window.__vtPhone` and fires `vt-phone`. The callback can land before
494
+ // this module loads, so check for an already-stored number too.
495
+ if (!w.__vtPhoneSwapListenerInstalled) {
496
+ w.__vtPhoneSwapListenerInstalled = true;
497
+ const sendSwap = () => {
498
+ const swapped = w.__vtPhone as { formatted?: string } | undefined;
499
+ if (swapped) trackPhoneSwap(swapped.formatted);
500
+ };
501
+ window.addEventListener("vt-phone", sendSwap);
502
+ if (w.__vtPhone) sendSwap();
503
+ }
289
504
  if (!w.__vtClickTrackingInstalled) {
290
505
  w.__vtClickTrackingInstalled = true;
291
506
  document.addEventListener(