@vulcantech/analytics 0.1.1 → 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
@@ -9,7 +9,15 @@
9
9
  const ENDPOINT = "/api/a";
10
10
  const SESSION_KEY = "__vt_sid";
11
11
 
12
- /** Generate a random session ID (stored in sessionStorage, not cookies). */
12
+ /**
13
+ * Generate a random session ID (stored in sessionStorage, not cookies).
14
+ *
15
+ * No cookies means nothing survives a tab close, and there is no cross-tab or
16
+ * cross-visit identity by design. When `sessionStorage` throws (private mode,
17
+ * blocked storage) this returns a FRESH id per call, so each event from that
18
+ * visitor counts as its own session — inflating session counts rather than
19
+ * failing.
20
+ */
13
21
  function getSessionId(): string {
14
22
  if (typeof window === "undefined") return "";
15
23
  try {
@@ -24,7 +32,68 @@ function getSessionId(): string {
24
32
  }
25
33
  }
26
34
 
27
- /** 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
+ */
28
97
  function getUtmParams(): Record<string, string> {
29
98
  if (typeof window === "undefined") return {};
30
99
  const params = new URLSearchParams(window.location.search);
@@ -35,6 +104,13 @@ function getUtmParams(): Record<string, string> {
35
104
  "utm_campaign",
36
105
  "utm_term",
37
106
  "utm_content",
107
+ "gclid",
108
+ "gbraid",
109
+ "wbraid",
110
+ "gad_source",
111
+ "gad_campaignid",
112
+ "fbclid",
113
+ "msclkid",
38
114
  ]) {
39
115
  const val = params.get(key);
40
116
  if (val) utms[key] = val;
@@ -42,20 +118,129 @@ function getUtmParams(): Record<string, string> {
42
118
  return utms;
43
119
  }
44
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
+
173
+ /**
174
+ * One analytics event as sent to `/api/a` and forwarded to the CMS.
175
+ *
176
+ * The limits noted per field are enforced SERVER-SIDE on ingest
177
+ * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length
178
+ * values are truncated and unsupported shapes are dropped — never rejected —
179
+ * so an oversized event is stored lossily rather than failing loudly.
180
+ *
181
+ * `type`, `url`, `sid` and `ts` are required; an event missing any of them is
182
+ * rejected at ingest with a 400.
183
+ */
45
184
  export interface AnalyticsEvent {
185
+ /** The only two valid values. */
46
186
  type: "pageview" | "event";
187
+ /**
188
+ * Pageviews send `pathname + search`; custom events send `pathname` only.
189
+ * Truncated to 2048 chars on ingest, with HTML tags stripped.
190
+ */
47
191
  url: string;
192
+ /**
193
+ * `document.referrer` on pageviews, `""` on custom events. Truncated to
194
+ * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
195
+ * traffic-source classification; custom events have no referrer, so their
196
+ * attribution rides entirely on {@link AnalyticsEvent.utm}.
197
+ */
48
198
  ref: string;
199
+ /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
49
200
  sid: string;
201
+ /**
202
+ * `window.innerWidth`. Not merely diagnostic: the CMS derives the device
203
+ * breakdown from it (<768 mobile, <1024 tablet, else desktop).
204
+ */
50
205
  vw: number;
206
+ /** `window.innerHeight`. */
51
207
  vh: number;
208
+ /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
52
209
  ts: number;
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
+ */
53
218
  utm?: Record<string, string>;
219
+ /**
220
+ * Custom events only. Truncated to 128 chars.
221
+ *
222
+ * `"tracker_test"` is RESERVED — the CMS discards events with that name
223
+ * (and events with url `/__analytics_test__`) so the connection self-test
224
+ * never pollutes stats. They will never appear in the dashboard.
225
+ */
54
226
  name?: string;
227
+ /**
228
+ * Custom events only. Must be FLAT primitives: nested objects and arrays
229
+ * are dropped on ingest, so flatten before sending. At most 32 keys
230
+ * survive; keys are truncated to 64 chars, string values to 256, and HTML
231
+ * tags are stripped from both.
232
+ */
55
233
  props?: Record<string, string | number | boolean>;
56
234
  }
57
235
 
58
- /** Check if we're in a dev environment — skip all tracking if so. */
236
+ /**
237
+ * Check if we're in a dev environment — skip all tracking if so.
238
+ *
239
+ * Matches `localhost`, `127.0.0.1`, `0.0.0.0`, any `*.local` host, and any
240
+ * hostname CONTAINING "localhost". Tracker functions stay safe to call on
241
+ * those hosts; they simply do nothing, so no dev-only guard is needed at the
242
+ * call site. Test conversions against a deployed URL.
243
+ */
59
244
  function isDev(): boolean {
60
245
  if (typeof window === "undefined") return true;
61
246
  const host = window.location.hostname;
@@ -68,7 +253,15 @@ function isDev(): boolean {
68
253
  );
69
254
  }
70
255
 
71
- /** Send an analytics event via beacon (non-blocking). */
256
+ /**
257
+ * Send an analytics event via beacon (non-blocking).
258
+ *
259
+ * Never throws and never reports failure: send errors are swallowed, and the
260
+ * `/api/a` proxy answers 204 even when the CMS was unreachable or rejected
261
+ * the event. The CMS additionally drops events silently when the request is
262
+ * bot-flagged by user agent or rate limited (100/min per `sid`, 600/min per
263
+ * IP). Confirm ingestion in the CMS dashboard, not from the network tab.
264
+ */
72
265
  function send(event: AnalyticsEvent): void {
73
266
  if (isDev()) return;
74
267
  const payload = JSON.stringify(event);
@@ -91,7 +284,16 @@ function send(event: AnalyticsEvent): void {
91
284
  /** Track a page view. */
92
285
  export function trackPageView(): void {
93
286
  if (typeof window === "undefined") return;
94
- 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
+ }
95
297
  send({
96
298
  type: "pageview",
97
299
  url: window.location.pathname + window.location.search,
@@ -104,12 +306,34 @@ export function trackPageView(): void {
104
306
  });
105
307
  }
106
308
 
107
- /** Track a custom event. */
309
+ /**
310
+ * Track a custom event.
311
+ *
312
+ * `props` must be FLAT primitives — nested objects and arrays are dropped by
313
+ * the CMS on ingest, along with anything past the 32nd key. See
314
+ * {@link AnalyticsEvent.props} for the full set of caps.
315
+ *
316
+ * Avoid the reserved name `"tracker_test"`; the CMS discards it.
317
+ *
318
+ * No-ops during SSR and on dev hostnames, and never throws.
319
+ */
108
320
  export function trackEvent(
109
321
  name: string,
110
322
  props?: Record<string, string | number | boolean>,
111
323
  ): void {
112
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
+
113
337
  send({
114
338
  type: "event",
115
339
  url: window.location.pathname,
@@ -118,17 +342,29 @@ export function trackEvent(
118
342
  vw: window.innerWidth,
119
343
  vh: window.innerHeight,
120
344
  ts: Date.now(),
345
+ ...(utm ? { utm } : {}),
121
346
  name,
122
347
  props,
123
348
  });
124
349
  }
125
350
 
126
- /** Track when a form comes into view. */
351
+ /**
352
+ * Track when a form comes into view.
353
+ *
354
+ * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on
355
+ * `window.__vtTrack` and fires it automatically for every rendered form. Only
356
+ * call it manually for a form this package's global hook can't see.
357
+ */
127
358
  export function trackFormView(formId: string, formName?: string): void {
128
359
  trackEvent("form_view", { formId, formName: formName ?? "" });
129
360
  }
130
361
 
131
- /** Track when a form is submitted successfully. */
362
+ /**
363
+ * Track when a form is submitted successfully.
364
+ *
365
+ * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via
366
+ * `window.__vtTrack`. `submissionType` defaults to `"contact"`.
367
+ */
132
368
  export function trackFormSubmit(
133
369
  formId: string,
134
370
  formName?: string,
@@ -141,30 +377,110 @@ export function trackFormSubmit(
141
377
  });
142
378
  }
143
379
 
144
- /** Track when a phone number link is clicked. */
380
+ /**
381
+ * Track when a phone number link is clicked.
382
+ *
383
+ * ⚠ Do NOT wire this into an `onClick` on an `<a href="tel:…">` — importing
384
+ * this module installs a delegated document listener that already fires it for
385
+ * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.
386
+ * Call it manually only for a non-anchor trigger (e.g. a button that dials via
387
+ * JS).
388
+ */
145
389
  export function trackPhoneClick(phoneNumber?: string): void {
146
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
+ }
147
415
  }
148
416
 
149
- /** Track when an email link is clicked. */
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 ?? "" });
441
+ }
442
+
443
+ /**
444
+ * Track when an email link is clicked.
445
+ *
446
+ * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href="mailto:…">`
447
+ * clicks are already captured by the delegated listener installed on import.
448
+ */
150
449
  export function trackEmailClick(email?: string): void {
151
450
  trackEvent("email_click", { email: email ?? "" });
152
451
  }
153
452
 
154
- /** Track a 404 page. */
453
+ /**
454
+ * Track a 404 page.
455
+ *
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.
460
+ */
155
461
  export function track404(url?: string): void {
156
- trackEvent("404", { url: url ?? window?.location?.pathname ?? "" });
462
+ const path =
463
+ url ?? (typeof window === "undefined" ? "" : window.location.pathname);
464
+ trackEvent("404", { url: path });
157
465
  }
158
466
 
159
467
  /* ------------------------------------------------------------------ */
160
468
  /* Global hook registration */
161
469
  /* ------------------------------------------------------------------ */
162
470
 
163
- // Expose the conversion trackers on a window global so UI packages
164
- // (e.g. @vulcantech/forms) can report form views/submits without a
165
- // hard dependency on this module, and install ONE delegated click
166
- // listener so tel:/mailto: links track phone/email conversions on
167
- // every page with zero per-component wiring.
471
+ // THREE IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which
472
+ // AnalyticsTracker does) is enough to activate all three — integrators get them
473
+ // whether or not they ask.
474
+ //
475
+ // 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.
476
+ // @vulcantech/forms) can report form views/submits without a hard
477
+ // dependency on this module. Passing onFormView/onFormSubmit props to
478
+ // DynamicForm OVERRIDES these rather than adding to them.
479
+ //
480
+ // 2. ONE delegated capture-phase click listener makes every
481
+ // `a[href^="tel:"]` / `a[href^="mailto:"]` on the site track a phone/email
482
+ // conversion with zero per-component wiring. Consequently, adding a manual
483
+ // onClick tracker to such an anchor double-counts it.
168
484
  if (typeof window !== "undefined") {
169
485
  const w = window as unknown as Record<string, unknown>;
170
486
  w.__vtTrack = {
@@ -173,6 +489,18 @@ if (typeof window !== "undefined") {
173
489
  trackPhoneClick,
174
490
  trackEmailClick,
175
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
+ }
176
504
  if (!w.__vtClickTrackingInstalled) {
177
505
  w.__vtClickTrackingInstalled = true;
178
506
  document.addEventListener(