@vulcantech/analytics 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -10,44 +10,104 @@ Exports:
10
10
  - `@vulcantech/analytics/route` — App Router proxy handler (`POST`, `OPTIONS`) for `/api/a`.
11
11
  - `@vulcantech/analytics/tags` — `CMSTags` server component + `fetchTrackingTags` + the `TrackingTags` type.
12
12
 
13
- ## Integration
13
+ ## Event shape (`AnalyticsEvent`)
14
14
 
15
- Wire analytics into a consumer site (Next.js App Router):
15
+ Every tracker call builds one of these client-side and beacons it to `/api/a`, which forwards it to the CMS. You rarely construct one by hand, but the field limits below are enforced **server-side on ingest** — anything over them is silently truncated or dropped, not rejected.
16
16
 
17
- **1. Add the dependency** (`package.json`):
18
- ```json
19
- "@vulcantech/analytics": "*"
17
+ ```ts
18
+ interface AnalyticsEvent {
19
+ type: "pageview" | "event"; // the only two valid values
20
+ url: string; // pageview: pathname + search. event: pathname only
21
+ ref: string; // document.referrer on pageviews; "" on custom events
22
+ sid: string; // session id — see Session identity below
23
+ vw: number; // window.innerWidth — the CMS derives device from this
24
+ vh: number; // window.innerHeight
25
+ ts: number; // Date.now() on the client (clock is not trusted)
26
+ utm?: Record<string, string>; // pageviews only, and only when present in the URL
27
+ name?: string; // custom events only — the event name
28
+ props?: Record<string, string | number | boolean>; // custom events only
29
+ }
20
30
  ```
21
31
 
22
- **2. Transpile + alias it to SOURCE** (`next.config.js`), same shape as the other CMS packages. Alias directly to the source files — the root `.gcloudignore` strips `**/dist/` from the Cloud Build upload, so resolving via `package.json` (→ `dist/…`) 404s the build. Note the two-key pattern: the `/tags` subpath first, then the `$`-anchored bare specifier so it doesn't shadow the subpath:
23
- ```js
24
- transpilePackages: ["@vulcantech/analytics", /* ... */],
25
- webpack: (config) => {
26
- // subpath must come before the "$"-anchored bare specifier
27
- config.resolve.alias["@vulcantech/analytics/tags"] = path.join(__dirname, "../../packages/analytics/src/tags.tsx");
28
- config.resolve.alias["@vulcantech/analytics$"] = path.join(__dirname, "../../packages/analytics/src/index.tsx");
29
- return config;
30
- },
31
- turbopack: {
32
- resolveAlias: {
33
- "@vulcantech/analytics/tags": "./../../packages/analytics/src/tags.tsx",
34
- "@vulcantech/analytics": "./../../packages/analytics/src/index.tsx",
35
- },
36
- },
37
- ```
32
+ Field notes — all verified against the CMS ingest path (`/api/analytics` → `lib/analytics/ingest`):
33
+
34
+ - **`props` must be flat primitives.** Nested objects and arrays are **dropped** on ingest, so `{ items: [...] }` or `{ user: { id } }` silently vanish — flatten to `string | number | boolean` yourself. At most **32 keys** survive; keys are truncated to 64 chars, string values to 256, and HTML tags are stripped from both.
35
+ - **Length caps:** `url` and `ref` 2048, `name` 128, `sid` 64. Over-length values are truncated, not rejected.
36
+ - **`vw` drives the device breakdown** in the CMS dashboard: `<768` mobile, `<1024` tablet, else desktop. It is not merely diagnostic.
37
+ - **`ref` + `utm` drive traffic-source classification.** Custom events send `ref: ""`, so only pageviews carry attribution — don't expect a source on `trackEvent` data.
38
+ - **Reserved names.** Events with `name === "tracker_test"` or `url === "/__analytics_test__"` are deliberately discarded by the CMS (they exist for the connection self-test) and will never appear in stats. Don't use those values.
39
+ - **`type`, `url`, `sid`, `ts` are required** — an event missing any of them is rejected with a 400 at ingest.
40
+
41
+ ### Session identity
42
+
43
+ `sid` is a random ID in `sessionStorage` under `__vt_sid` — **no cookies, so nothing survives a tab close** and there is no cross-tab or cross-visit identity. When `sessionStorage` throws (private mode, blocked storage), the tracker falls back to a fresh random ID **per event**, which inflates session counts for those visitors. This is by design; the package never fingerprints.
44
+
45
+ ### Conversion tracking is automatic — do not double-wire
46
+
47
+ Importing this package (which `AnalyticsTracker` does) has two side effects at module load, on the client only:
48
+
49
+ 1. **A delegated `document` click listener** (capture phase, installed once) fires `trackPhoneClick` / `trackEmailClick` for **every** `a[href^="tel:"]` and `a[href^="mailto:"]` on the site. Adding your own `onClick={() => trackPhoneClick(...)}` **double-counts the conversion** — the listener already caught it. Only call those functions manually for a non-anchor trigger (e.g. a button that dials via JS).
50
+ 2. **`window.__vtTrack`** is registered with the four conversion trackers. `@vulcantech/forms` picks it up, so `form_view` / `form_submit` conversions track automatically on any site running `AnalyticsTracker`, with no per-form wiring. Passing `onFormView` / `onFormSubmit` props to `DynamicForm` **overrides** this rather than adding to it.
51
+
52
+ ### Dev-host skip
53
+
54
+ `send()` no-ops when the hostname is `localhost`, `127.0.0.1`, `0.0.0.0`, ends in `.local`, or contains `"localhost"`. The tracker functions are still safe to call — they just do nothing — so there is no dev-only guard to write. Test conversions against a deployed URL.
55
+
56
+ ### `AnalyticsTracker` firing rules
57
+
58
+ Client component (`"use client"`), renders `null`, and wraps itself in `Suspense` (Next 16 requires `useSearchParams` inside one) — so it is safe to drop straight into a server layout. It fires **exactly one** `trackPageView()` on mount and one per `pathname` **or** `searchParams` change. Because it watches search params, `/x?page=2` counts as a **separate pageview** from `/x`.
59
+
60
+ ## Tag config shape (`TrackingTags`)
61
+
62
+ `fetchTrackingTags()` resolves the project's third-party tag IDs; `CMSTags` renders them. The type carries only public IDs — the CMS strips its internal `enabled` / `updatedAt` fields before returning them to a consumer site.
38
63
 
39
- **2a. Add tsconfig paths** (`tsconfig.json`) so TypeScript resolves the source (no built `dist`):
40
- ```json
41
- "paths": {
42
- "@vulcantech/analytics": ["../../packages/analytics/src"],
43
- "@vulcantech/analytics/tags": ["../../packages/analytics/src/tags.tsx"]
64
+ ```ts
65
+ interface TrackingTags {
66
+ ga4Id?: string; // GA4 measurement ID — CMS validates /^G-[A-Z0-9]{4,14}$/
67
+ googleAdsId?: string; // Google Ads conversion ID — CMS validates /^AW-\d{6,12}$/
68
+ metaPixelId?: string; // Meta Pixel ID — CMS validates /^\d{6,20}$/ (numeric string)
44
69
  }
45
70
  ```
46
71
 
47
- **2b. COPY it in the Dockerfile** deps stage (alongside the other `packages/*/package.json` copies) — a frozen-lockfile `yarn install` needs the workspace member present or the build fails:
48
- ```dockerfile
49
- COPY packages/analytics/package.json ./packages/analytics/
72
+ - **`fetchTrackingTags()` returns `null`, not `{}`,** when all three resolve empty. `CMSTags` renders `null` in that case.
73
+ - **Format validation is CMS-side only.** Those patterns are enforced when a staff user saves the config in the dashboard. Values coming from the `NEXT_PUBLIC_*` env fallbacks are **not** validated by this package — a typo'd env ID is injected verbatim.
74
+ - **`CMSTags` is an async React Server Component.** Do not add `"use client"` to a wrapper around it and do not call `fetchTrackingTags()` from client code — it reads `VULCANTECH_API_KEY`.
75
+ - **What it renders:** one shared `next/script` `gtag.js` loader with `strategy="afterInteractive"`, keyed to the **first** present Google ID, plus an inline init that `gtag('config', …)`s every present Google ID; and, for Meta, the standard inline `fbq` bootstrap with `fbq('track','PageView')` and a `<noscript>` tracking-pixel `<img>`. Because it uses `next/script`, mounting it in `<body>` is correct — it does not need to be in `<head>`.
76
+ - **No consent gating.** Tags load as soon as the page hydrates. If the site needs a CMP / GDPR consent gate, `CMSTags` does not provide one and must not be mounted unconditionally on a site that requires consent.
77
+
78
+ ### The `enabled` toggle does not override env fallbacks
79
+
80
+ Turning tracking tags **off** in the CMS makes `/api/analytics/config` return `config: null` — which is the *same* response as "never configured". `fetchTrackingTags` then fills each field from `NEXT_PUBLIC_GA_ID` / `NEXT_PUBLIC_GOOGLE_ADS_ID` / `NEXT_PUBLIC_META_PIXEL_ID`. **So a site with those env vars set keeps firing its tags after the CMS switch is off.** To actually disable tags on such a site you must unset the env vars and redeploy. Sites that rely purely on the CMS (no `NEXT_PUBLIC_*` set) honor the toggle as expected.
81
+
82
+ ## Failure mode
83
+
84
+ **Nothing in this package throws, and nothing surfaces an error to your code.** There is no error state to render and no `catch` block worth writing — but that also means a fully broken pipeline looks identical to a working one from the site's side.
85
+
86
+ - **Trackers** (`trackEvent` and friends) swallow every send failure and return `void`. They also no-op entirely on SSR and on dev hostnames.
87
+ - **The `/api/a` proxy route** returns `503` when `VULCANTECH_PROJECT_ID` / `VULCANTECH_API_KEY` are unset and `400` on unparseable JSON — otherwise it **always returns `204`, including when the CMS was unreachable or rejected the event.** A 204 from `/api/a` is *not* evidence that anything was ingested.
88
+ - **The CMS drops events silently** when the request is bot-flagged by user agent, or rate limited — **100 events/min per `sid` and 600/min per IP**. Neither is reported back to the browser.
89
+ - **`fetchTrackingTags` / `CMSTags`** swallow CMS errors and fall through to the env fallbacks, then render `null` if those are empty too. A page build can never fail on the CMS being down.
90
+
91
+ **Two different API-key scopes are required, and the common misconfiguration is having only one.** Getting this wrong is invisible: events vanish while `/api/a` still answers 204.
92
+
93
+ | Surface | CMS endpoint | Required scope |
94
+ |---|---|---|
95
+ | `AnalyticsTracker` / trackers, via the `/api/a` proxy | `POST /api/analytics` | **`analytics:write`** |
96
+ | `CMSTags` / `fetchTrackingTags` | `GET /api/analytics/config` | **`analytics:read`** |
97
+
98
+ A site doing both needs **both scopes on the one key**. Verify ingestion in the CMS dashboard (Analytics → realtime), not by watching the browser's network tab for a 204.
99
+
100
+ ## Integration
101
+
102
+ Wire analytics into a consumer site (Next.js App Router):
103
+
104
+ **1. Add the dependency**:
105
+ ```bash
106
+ npm install @vulcantech/analytics
50
107
  ```
108
+ (Inside the VulcanTech monorepo, use the workspace wiring in `MONOREPO.md` instead.)
109
+
110
+ **2. Set the env** — see [Required env](#required-env) below.
51
111
 
52
112
  **3. Mount `AnalyticsTracker`** in the root layout (`src/app/layout.tsx`) — tracks page views on every route change:
53
113
  ```tsx
@@ -81,6 +141,8 @@ import { CMSTags } from "@vulcantech/analytics/tags";
81
141
 
82
142
  The API key must be granted the **`analytics:read`** scope in the CMS for `CMSTags` to resolve tag IDs (the `/api/analytics/config` endpoint). Without it (or with tags disabled) the CMS returns `null` and only the env fallbacks apply.
83
143
 
144
+ Event ingestion needs a **separate** scope — **`analytics:write`** — on the same key. See the scope table under [Failure mode](#failure-mode); a key with only `analytics:read` drops every event silently.
145
+
84
146
  ### Env fallbacks (tags)
85
147
  When the CMS omits a field (unreachable, unconfigured, or key lacks scope), each tag ID falls back to a public env var — **CMS value wins when present**:
86
148
 
@@ -104,7 +166,7 @@ None beyond env — analytics and tags are fully config-driven from the CMS.
104
166
  ```
105
167
 
106
168
  ### Notes
107
- - The tracker skips all sends on localhost/dev hostnames; test conversions against a deployed URL.
169
+ - The tracker skips all sends on localhost/dev hostnames; test conversions against a deployed URL. (Exact host list under [Dev-host skip](#dev-host-skip).)
108
170
  - `CMSTags` never throws — tag resolution failures are swallowed so a page build can never break on the CMS being down.
109
171
  - ISR invalidation: the CMS purges the `tracking-tags:{projectId}` tag when the project's analytics config changes. No consumer redeploy is needed for CMS value changes — ISR picks them up within ~60s (or instantly if the site is registered as a revalidation consumer).
110
172
  - **Google Ads shares the GA4 loader.** There is one `gtag.js` request (keyed to the GA4 ID); the Ads ID rides on it via an inline `gtag('config','AW-…')`. Don't expect a separate `gtag/js?id=AW-…` request or a standalone DOM element for it.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
1
+ import * as react from 'react';
2
2
 
3
3
  /**
4
4
  * VulcanTech Analytics — lightweight first-party tracker.
@@ -7,33 +7,115 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
7
7
  * Sends page views and custom events to /api/a on the same domain
8
8
  * via navigator.sendBeacon (falls back to fetch).
9
9
  */
10
+ /**
11
+ * One analytics event as sent to `/api/a` and forwarded to the CMS.
12
+ *
13
+ * The limits noted per field are enforced SERVER-SIDE on ingest
14
+ * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length
15
+ * values are truncated and unsupported shapes are dropped — never rejected —
16
+ * so an oversized event is stored lossily rather than failing loudly.
17
+ *
18
+ * `type`, `url`, `sid` and `ts` are required; an event missing any of them is
19
+ * rejected at ingest with a 400.
20
+ */
10
21
  interface AnalyticsEvent {
22
+ /** The only two valid values. */
11
23
  type: "pageview" | "event";
24
+ /**
25
+ * Pageviews send `pathname + search`; custom events send `pathname` only.
26
+ * Truncated to 2048 chars on ingest, with HTML tags stripped.
27
+ */
12
28
  url: string;
29
+ /**
30
+ * `document.referrer` on pageviews, `""` on custom events. Truncated to
31
+ * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
32
+ * traffic-source classification — so custom events carry no attribution.
33
+ */
13
34
  ref: string;
35
+ /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
14
36
  sid: string;
37
+ /**
38
+ * `window.innerWidth`. Not merely diagnostic: the CMS derives the device
39
+ * breakdown from it (<768 mobile, <1024 tablet, else desktop).
40
+ */
15
41
  vw: number;
42
+ /** `window.innerHeight`. */
16
43
  vh: number;
44
+ /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
17
45
  ts: number;
46
+ /** Pageviews only, and only for UTM params actually present in the URL. */
18
47
  utm?: Record<string, string>;
48
+ /**
49
+ * Custom events only. Truncated to 128 chars.
50
+ *
51
+ * `"tracker_test"` is RESERVED — the CMS discards events with that name
52
+ * (and events with url `/__analytics_test__`) so the connection self-test
53
+ * never pollutes stats. They will never appear in the dashboard.
54
+ */
19
55
  name?: string;
56
+ /**
57
+ * Custom events only. Must be FLAT primitives: nested objects and arrays
58
+ * are dropped on ingest, so flatten before sending. At most 32 keys
59
+ * survive; keys are truncated to 64 chars, string values to 256, and HTML
60
+ * tags are stripped from both.
61
+ */
20
62
  props?: Record<string, string | number | boolean>;
21
63
  }
22
64
  /** Track a page view. */
23
65
  declare function trackPageView(): void;
24
- /** Track a custom event. */
66
+ /**
67
+ * Track a custom event.
68
+ *
69
+ * `props` must be FLAT primitives — nested objects and arrays are dropped by
70
+ * the CMS on ingest, along with anything past the 32nd key. See
71
+ * {@link AnalyticsEvent.props} for the full set of caps.
72
+ *
73
+ * Avoid the reserved name `"tracker_test"`; the CMS discards it.
74
+ *
75
+ * No-ops during SSR and on dev hostnames, and never throws.
76
+ */
25
77
  declare function trackEvent(name: string, props?: Record<string, string | number | boolean>): void;
26
- /** Track when a form comes into view. */
78
+ /**
79
+ * Track when a form comes into view.
80
+ *
81
+ * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on
82
+ * `window.__vtTrack` and fires it automatically for every rendered form. Only
83
+ * call it manually for a form this package's global hook can't see.
84
+ */
27
85
  declare function trackFormView(formId: string, formName?: string): void;
28
- /** Track when a form is submitted successfully. */
86
+ /**
87
+ * Track when a form is submitted successfully.
88
+ *
89
+ * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via
90
+ * `window.__vtTrack`. `submissionType` defaults to `"contact"`.
91
+ */
29
92
  declare function trackFormSubmit(formId: string, formName?: string, submissionType?: string): void;
30
- /** Track when a phone number link is clicked. */
93
+ /**
94
+ * Track when a phone number link is clicked.
95
+ *
96
+ * ⚠ Do NOT wire this into an `onClick` on an `<a href="tel:…">` — importing
97
+ * this module installs a delegated document listener that already fires it for
98
+ * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.
99
+ * Call it manually only for a non-anchor trigger (e.g. a button that dials via
100
+ * JS).
101
+ */
31
102
  declare function trackPhoneClick(phoneNumber?: string): void;
32
- /** Track when an email link is clicked. */
103
+ /**
104
+ * Track when an email link is clicked.
105
+ *
106
+ * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href="mailto:…">`
107
+ * clicks are already captured by the delegated listener installed on import.
108
+ */
33
109
  declare function trackEmailClick(email?: string): void;
34
- /** Track a 404 page. */
110
+ /**
111
+ * Track a 404 page.
112
+ *
113
+ * Client-only. Unlike the other trackers, this dereferences `window` while
114
+ * building its argument, so calling it during SSR throws a ReferenceError —
115
+ * call it from a client component (or an effect), or pass `url` explicitly.
116
+ */
35
117
  declare function track404(url?: string): void;
36
118
 
37
- declare function AnalyticsTracker(): react_jsx_runtime.JSX.Element;
119
+ declare function AnalyticsTracker(): react.JSX.Element;
38
120
 
39
121
  export { type AnalyticsEvent, AnalyticsTracker, track404, trackEmailClick, trackEvent, trackFormSubmit, trackFormView, trackPageView, trackPhoneClick };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
1
+ import * as react from 'react';
2
2
 
3
3
  /**
4
4
  * VulcanTech Analytics — lightweight first-party tracker.
@@ -7,33 +7,115 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
7
7
  * Sends page views and custom events to /api/a on the same domain
8
8
  * via navigator.sendBeacon (falls back to fetch).
9
9
  */
10
+ /**
11
+ * One analytics event as sent to `/api/a` and forwarded to the CMS.
12
+ *
13
+ * The limits noted per field are enforced SERVER-SIDE on ingest
14
+ * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length
15
+ * values are truncated and unsupported shapes are dropped — never rejected —
16
+ * so an oversized event is stored lossily rather than failing loudly.
17
+ *
18
+ * `type`, `url`, `sid` and `ts` are required; an event missing any of them is
19
+ * rejected at ingest with a 400.
20
+ */
10
21
  interface AnalyticsEvent {
22
+ /** The only two valid values. */
11
23
  type: "pageview" | "event";
24
+ /**
25
+ * Pageviews send `pathname + search`; custom events send `pathname` only.
26
+ * Truncated to 2048 chars on ingest, with HTML tags stripped.
27
+ */
12
28
  url: string;
29
+ /**
30
+ * `document.referrer` on pageviews, `""` on custom events. Truncated to
31
+ * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS
32
+ * traffic-source classification — so custom events carry no attribution.
33
+ */
13
34
  ref: string;
35
+ /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */
14
36
  sid: string;
37
+ /**
38
+ * `window.innerWidth`. Not merely diagnostic: the CMS derives the device
39
+ * breakdown from it (<768 mobile, <1024 tablet, else desktop).
40
+ */
15
41
  vw: number;
42
+ /** `window.innerHeight`. */
16
43
  vh: number;
44
+ /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */
17
45
  ts: number;
46
+ /** Pageviews only, and only for UTM params actually present in the URL. */
18
47
  utm?: Record<string, string>;
48
+ /**
49
+ * Custom events only. Truncated to 128 chars.
50
+ *
51
+ * `"tracker_test"` is RESERVED — the CMS discards events with that name
52
+ * (and events with url `/__analytics_test__`) so the connection self-test
53
+ * never pollutes stats. They will never appear in the dashboard.
54
+ */
19
55
  name?: string;
56
+ /**
57
+ * Custom events only. Must be FLAT primitives: nested objects and arrays
58
+ * are dropped on ingest, so flatten before sending. At most 32 keys
59
+ * survive; keys are truncated to 64 chars, string values to 256, and HTML
60
+ * tags are stripped from both.
61
+ */
20
62
  props?: Record<string, string | number | boolean>;
21
63
  }
22
64
  /** Track a page view. */
23
65
  declare function trackPageView(): void;
24
- /** Track a custom event. */
66
+ /**
67
+ * Track a custom event.
68
+ *
69
+ * `props` must be FLAT primitives — nested objects and arrays are dropped by
70
+ * the CMS on ingest, along with anything past the 32nd key. See
71
+ * {@link AnalyticsEvent.props} for the full set of caps.
72
+ *
73
+ * Avoid the reserved name `"tracker_test"`; the CMS discards it.
74
+ *
75
+ * No-ops during SSR and on dev hostnames, and never throws.
76
+ */
25
77
  declare function trackEvent(name: string, props?: Record<string, string | number | boolean>): void;
26
- /** Track when a form comes into view. */
78
+ /**
79
+ * Track when a form comes into view.
80
+ *
81
+ * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on
82
+ * `window.__vtTrack` and fires it automatically for every rendered form. Only
83
+ * call it manually for a form this package's global hook can't see.
84
+ */
27
85
  declare function trackFormView(formId: string, formName?: string): void;
28
- /** Track when a form is submitted successfully. */
86
+ /**
87
+ * Track when a form is submitted successfully.
88
+ *
89
+ * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via
90
+ * `window.__vtTrack`. `submissionType` defaults to `"contact"`.
91
+ */
29
92
  declare function trackFormSubmit(formId: string, formName?: string, submissionType?: string): void;
30
- /** Track when a phone number link is clicked. */
93
+ /**
94
+ * Track when a phone number link is clicked.
95
+ *
96
+ * ⚠ Do NOT wire this into an `onClick` on an `<a href="tel:…">` — importing
97
+ * this module installs a delegated document listener that already fires it for
98
+ * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.
99
+ * Call it manually only for a non-anchor trigger (e.g. a button that dials via
100
+ * JS).
101
+ */
31
102
  declare function trackPhoneClick(phoneNumber?: string): void;
32
- /** Track when an email link is clicked. */
103
+ /**
104
+ * Track when an email link is clicked.
105
+ *
106
+ * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href="mailto:…">`
107
+ * clicks are already captured by the delegated listener installed on import.
108
+ */
33
109
  declare function trackEmailClick(email?: string): void;
34
- /** Track a 404 page. */
110
+ /**
111
+ * Track a 404 page.
112
+ *
113
+ * Client-only. Unlike the other trackers, this dereferences `window` while
114
+ * building its argument, so calling it during SSR throws a ReferenceError —
115
+ * call it from a client component (or an effect), or pass `url` explicitly.
116
+ */
35
117
  declare function track404(url?: string): void;
36
118
 
37
- declare function AnalyticsTracker(): react_jsx_runtime.JSX.Element;
119
+ declare function AnalyticsTracker(): react.JSX.Element;
38
120
 
39
121
  export { type AnalyticsEvent, AnalyticsTracker, track404, trackEmailClick, trackEvent, trackFormSubmit, trackFormView, trackPageView, trackPhoneClick };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx"],"names":["usePathname","useSearchParams","useRef","useEffect","Suspense","jsx"],"mappings":";;;;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAGpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,GAAA,EAAI,CAAE,SAAS,EAAE,CAAA;AAClE,MAAA,cAAA,CAAe,OAAA,CAAQ,aAAa,GAAG,CAAA;AAAA,IACzC;AACA,IA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AACX,QAAA,MAAM,IAAA,GAAO,IAAA,CAAK,YAAA,CAAa,MAAM,CAAA,IAAK,EAAA;AAC1C,QAAA,IAAI,IAAA,CAAK,WAAW,MAAM,CAAA,kBAAmB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,aACrD,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MACpC,CAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;AC5KA,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,WAAWA,sBAAA,EAAY;AAC7B,EAAA,MAAM,eAAeC,0BAAA,EAAgB;AACrC,EAAA,MAAM,aAAA,GAAgBC,aAAO,IAAI,CAAA;AAEjC,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,cAAc,OAAA,EAAS;AACzB,MAAA,aAAA,CAAc,OAAA,GAAU,KAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,CAAC,QAAA,EAAU,YAAY,CAAC,CAAA;AAE3B,EAAAA,eAAA,CAAU,MAAM;AACd,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,sCACGC,cAAA,EAAA,EAAS,QAAA,EAAU,IAAA,EAClB,QAAA,kBAAAC,cAAA,CAAC,yBAAsB,CAAA,EACzB,CAAA;AAEJ","file":"index.js","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/** Generate a random session ID (stored in sessionStorage, not cookies). */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/** Extract UTM params from the current URL. */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\nexport interface AnalyticsEvent {\n type: \"pageview\" | \"event\";\n url: string;\n ref: string;\n sid: string;\n vw: number;\n vh: number;\n ts: number;\n utm?: Record<string, string>;\n name?: string;\n props?: Record<string, string | number | boolean>;\n}\n\n/** Check if we're in a dev environment — skip all tracking if so. */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/** Send an analytics event via beacon (non-blocking). */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n const utms = getUtmParams();\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/** Track a custom event. */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n name,\n props,\n });\n}\n\n/** Track when a form comes into view. */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/** Track when a form is submitted successfully. */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/** Track when a phone number link is clicked. */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n}\n\n/** Track when an email link is clicked. */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/** Track a 404 page. */\nexport function track404(url?: string): void {\n trackEvent(\"404\", { url: url ?? window?.location?.pathname ?? \"\" });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// Expose the conversion trackers on a window global so UI packages\n// (e.g. @vulcantech/forms) can report form views/submits without a\n// hard dependency on this module, and install ONE delegated click\n// listener so tel:/mailto: links track phone/email conversions on\n// every page with zero per-component wiring.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place in your root layout — tracks page views on every route change.\n * Wrapped in Suspense to satisfy Next.js 16's requirement that\n * useSearchParams is inside a Suspense boundary.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx"],"names":["usePathname","useSearchParams","useRef","useEffect","Suspense","jsx"],"mappings":";;;;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAWpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,GAAA,EAAI,CAAE,SAAS,EAAE,CAAA;AAClE,MAAA,cAAA,CAAe,OAAA,CAAQ,aAAa,GAAG,CAAA;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CAAC,IAAA,EAAM;AACX,QAAA,MAAM,IAAA,GAAO,IAAA,CAAK,YAAA,CAAa,MAAM,CAAA,IAAK,EAAA;AAC1C,QAAA,IAAI,IAAA,CAAK,WAAW,MAAM,CAAA,kBAAmB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,aACrD,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MACpC,CAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;ACnRA,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,WAAWA,sBAAA,EAAY;AAC7B,EAAA,MAAM,eAAeC,0BAAA,EAAgB;AACrC,EAAA,MAAM,aAAA,GAAgBC,aAAO,IAAI,CAAA;AAEjC,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,cAAc,OAAA,EAAS;AACzB,MAAA,aAAA,CAAc,OAAA,GAAU,KAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,CAAC,QAAA,EAAU,YAAY,CAAC,CAAA;AAE3B,EAAAA,eAAA,CAAU,MAAM;AACd,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,sCACGC,cAAA,EAAA,EAAS,QAAA,EAAU,IAAA,EAClB,QAAA,kBAAAC,cAAA,CAAC,yBAAsB,CAAA,EACzB,CAAA;AAEJ","file":"index.js","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/**\n * Generate a random session ID (stored in sessionStorage, not cookies).\n *\n * No cookies means nothing survives a tab close, and there is no cross-tab or\n * cross-visit identity by design. When `sessionStorage` throws (private mode,\n * blocked storage) this returns a FRESH id per call, so each event from that\n * visitor counts as its own session — inflating session counts rather than\n * failing.\n */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/** Extract UTM params from the current URL. */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\n/**\n * One analytics event as sent to `/api/a` and forwarded to the CMS.\n *\n * The limits noted per field are enforced SERVER-SIDE on ingest\n * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length\n * values are truncated and unsupported shapes are dropped — never rejected —\n * so an oversized event is stored lossily rather than failing loudly.\n *\n * `type`, `url`, `sid` and `ts` are required; an event missing any of them is\n * rejected at ingest with a 400.\n */\nexport interface AnalyticsEvent {\n /** The only two valid values. */\n type: \"pageview\" | \"event\";\n /**\n * Pageviews send `pathname + search`; custom events send `pathname` only.\n * Truncated to 2048 chars on ingest, with HTML tags stripped.\n */\n url: string;\n /**\n * `document.referrer` on pageviews, `\"\"` on custom events. Truncated to\n * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS\n * traffic-source classification — so custom events carry no attribution.\n */\n ref: string;\n /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */\n sid: string;\n /**\n * `window.innerWidth`. Not merely diagnostic: the CMS derives the device\n * breakdown from it (<768 mobile, <1024 tablet, else desktop).\n */\n vw: number;\n /** `window.innerHeight`. */\n vh: number;\n /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */\n ts: number;\n /** Pageviews only, and only for UTM params actually present in the URL. */\n utm?: Record<string, string>;\n /**\n * Custom events only. Truncated to 128 chars.\n *\n * `\"tracker_test\"` is RESERVED — the CMS discards events with that name\n * (and events with url `/__analytics_test__`) so the connection self-test\n * never pollutes stats. They will never appear in the dashboard.\n */\n name?: string;\n /**\n * Custom events only. Must be FLAT primitives: nested objects and arrays\n * are dropped on ingest, so flatten before sending. At most 32 keys\n * survive; keys are truncated to 64 chars, string values to 256, and HTML\n * tags are stripped from both.\n */\n props?: Record<string, string | number | boolean>;\n}\n\n/**\n * Check if we're in a dev environment — skip all tracking if so.\n *\n * Matches `localhost`, `127.0.0.1`, `0.0.0.0`, any `*.local` host, and any\n * hostname CONTAINING \"localhost\". Tracker functions stay safe to call on\n * those hosts; they simply do nothing, so no dev-only guard is needed at the\n * call site. Test conversions against a deployed URL.\n */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/**\n * Send an analytics event via beacon (non-blocking).\n *\n * Never throws and never reports failure: send errors are swallowed, and the\n * `/api/a` proxy answers 204 even when the CMS was unreachable or rejected\n * the event. The CMS additionally drops events silently when the request is\n * bot-flagged by user agent or rate limited (100/min per `sid`, 600/min per\n * IP). Confirm ingestion in the CMS dashboard, not from the network tab.\n */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n const utms = getUtmParams();\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/**\n * Track a custom event.\n *\n * `props` must be FLAT primitives — nested objects and arrays are dropped by\n * the CMS on ingest, along with anything past the 32nd key. See\n * {@link AnalyticsEvent.props} for the full set of caps.\n *\n * Avoid the reserved name `\"tracker_test\"`; the CMS discards it.\n *\n * No-ops during SSR and on dev hostnames, and never throws.\n */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n name,\n props,\n });\n}\n\n/**\n * Track when a form comes into view.\n *\n * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on\n * `window.__vtTrack` and fires it automatically for every rendered form. Only\n * call it manually for a form this package's global hook can't see.\n */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/**\n * Track when a form is submitted successfully.\n *\n * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via\n * `window.__vtTrack`. `submissionType` defaults to `\"contact\"`.\n */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/**\n * Track when a phone number link is clicked.\n *\n * ⚠ Do NOT wire this into an `onClick` on an `<a href=\"tel:…\">` — importing\n * this module installs a delegated document listener that already fires it for\n * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.\n * Call it manually only for a non-anchor trigger (e.g. a button that dials via\n * JS).\n */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n}\n\n/**\n * Track when an email link is clicked.\n *\n * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href=\"mailto:…\">`\n * clicks are already captured by the delegated listener installed on import.\n */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/**\n * Track a 404 page.\n *\n * Client-only. Unlike the other trackers, this dereferences `window` while\n * building its argument, so calling it during SSR throws a ReferenceError —\n * call it from a client component (or an effect), or pass `url` explicitly.\n */\nexport function track404(url?: string): void {\n trackEvent(\"404\", { url: url ?? window?.location?.pathname ?? \"\" });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// TWO IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which\n// AnalyticsTracker does) is enough to activate both — integrators get them\n// whether or not they ask.\n//\n// 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.\n// @vulcantech/forms) can report form views/submits without a hard\n// dependency on this module. Passing onFormView/onFormSubmit props to\n// DynamicForm OVERRIDES these rather than adding to them.\n//\n// 2. ONE delegated capture-phase click listener makes every\n// `a[href^=\"tel:\"]` / `a[href^=\"mailto:\"]` on the site track a phone/email\n// conversion with zero per-component wiring. Consequently, adding a manual\n// onClick tracker to such an anchor double-counts it.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place ONCE in your root layout — tracks page views on every route change.\n * Renders `null`, and wraps itself in Suspense to satisfy Next.js 16's\n * requirement that useSearchParams sits inside a Suspense boundary, so it is\n * safe to drop directly into a server layout despite being a client component.\n *\n * Firing rules: exactly ONE trackPageView() on mount (the isFirstRender guard\n * below stops the mount from double-firing), then one per `pathname` OR\n * `searchParams` change. Because search params are watched, `/x?page=2` counts\n * as a separate pageview from `/x`.\n *\n * Mounting this also activates the module-level side effects in `./tracker` —\n * `window.__vtTrack` (which @vulcantech/forms uses for automatic form\n * conversions) and the delegated tel:/mailto: click listener.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx"],"names":[],"mappings":";;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAGpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM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A,QAAA,CAAS,gBAAA;AAAA,MACP,OAAA;AAAA,MACA,CAAC,CAAA,KAAM;AACL,QAAA,MAAM,SAAS,CAAA,CAAE,MAAA;AACjB,QAAA,MAAM,IAAA,GAAO,MAAA,EAAQ,OAAA,GAAU,qCAAqC,CAAA;AACpE,QAAA,IAAI,CAAC,IAAA,EAAM;AACX,QAAA,MAAM,IAAA,GAAO,IAAA,CAAK,YAAA,CAAa,MAAM,CAAA,IAAK,EAAA;AAC1C,QAAA,IAAI,IAAA,CAAK,WAAW,MAAM,CAAA,kBAAmB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,aACrD,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MACpC,CAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;AC5KA,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,MAAM,eAAe,eAAA,EAAgB;AACrC,EAAA,MAAM,aAAA,GAAgB,OAAO,IAAI,CAAA;AAEjC,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,cAAc,OAAA,EAAS;AACzB,MAAA,aAAA,CAAc,OAAA,GAAU,KAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,CAAC,QAAA,EAAU,YAAY,CAAC,CAAA;AAE3B,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,2BACG,QAAA,EAAA,EAAS,QAAA,EAAU,IAAA,EAClB,QAAA,kBAAA,GAAA,CAAC,yBAAsB,CAAA,EACzB,CAAA;AAEJ","file":"index.mjs","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/** Generate a random session ID (stored in sessionStorage, not cookies). */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/** Extract UTM params from the current URL. */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\nexport interface AnalyticsEvent {\n type: \"pageview\" | \"event\";\n url: string;\n ref: string;\n sid: string;\n vw: number;\n vh: number;\n ts: number;\n utm?: Record<string, string>;\n name?: string;\n props?: Record<string, string | number | boolean>;\n}\n\n/** Check if we're in a dev environment — skip all tracking if so. */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/** Send an analytics event via beacon (non-blocking). */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n const utms = getUtmParams();\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/** Track a custom event. */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n name,\n props,\n });\n}\n\n/** Track when a form comes into view. */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/** Track when a form is submitted successfully. */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/** Track when a phone number link is clicked. */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n}\n\n/** Track when an email link is clicked. */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/** Track a 404 page. */\nexport function track404(url?: string): void {\n trackEvent(\"404\", { url: url ?? window?.location?.pathname ?? \"\" });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// Expose the conversion trackers on a window global so UI packages\n// (e.g. @vulcantech/forms) can report form views/submits without a\n// hard dependency on this module, and install ONE delegated click\n// listener so tel:/mailto: links track phone/email conversions on\n// every page with zero per-component wiring.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place in your root layout — tracks page views on every route change.\n * Wrapped in Suspense to satisfy Next.js 16's requirement that\n * useSearchParams is inside a Suspense boundary.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/tracker.ts","../src/AnalyticsTracker.tsx"],"names":[],"mappings":";;;;;AAQA,IAAM,QAAA,GAAW,QAAA;AACjB,IAAM,WAAA,GAAc,UAAA;AAWpB,SAAS,YAAA,GAAuB;AAC9B,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAC1C,EAAA,IAAI;AACF,IAAA,IAAI,GAAA,GAAM,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAA;AAC5C,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,GAAA,GAAM,IAAA,CAAK,MAAA,EAAO,CA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ACP,OAAA;AAAA,MACA,CAAC,CAAA,KAAM;AACL,QAAA,MAAM,SAAS,CAAA,CAAE,MAAA;AACjB,QAAA,MAAM,IAAA,GAAO,MAAA,EAAQ,OAAA,GAAU,qCAAqC,CAAA;AACpE,QAAA,IAAI,CAAC,IAAA,EAAM;AACX,QAAA,MAAM,IAAA,GAAO,IAAA,CAAK,YAAA,CAAa,MAAM,CAAA,IAAK,EAAA;AAC1C,QAAA,IAAI,IAAA,CAAK,WAAW,MAAM,CAAA,kBAAmB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,aACrD,eAAA,CAAgB,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MACpC,CAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;ACnRA,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,MAAM,eAAe,eAAA,EAAgB;AACrC,EAAA,MAAM,aAAA,GAAgB,OAAO,IAAI,CAAA;AAEjC,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,cAAc,OAAA,EAAS;AACzB,MAAA,aAAA,CAAc,OAAA,GAAU,KAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,CAAC,QAAA,EAAU,YAAY,CAAC,CAAA;AAE3B,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,aAAA,EAAc;AAAA,EAChB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,2BACG,QAAA,EAAA,EAAS,QAAA,EAAU,IAAA,EAClB,QAAA,kBAAA,GAAA,CAAC,yBAAsB,CAAA,EACzB,CAAA;AAEJ","file":"index.mjs","sourcesContent":["/**\n * VulcanTech Analytics — lightweight first-party tracker.\n *\n * < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.\n * Sends page views and custom events to /api/a on the same domain\n * via navigator.sendBeacon (falls back to fetch).\n */\n\nconst ENDPOINT = \"/api/a\";\nconst SESSION_KEY = \"__vt_sid\";\n\n/**\n * Generate a random session ID (stored in sessionStorage, not cookies).\n *\n * No cookies means nothing survives a tab close, and there is no cross-tab or\n * cross-visit identity by design. When `sessionStorage` throws (private mode,\n * blocked storage) this returns a FRESH id per call, so each event from that\n * visitor counts as its own session — inflating session counts rather than\n * failing.\n */\nfunction getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n try {\n let sid = sessionStorage.getItem(SESSION_KEY);\n if (!sid) {\n sid = Math.random().toString(36).slice(2) + Date.now().toString(36);\n sessionStorage.setItem(SESSION_KEY, sid);\n }\n return sid;\n } catch {\n return Math.random().toString(36).slice(2);\n }\n}\n\n/** Extract UTM params from the current URL. */\nfunction getUtmParams(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const params = new URLSearchParams(window.location.search);\n const utms: Record<string, string> = {};\n for (const key of [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n ]) {\n const val = params.get(key);\n if (val) utms[key] = val;\n }\n return utms;\n}\n\n/**\n * One analytics event as sent to `/api/a` and forwarded to the CMS.\n *\n * The limits noted per field are enforced SERVER-SIDE on ingest\n * (`/api/analytics` → `lib/analytics/ingest` in vulcantech-cms). Over-length\n * values are truncated and unsupported shapes are dropped — never rejected —\n * so an oversized event is stored lossily rather than failing loudly.\n *\n * `type`, `url`, `sid` and `ts` are required; an event missing any of them is\n * rejected at ingest with a 400.\n */\nexport interface AnalyticsEvent {\n /** The only two valid values. */\n type: \"pageview\" | \"event\";\n /**\n * Pageviews send `pathname + search`; custom events send `pathname` only.\n * Truncated to 2048 chars on ingest, with HTML tags stripped.\n */\n url: string;\n /**\n * `document.referrer` on pageviews, `\"\"` on custom events. Truncated to\n * 2048 chars. Together with {@link AnalyticsEvent.utm} this drives the CMS\n * traffic-source classification — so custom events carry no attribution.\n */\n ref: string;\n /** Session id from `sessionStorage` — see {@link getSessionId}. Capped at 64 chars. */\n sid: string;\n /**\n * `window.innerWidth`. Not merely diagnostic: the CMS derives the device\n * breakdown from it (<768 mobile, <1024 tablet, else desktop).\n */\n vw: number;\n /** `window.innerHeight`. */\n vh: number;\n /** `Date.now()` on the client. The CMS stores its own `serverTs` alongside it. */\n ts: number;\n /** Pageviews only, and only for UTM params actually present in the URL. */\n utm?: Record<string, string>;\n /**\n * Custom events only. Truncated to 128 chars.\n *\n * `\"tracker_test\"` is RESERVED — the CMS discards events with that name\n * (and events with url `/__analytics_test__`) so the connection self-test\n * never pollutes stats. They will never appear in the dashboard.\n */\n name?: string;\n /**\n * Custom events only. Must be FLAT primitives: nested objects and arrays\n * are dropped on ingest, so flatten before sending. At most 32 keys\n * survive; keys are truncated to 64 chars, string values to 256, and HTML\n * tags are stripped from both.\n */\n props?: Record<string, string | number | boolean>;\n}\n\n/**\n * Check if we're in a dev environment — skip all tracking if so.\n *\n * Matches `localhost`, `127.0.0.1`, `0.0.0.0`, any `*.local` host, and any\n * hostname CONTAINING \"localhost\". Tracker functions stay safe to call on\n * those hosts; they simply do nothing, so no dev-only guard is needed at the\n * call site. Test conversions against a deployed URL.\n */\nfunction isDev(): boolean {\n if (typeof window === \"undefined\") return true;\n const host = window.location.hostname;\n return (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.endsWith(\".local\") ||\n host.includes(\"localhost\")\n );\n}\n\n/**\n * Send an analytics event via beacon (non-blocking).\n *\n * Never throws and never reports failure: send errors are swallowed, and the\n * `/api/a` proxy answers 204 even when the CMS was unreachable or rejected\n * the event. The CMS additionally drops events silently when the request is\n * bot-flagged by user agent or rate limited (100/min per `sid`, 600/min per\n * IP). Confirm ingestion in the CMS dashboard, not from the network tab.\n */\nfunction send(event: AnalyticsEvent): void {\n if (isDev()) return;\n const payload = JSON.stringify(event);\n try {\n if (navigator.sendBeacon) {\n navigator.sendBeacon(ENDPOINT, payload);\n } else {\n fetch(ENDPOINT, {\n method: \"POST\",\n body: payload,\n headers: { \"Content-Type\": \"application/json\" },\n keepalive: true,\n }).catch(() => {});\n }\n } catch {\n // Silently fail — analytics should never break the app\n }\n}\n\n/** Track a page view. */\nexport function trackPageView(): void {\n if (typeof window === \"undefined\") return;\n const utms = getUtmParams();\n send({\n type: \"pageview\",\n url: window.location.pathname + window.location.search,\n ref: document.referrer,\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n ...(Object.keys(utms).length > 0 ? { utm: utms } : {}),\n });\n}\n\n/**\n * Track a custom event.\n *\n * `props` must be FLAT primitives — nested objects and arrays are dropped by\n * the CMS on ingest, along with anything past the 32nd key. See\n * {@link AnalyticsEvent.props} for the full set of caps.\n *\n * Avoid the reserved name `\"tracker_test\"`; the CMS discards it.\n *\n * No-ops during SSR and on dev hostnames, and never throws.\n */\nexport function trackEvent(\n name: string,\n props?: Record<string, string | number | boolean>,\n): void {\n if (typeof window === \"undefined\") return;\n send({\n type: \"event\",\n url: window.location.pathname,\n ref: \"\",\n sid: getSessionId(),\n vw: window.innerWidth,\n vh: window.innerHeight,\n ts: Date.now(),\n name,\n props,\n });\n}\n\n/**\n * Track when a form comes into view.\n *\n * Usually you do NOT call this yourself: `@vulcantech/forms` finds it on\n * `window.__vtTrack` and fires it automatically for every rendered form. Only\n * call it manually for a form this package's global hook can't see.\n */\nexport function trackFormView(formId: string, formName?: string): void {\n trackEvent(\"form_view\", { formId, formName: formName ?? \"\" });\n}\n\n/**\n * Track when a form is submitted successfully.\n *\n * Like {@link trackFormView}, `@vulcantech/forms` fires this automatically via\n * `window.__vtTrack`. `submissionType` defaults to `\"contact\"`.\n */\nexport function trackFormSubmit(\n formId: string,\n formName?: string,\n submissionType?: string,\n): void {\n trackEvent(\"form_submit\", {\n formId,\n formName: formName ?? \"\",\n submissionType: submissionType ?? \"contact\",\n });\n}\n\n/**\n * Track when a phone number link is clicked.\n *\n * ⚠ Do NOT wire this into an `onClick` on an `<a href=\"tel:…\">` — importing\n * this module installs a delegated document listener that already fires it for\n * every such anchor, so adding your own handler DOUBLE-COUNTS the conversion.\n * Call it manually only for a non-anchor trigger (e.g. a button that dials via\n * JS).\n */\nexport function trackPhoneClick(phoneNumber?: string): void {\n trackEvent(\"phone_click\", { phone: phoneNumber ?? \"\" });\n}\n\n/**\n * Track when an email link is clicked.\n *\n * ⚠ Same double-count caveat as {@link trackPhoneClick}: `<a href=\"mailto:…\">`\n * clicks are already captured by the delegated listener installed on import.\n */\nexport function trackEmailClick(email?: string): void {\n trackEvent(\"email_click\", { email: email ?? \"\" });\n}\n\n/**\n * Track a 404 page.\n *\n * Client-only. Unlike the other trackers, this dereferences `window` while\n * building its argument, so calling it during SSR throws a ReferenceError —\n * call it from a client component (or an effect), or pass `url` explicitly.\n */\nexport function track404(url?: string): void {\n trackEvent(\"404\", { url: url ?? window?.location?.pathname ?? \"\" });\n}\n\n/* ------------------------------------------------------------------ */\n/* Global hook registration */\n/* ------------------------------------------------------------------ */\n\n// TWO IMPORT-TIME SIDE EFFECTS, client-only. Importing this module (which\n// AnalyticsTracker does) is enough to activate both — integrators get them\n// whether or not they ask.\n//\n// 1. `window.__vtTrack` exposes the conversion trackers so UI packages (e.g.\n// @vulcantech/forms) can report form views/submits without a hard\n// dependency on this module. Passing onFormView/onFormSubmit props to\n// DynamicForm OVERRIDES these rather than adding to them.\n//\n// 2. ONE delegated capture-phase click listener makes every\n// `a[href^=\"tel:\"]` / `a[href^=\"mailto:\"]` on the site track a phone/email\n// conversion with zero per-component wiring. Consequently, adding a manual\n// onClick tracker to such an anchor double-counts it.\nif (typeof window !== \"undefined\") {\n const w = window as unknown as Record<string, unknown>;\n w.__vtTrack = {\n trackFormView,\n trackFormSubmit,\n trackPhoneClick,\n trackEmailClick,\n };\n if (!w.__vtClickTrackingInstalled) {\n w.__vtClickTrackingInstalled = true;\n document.addEventListener(\n \"click\",\n (e) => {\n const target = e.target as Element | null;\n const link = target?.closest?.(\"a[href^='tel:'], a[href^='mailto:']\");\n if (!link) return;\n const href = link.getAttribute(\"href\") || \"\";\n if (href.startsWith(\"tel:\")) trackPhoneClick(href.slice(4));\n else trackEmailClick(href.slice(7));\n },\n true,\n );\n }\n}\n","\"use client\";\n\n/**\n * Drop-in analytics component for Next.js App Router.\n *\n * Place ONCE in your root layout — tracks page views on every route change.\n * Renders `null`, and wraps itself in Suspense to satisfy Next.js 16's\n * requirement that useSearchParams sits inside a Suspense boundary, so it is\n * safe to drop directly into a server layout despite being a client component.\n *\n * Firing rules: exactly ONE trackPageView() on mount (the isFirstRender guard\n * below stops the mount from double-firing), then one per `pathname` OR\n * `searchParams` change. Because search params are watched, `/x?page=2` counts\n * as a separate pageview from `/x`.\n *\n * Mounting this also activates the module-level side effects in `./tracker` —\n * `window.__vtTrack` (which @vulcantech/forms uses for automatic form\n * conversions) and the delegated tel:/mailto: click listener.\n *\n * Usage:\n * import { AnalyticsTracker } from \"@vulcantech/analytics\";\n * <AnalyticsTracker />\n */\n\nimport { Suspense, useEffect, useRef } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport { trackPageView } from \"./tracker\";\n\nfunction AnalyticsTrackerInner() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRender = useRef(true);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n trackPageView();\n }, [pathname, searchParams]);\n\n useEffect(() => {\n trackPageView();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsTracker() {\n return (\n <Suspense fallback={null}>\n <AnalyticsTrackerInner />\n </Suspense>\n );\n}\n"]}
package/dist/route.d.mts CHANGED
@@ -11,9 +11,30 @@ import { NextResponse, NextRequest } from 'next/server';
11
11
  * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
12
12
  * VULCANTECH_PROJECT_ID — project ID for this site
13
13
  * VULCANTECH_API_KEY — API key for this site
14
+ *
15
+ * The API key must carry the `analytics:write` scope — the scope the CMS's
16
+ * POST /api/analytics enforces. This is a DIFFERENT scope from the
17
+ * `analytics:read` that CMSTags needs for tag config; a site doing both needs
18
+ * both on the one key. A key missing `analytics:write` drops every event while
19
+ * this route still answers 204 (see POST below), so the misconfiguration is
20
+ * invisible from the browser — verify ingestion in the CMS dashboard.
14
21
  */
15
22
 
16
23
  declare function OPTIONS(): Promise<NextResponse<unknown>>;
24
+ /**
25
+ * Forward one tracker event to the CMS, stamped with this site's project ID,
26
+ * API key, and any CDN-provided geo headers.
27
+ *
28
+ * Status contract:
29
+ * 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.
30
+ * 400 — the request body is not parseable JSON.
31
+ * 204 — EVERYTHING else, including when the CMS was unreachable, rejected
32
+ * the event, or dropped it (bad scope, bot user agent, rate limit).
33
+ *
34
+ * So a 204 is not evidence of ingestion. This is deliberate: the forward is
35
+ * awaited but its result is discarded, because analytics must never block or
36
+ * break a page.
37
+ */
17
38
  declare function POST(req: NextRequest): Promise<NextResponse<unknown>>;
18
39
 
19
40
  export { OPTIONS, POST };
package/dist/route.d.ts CHANGED
@@ -11,9 +11,30 @@ import { NextResponse, NextRequest } from 'next/server';
11
11
  * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
12
12
  * VULCANTECH_PROJECT_ID — project ID for this site
13
13
  * VULCANTECH_API_KEY — API key for this site
14
+ *
15
+ * The API key must carry the `analytics:write` scope — the scope the CMS's
16
+ * POST /api/analytics enforces. This is a DIFFERENT scope from the
17
+ * `analytics:read` that CMSTags needs for tag config; a site doing both needs
18
+ * both on the one key. A key missing `analytics:write` drops every event while
19
+ * this route still answers 204 (see POST below), so the misconfiguration is
20
+ * invisible from the browser — verify ingestion in the CMS dashboard.
14
21
  */
15
22
 
16
23
  declare function OPTIONS(): Promise<NextResponse<unknown>>;
24
+ /**
25
+ * Forward one tracker event to the CMS, stamped with this site's project ID,
26
+ * API key, and any CDN-provided geo headers.
27
+ *
28
+ * Status contract:
29
+ * 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.
30
+ * 400 — the request body is not parseable JSON.
31
+ * 204 — EVERYTHING else, including when the CMS was unreachable, rejected
32
+ * the event, or dropped it (bad scope, bot user agent, rate limit).
33
+ *
34
+ * So a 204 is not evidence of ingestion. This is deliberate: the forward is
35
+ * awaited but its result is discarded, because analytics must never block or
36
+ * break a page.
37
+ */
17
38
  declare function POST(req: NextRequest): Promise<NextResponse<unknown>>;
18
39
 
19
40
  export { OPTIONS, POST };