@codefast/tracking 0.5.0-canary.5 → 1.0.0-canary.6

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.
Files changed (133) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +122 -127
  3. package/dist/client/browser-cookie.d.mts +11 -0
  4. package/dist/client/browser-cookie.mjs +15 -0
  5. package/dist/client/consent-runtime.d.mts +56 -0
  6. package/dist/client/consent-runtime.mjs +35 -0
  7. package/dist/client/consent-storage.d.mts +5 -0
  8. package/dist/client/consent-storage.mjs +20 -1
  9. package/dist/client/consent-withdrawal.d.mts +21 -0
  10. package/dist/client/consent-withdrawal.mjs +17 -0
  11. package/dist/client/cookie-anonymous-id.d.mts +37 -0
  12. package/dist/client/cookie-anonymous-id.mjs +46 -0
  13. package/dist/client/create-client-tracker.d.mts +11 -16
  14. package/dist/client/create-client-tracker.mjs +27 -53
  15. package/dist/client/gpc.d.mts +2 -0
  16. package/dist/client/gpc.mjs +3 -1
  17. package/dist/client/index.d.mts +7 -5
  18. package/dist/client/index.mjs +8 -6
  19. package/dist/client/initial-consent-store.d.mts +66 -0
  20. package/dist/client/initial-consent-store.mjs +119 -0
  21. package/dist/client/is-analytics-allowed.d.mts +29 -0
  22. package/dist/client/is-analytics-allowed.mjs +23 -0
  23. package/dist/client/server-persisted-anonymous-id.d.mts +33 -0
  24. package/dist/client/server-persisted-anonymous-id.mjs +50 -0
  25. package/dist/core/consent-config.d.mts +27 -0
  26. package/dist/core/consent-config.mjs +11 -0
  27. package/dist/core/consent.d.mts +99 -4
  28. package/dist/core/consent.mjs +99 -4
  29. package/dist/core/cookie.d.mts +17 -0
  30. package/dist/core/cookie.mjs +23 -0
  31. package/dist/core/destination.d.mts +10 -8
  32. package/dist/core/event-catalog.d.mts +16 -13
  33. package/dist/core/event-catalog.mjs +19 -1
  34. package/dist/core/event-id.d.mts +1 -2
  35. package/dist/core/event-id.mjs +1 -2
  36. package/dist/core/index.d.mts +6 -4
  37. package/dist/core/index.mjs +5 -3
  38. package/dist/core/tracked-event.d.mts +21 -8
  39. package/dist/destinations/google-analytics.d.mts +100 -48
  40. package/dist/destinations/google-analytics.mjs +89 -85
  41. package/dist/destinations/google-consent.d.mts +64 -0
  42. package/dist/destinations/google-consent.mjs +102 -0
  43. package/dist/destinations/index.d.mts +2 -5
  44. package/dist/destinations/index.mjs +2 -5
  45. package/dist/destinations/shared.d.mts +20 -0
  46. package/dist/destinations/shared.mjs +13 -0
  47. package/dist/destinations/vercel-analytics.d.mts +19 -4
  48. package/dist/destinations/vercel-analytics.mjs +11 -18
  49. package/dist/import-protection.d.mts +19 -0
  50. package/dist/import-protection.mjs +23 -0
  51. package/dist/index.d.mts +6 -4
  52. package/dist/index.mjs +5 -3
  53. package/dist/react/consent-banner.d.mts +24 -7
  54. package/dist/react/consent-banner.mjs +16 -11
  55. package/dist/react/gtag-consent-bootstrap.d.mts +27 -0
  56. package/dist/react/gtag-consent-bootstrap.mjs +29 -0
  57. package/dist/react/index.d.mts +4 -1
  58. package/dist/react/index.mjs +4 -1
  59. package/dist/react/use-consent.d.mts +9 -13
  60. package/dist/react/use-consent.mjs +42 -25
  61. package/dist/react/use-google-consent-sync.d.mts +23 -0
  62. package/dist/react/use-google-consent-sync.mjs +24 -0
  63. package/dist/react/use-initial-consent.d.mts +14 -0
  64. package/dist/react/use-initial-consent.mjs +19 -0
  65. package/dist/server/anonymous-id-cookie.d.mts +46 -0
  66. package/dist/server/anonymous-id-cookie.mjs +51 -0
  67. package/dist/server/index.d.mts +5 -3
  68. package/dist/server/index.mjs +4 -3
  69. package/dist/server/initial-consent.d.mts +29 -0
  70. package/dist/server/initial-consent.mjs +31 -0
  71. package/dist/server/region.d.mts +21 -4
  72. package/dist/server/region.mjs +26 -5
  73. package/dist/tanstack-start/index.d.mts +58 -0
  74. package/dist/tanstack-start/index.mjs +45 -0
  75. package/package.json +26 -110
  76. package/src/client/browser-cookie.ts +16 -0
  77. package/src/client/consent-runtime.ts +80 -0
  78. package/src/client/consent-storage.ts +31 -1
  79. package/src/client/consent-withdrawal.ts +32 -0
  80. package/src/client/cookie-anonymous-id.ts +93 -0
  81. package/src/client/create-client-tracker.ts +56 -85
  82. package/src/client/gpc.ts +4 -2
  83. package/src/client/index.ts +19 -8
  84. package/src/client/initial-consent-store.ts +218 -0
  85. package/src/client/is-analytics-allowed.ts +43 -0
  86. package/src/client/server-persisted-anonymous-id.ts +99 -0
  87. package/src/core/consent-config.ts +27 -0
  88. package/src/core/consent.ts +164 -10
  89. package/src/core/cookie.ts +29 -0
  90. package/src/core/destination.ts +10 -8
  91. package/src/core/event-catalog.ts +28 -15
  92. package/src/core/event-id.ts +1 -2
  93. package/src/core/index.ts +19 -3
  94. package/src/core/tracked-event.ts +22 -7
  95. package/src/destinations/google-analytics.ts +196 -133
  96. package/src/destinations/google-consent.ts +164 -0
  97. package/src/destinations/index.ts +14 -15
  98. package/src/destinations/shared.ts +45 -0
  99. package/src/destinations/vercel-analytics.ts +23 -24
  100. package/src/import-protection.ts +20 -0
  101. package/src/index.ts +46 -8
  102. package/src/react/consent-banner.tsx +40 -14
  103. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  104. package/src/react/index.ts +8 -0
  105. package/src/react/use-consent.ts +53 -45
  106. package/src/react/use-google-consent-sync.ts +38 -0
  107. package/src/react/use-initial-consent.ts +22 -0
  108. package/src/server/anonymous-id-cookie.ts +76 -0
  109. package/src/server/index.ts +15 -3
  110. package/src/server/initial-consent.ts +48 -0
  111. package/src/server/region.ts +22 -5
  112. package/src/tanstack-start/index.ts +83 -0
  113. package/dist/client/lifecycle.d.mts +0 -23
  114. package/dist/client/lifecycle.mjs +0 -30
  115. package/dist/client/local-storage.d.mts +0 -13
  116. package/dist/client/local-storage.mjs +0 -31
  117. package/dist/client/queue.d.mts +0 -49
  118. package/dist/client/queue.mjs +0 -71
  119. package/dist/client/router.d.mts +0 -30
  120. package/dist/client/router.mjs +0 -17
  121. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  122. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  123. package/dist/destinations/http-destination.d.mts +0 -20
  124. package/dist/destinations/http-destination.mjs +0 -25
  125. package/dist/server/create-server-tracker.d.mts +0 -42
  126. package/dist/server/create-server-tracker.mjs +0 -67
  127. package/src/client/lifecycle.ts +0 -50
  128. package/src/client/local-storage.ts +0 -44
  129. package/src/client/queue.ts +0 -117
  130. package/src/client/router.ts +0 -37
  131. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  132. package/src/destinations/http-destination.ts +0 -33
  133. package/src/server/create-server-tracker.ts +0 -128
@@ -1,42 +0,0 @@
1
- import { TrackedEvent } from "../core/tracked-event.mjs";
2
- import { Destination } from "../core/destination.mjs";
3
- import { EventCatalog, EventsOf } from "../core/event-catalog.mjs";
4
- import { z } from "zod";
5
-
6
- //#region src/server/create-server-tracker.d.ts
7
- /**
8
- * @since 0.5.0-canary.4
9
- */
10
- interface ServerTrackContext {
11
- anonymousId: string;
12
- userId?: string | undefined;
13
- }
14
- /**
15
- * @since 0.5.0-canary.4
16
- */
17
- interface ServerTrackerOptions<Catalog extends EventCatalog> {
18
- catalog: Catalog;
19
- destinations: Array<Destination>;
20
- generateEventId?: () => string;
21
- maxRetries?: number;
22
- onDestinationError?: (error: unknown, destination: Destination, event: TrackedEvent) => void;
23
- retryDelayMs?: number;
24
- }
25
- /**
26
- * @since 0.5.0-canary.4
27
- */
28
- interface ServerTracker<Catalog extends EventCatalog> {
29
- /** Explicit anonymous → known-user merge, for when `identify` timing can't do it. */
30
- alias: (previousId: string, userId: string, context: ServerTrackContext) => Promise<void>;
31
- group: (groupId: string, traits: Record<string, unknown> | undefined, context: ServerTrackContext) => Promise<void>;
32
- track: <Name extends keyof EventsOf<Catalog, "server">>(name: Name, props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>, context: ServerTrackContext) => Promise<void>;
33
- }
34
- /**
35
- * No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
36
- * failing after retries is only logged via `onDestinationError`, never re-queued.
37
- *
38
- * @since 0.5.0-canary.4
39
- */
40
- declare function createServerTracker<Catalog extends EventCatalog>(options: ServerTrackerOptions<Catalog>): ServerTracker<Catalog>;
41
- //#endregion
42
- export { ServerTrackContext, ServerTracker, ServerTrackerOptions, createServerTracker };
@@ -1,67 +0,0 @@
1
- import { generateEventId } from "../core/event-id.mjs";
2
- //#region src/server/create-server-tracker.ts
3
- function sleep(ms) {
4
- return new Promise((resolve) => {
5
- setTimeout(resolve, ms);
6
- });
7
- }
8
- async function sendWithRetry(destination, event, maxRetries, retryDelayMs, onError) {
9
- for (let attempt = 0; attempt <= maxRetries; attempt += 1) try {
10
- await destination.send(event);
11
- return;
12
- } catch (error) {
13
- if (attempt === maxRetries) {
14
- onError(error, destination, event);
15
- return;
16
- }
17
- await sleep(retryDelayMs * 2 ** attempt);
18
- }
19
- }
20
- /**
21
- * No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
22
- * failing after retries is only logged via `onDestinationError`, never re-queued.
23
- *
24
- * @since 0.5.0-canary.4
25
- */
26
- function createServerTracker(options) {
27
- const maxRetries = options.maxRetries ?? 2;
28
- const retryDelayMs = options.retryDelayMs ?? 200;
29
- const createId = options.generateEventId ?? generateEventId;
30
- const onError = options.onDestinationError ?? ((error, destination, event) => {
31
- console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
32
- });
33
- async function sendEvent(name, props, context) {
34
- const event = {
35
- anonymousId: context.anonymousId,
36
- eventId: createId(),
37
- name,
38
- owner: "server",
39
- props,
40
- timestamp: Date.now(),
41
- ...context.userId === void 0 ? {} : { userId: context.userId }
42
- };
43
- await Promise.all(options.destinations.map(async (destination) => sendWithRetry(destination, event, maxRetries, retryDelayMs, onError)));
44
- }
45
- return {
46
- async alias(previousId, userId, context) {
47
- await sendEvent("$alias", {
48
- previousId,
49
- userId
50
- }, context);
51
- },
52
- async group(groupId, traits, context) {
53
- await sendEvent("$group", {
54
- groupId,
55
- ...traits
56
- }, context);
57
- },
58
- async track(name, props, context) {
59
- const definition = options.catalog[name];
60
- if (!definition || definition.owner !== "server") throw new Error(`Unknown server-owned event: ${String(name)}`);
61
- definition.schema.parse(props);
62
- await sendEvent(name, props, context);
63
- }
64
- };
65
- }
66
- //#endregion
67
- export { createServerTracker };
@@ -1,50 +0,0 @@
1
- import type { ClientTracker } from "#/client/create-client-tracker";
2
- import type { EventCatalog } from "#/core/event-catalog";
3
-
4
- /**
5
- * @since 0.5.0-canary.4
6
- */
7
- export interface ClientLifecycleOptions {
8
- /** `sendBeacon` target used on unload — omit to skip the unload flush entirely. */
9
- beaconEndpoint?: string;
10
- flushIntervalMs?: number;
11
- }
12
-
13
- /**
14
- * Wires the two flush triggers the queue itself can't own (batch-size is handled inside
15
- * `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
16
- * unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
17
- * Returns a cleanup function to remove all listeners/timers.
18
- *
19
- * @since 0.5.0-canary.4
20
- */
21
- export function attachClientLifecycle<Catalog extends EventCatalog>(
22
- tracker: Pick<ClientTracker<Catalog>, "flush" | "flushWithBeacon">,
23
- options: ClientLifecycleOptions = {},
24
- ): () => void {
25
- const flushIntervalMs = options.flushIntervalMs ?? 10_000;
26
- const intervalId = setInterval(() => {
27
- void tracker.flush();
28
- }, flushIntervalMs);
29
-
30
- function flushOnUnload(): void {
31
- if (options.beaconEndpoint !== undefined) {
32
- tracker.flushWithBeacon(options.beaconEndpoint);
33
- }
34
- }
35
-
36
- function handleVisibilityChange(): void {
37
- if (document.visibilityState === "hidden") {
38
- flushOnUnload();
39
- }
40
- }
41
-
42
- document.addEventListener("visibilitychange", handleVisibilityChange);
43
- window.addEventListener("pagehide", flushOnUnload);
44
-
45
- return () => {
46
- clearInterval(intervalId);
47
- document.removeEventListener("visibilitychange", handleVisibilityChange);
48
- window.removeEventListener("pagehide", flushOnUnload);
49
- };
50
- }
@@ -1,44 +0,0 @@
1
- import type { EventQueueStorage } from "#/client/queue";
2
- import type { TrackedEvent } from "#/core/tracked-event";
3
-
4
- /**
5
- * `localStorage`-backed queue storage — corrupt/missing state, a private-mode/quota
6
- * error, or no `window` (SSR) are all treated as empty rather than thrown, since a lost
7
- * offline queue is preferable to a crashing app.
8
- *
9
- * @since 0.5.0-canary.4
10
- */
11
- export function createLocalStorageQueueStorage(storageKey: string): EventQueueStorage {
12
- return {
13
- load(): Array<TrackedEvent> {
14
- if (typeof globalThis.window === "undefined") {
15
- return [];
16
- }
17
-
18
- try {
19
- const raw = globalThis.window.localStorage.getItem(storageKey);
20
-
21
- if (!raw) {
22
- return [];
23
- }
24
-
25
- const parsed: unknown = JSON.parse(raw);
26
-
27
- return Array.isArray(parsed) ? (parsed as Array<TrackedEvent>) : [];
28
- } catch {
29
- return [];
30
- }
31
- },
32
- save(events: Array<TrackedEvent>): void {
33
- if (typeof globalThis.window === "undefined") {
34
- return;
35
- }
36
-
37
- try {
38
- globalThis.window.localStorage.setItem(storageKey, JSON.stringify(events));
39
- } catch {
40
- /* storage blocked (private mode / quota) */
41
- }
42
- },
43
- };
44
- }
@@ -1,117 +0,0 @@
1
- import type { Destination } from "#/core/destination";
2
- import type { TrackedEvent } from "#/core/tracked-event";
3
-
4
- /**
5
- * Persistence backend for the offline queue — a thin wrapper so tests and non-browser
6
- * environments can swap in an in-memory implementation instead of real `localStorage`.
7
- *
8
- * @since 0.5.0-canary.4
9
- */
10
- export interface EventQueueStorage {
11
- load: () => Array<TrackedEvent>;
12
- save: (events: Array<TrackedEvent>) => void;
13
- }
14
-
15
- /**
16
- * @since 0.5.0-canary.4
17
- */
18
- export interface EventQueueOptions {
19
- destinations: Array<Destination>;
20
- flushBatchSize?: number | undefined;
21
- maxQueueSize?: number | undefined;
22
- maxRetries?: number | undefined;
23
- storage: EventQueueStorage;
24
- }
25
-
26
- interface QueuedEvent {
27
- attempts: number;
28
- event: TrackedEvent;
29
- }
30
-
31
- /**
32
- * Client-side batching/offline queue: persists across reloads, caps its size
33
- * (drop-oldest), and retries a failed batch up to `maxRetries` times.
34
- *
35
- * @since 0.5.0-canary.4
36
- */
37
- export class EventQueue {
38
- private readonly destinations: Array<Destination>;
39
- private readonly flushBatchSize: number;
40
- private readonly maxQueueSize: number;
41
- private readonly maxRetries: number;
42
- private pending: Array<QueuedEvent>;
43
- private readonly storage: EventQueueStorage;
44
-
45
- constructor(options: EventQueueOptions) {
46
- this.destinations = options.destinations;
47
- this.storage = options.storage;
48
- this.maxQueueSize = options.maxQueueSize ?? 500;
49
- this.maxRetries = options.maxRetries ?? 3;
50
- this.flushBatchSize = options.flushBatchSize ?? 20;
51
- this.pending = this.storage.load().map((event) => ({ attempts: 0, event }));
52
- }
53
-
54
- get size(): number {
55
- return this.pending.length;
56
- }
57
-
58
- /** Drops every pending event without sending it — used on consent revoke. */
59
- clear(): void {
60
- this.pending = [];
61
- this.persist();
62
- }
63
-
64
- /** Empties the queue synchronously for `navigator.sendBeacon`, which can't be awaited. */
65
- drain(): Array<TrackedEvent> {
66
- const events = this.pending.map((queued) => queued.event);
67
-
68
- this.pending = [];
69
- this.persist();
70
-
71
- return events;
72
- }
73
-
74
- enqueue(event: TrackedEvent): void {
75
- this.pending.push({ attempts: 0, event });
76
-
77
- if (this.pending.length > this.maxQueueSize) {
78
- this.pending = this.pending.slice(this.pending.length - this.maxQueueSize);
79
- }
80
-
81
- this.persist();
82
-
83
- if (this.pending.length >= this.flushBatchSize) {
84
- void this.flush();
85
- }
86
- }
87
-
88
- async flush(): Promise<void> {
89
- if (this.pending.length === 0) {
90
- return;
91
- }
92
-
93
- const batch = this.pending;
94
-
95
- this.pending = [];
96
-
97
- const results = await Promise.allSettled(
98
- batch.map(async (queued) => {
99
- await Promise.all(this.destinations.map(async (destination) => destination.send(queued.event)));
100
- }),
101
- );
102
-
103
- for (const [index, result] of results.entries()) {
104
- const queued = batch[index];
105
-
106
- if (result.status === "rejected" && queued && queued.attempts < this.maxRetries) {
107
- this.pending.push({ attempts: queued.attempts + 1, event: queued.event });
108
- }
109
- }
110
-
111
- this.persist();
112
- }
113
-
114
- private persist(): void {
115
- this.storage.save(this.pending.map((queued) => queued.event));
116
- }
117
- }
@@ -1,37 +0,0 @@
1
- import type { ClientTracker } from "#/client/create-client-tracker";
2
- import type { EventCatalog } from "#/core/event-catalog";
3
-
4
- interface ResolvedNavigation {
5
- toLocation: {
6
- href: string;
7
- pathname: string;
8
- };
9
- }
10
-
11
- /**
12
- * Structurally matches `Router["subscribe"]` from `@tanstack/router-core` for the
13
- * `"onResolved"` event — duck-typed so this package doesn't depend on TanStack Router.
14
- *
15
- * @since 0.5.0-canary.4
16
- */
17
- export interface RouterLike {
18
- subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
19
- }
20
-
21
- /**
22
- * `onResolved` (not `popstate`) is what fires on SPA navigation in TanStack Router;
23
- * `popstate` only fires for browser back/forward. Page views are low-frequency, so this
24
- * flushes right away instead of waiting on the batch queue's interval/size threshold —
25
- * a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
26
- *
27
- * @since 0.5.0-canary.4
28
- */
29
- export function attachRouterPageTracking<Catalog extends EventCatalog>(
30
- tracker: Pick<ClientTracker<Catalog>, "flush" | "page">,
31
- router: RouterLike,
32
- ): () => void {
33
- return router.subscribe("onResolved", (event) => {
34
- tracker.page(event.toLocation.pathname, { href: event.toLocation.href });
35
- void tracker.flush();
36
- });
37
- }
@@ -1,166 +0,0 @@
1
- import type { Destination } from "#/core/destination";
2
-
3
- type MeasurementProtocolParamValue = boolean | number | string;
4
-
5
- /**
6
- * Measurement Protocol event params must be flat string/number/boolean — stringify
7
- * anything else instead of letting GA4 silently drop it.
8
- */
9
- function toMeasurementProtocolParams(props: Record<string, unknown>): Record<string, MeasurementProtocolParamValue> {
10
- const result: Record<string, MeasurementProtocolParamValue> = {};
11
-
12
- for (const [key, value] of Object.entries(props)) {
13
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
14
- result[key] = value;
15
- } else if (value !== undefined && value !== null) {
16
- result[key] = JSON.stringify(value);
17
- }
18
- }
19
-
20
- return result;
21
- }
22
-
23
- function readCookie(cookieHeader: string | undefined, cookieName: string): string | undefined {
24
- if (!cookieHeader) {
25
- return undefined;
26
- }
27
-
28
- for (const part of cookieHeader.split(";")) {
29
- const separatorIndex = part.indexOf("=");
30
-
31
- if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) {
32
- return part.slice(separatorIndex + 1).trim();
33
- }
34
- }
35
-
36
- return undefined;
37
- }
38
-
39
- /**
40
- * Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
41
- * `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
42
- * pass it as `clientId` to make server events land on the same user as the visitor's
43
- * client-side hits.
44
- *
45
- * @since 0.5.0-canary.4
46
- */
47
- export function extractGa4ClientId(cookieHeader: string | undefined): string | undefined {
48
- const value = readCookie(cookieHeader, "_ga");
49
-
50
- if (!value) {
51
- return undefined;
52
- }
53
-
54
- // Format: GA1.<domain-depth>.<random>.<timestamp> — the client ID is the last two segments.
55
- const segments = value.split(".");
56
-
57
- return segments.length >= 4 ? segments.slice(-2).join(".") : undefined;
58
- }
59
-
60
- /**
61
- * Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
62
- * (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
63
- * `$`-delimited `GS2` value formats.
64
- *
65
- * @since 0.5.0-canary.4
66
- */
67
- export function extractGa4SessionId(cookieHeader: string | undefined, measurementId: string): string | undefined {
68
- const value = readCookie(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
69
-
70
- if (!value) {
71
- return undefined;
72
- }
73
-
74
- // GS1.1.<session_id>.<count>... vs GS2.1.s<session_id>$o<count>... — the session ID is
75
- // the first number after the version prefix either way.
76
- const match = /^GS\d+\.\d+\.s?(\d+)/.exec(value);
77
-
78
- return match?.[1];
79
- }
80
-
81
- /**
82
- * @since 0.5.0-canary.4
83
- */
84
- export interface Ga4MeasurementProtocolDestinationOptions {
85
- apiSecret: string;
86
- /**
87
- * gtag.js's client ID for this visitor (see `extractGa4ClientId`). Without it the
88
- * event falls back to the tracker's anonymous ID, which GA4 treats as a *different
89
- * user* than the visitor's client-side hits — pass it whenever the request carries a
90
- * `_ga` cookie.
91
- */
92
- clientId?: string | undefined;
93
- /** Routes to GA4's `/debug/mp/collect` validation endpoint — hits are validated but never recorded. */
94
- debug?: boolean;
95
- measurementId: string;
96
- name?: string;
97
- /**
98
- * Current GA4 session for this visitor (see `extractGa4SessionId`). Without a
99
- * `session_id`, GA4 accepts the event but leaves it out of session-scoped and realtime
100
- * reporting.
101
- */
102
- sessionId?: string | undefined;
103
- }
104
-
105
- /**
106
- * Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
107
- * signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
108
- * to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
109
- * `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
110
- *
111
- * @since 0.5.0-canary.4
112
- */
113
- export function createGa4MeasurementProtocolDestination(
114
- options: Ga4MeasurementProtocolDestinationOptions,
115
- ): Destination {
116
- const name = options.name ?? "ga4-measurement-protocol";
117
- const host = options.debug
118
- ? "https://www.google-analytics.com/debug/mp/collect"
119
- : "https://www.google-analytics.com/mp/collect";
120
- const endpoint = `${host}?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
121
-
122
- return {
123
- name,
124
- async send(event) {
125
- // GA4 has no alias concept — identity merge happens via user_id on later events.
126
- if (event.name === "$alias") {
127
- return;
128
- }
129
-
130
- // join_group is GA4's recommended-event equivalent of a group association.
131
- const eventName = event.name === "$group" ? "join_group" : event.name;
132
- const props = event.name === "$group" ? renameGroupIdProp(event.props) : event.props;
133
- const params = toMeasurementProtocolParams(props);
134
-
135
- if (options.sessionId !== undefined && params.session_id === undefined) {
136
- params.session_id = options.sessionId;
137
- }
138
-
139
- // Without an engagement time GA4 won't count the user as active in realtime;
140
- // 100ms is the fallback Google's own MP examples use when elapsed time is unknown.
141
- params.engagement_time_msec ??= 100;
142
-
143
- const response = await fetch(endpoint, {
144
- body: JSON.stringify({
145
- client_id: options.clientId ?? event.anonymousId,
146
- events: [{ name: eventName, params }],
147
- // MP stamps receipt time otherwise — retried events would drift.
148
- timestamp_micros: event.timestamp * 1000,
149
- ...(event.userId === undefined ? {} : { user_id: event.userId }),
150
- }),
151
- headers: { "content-type": "application/json" },
152
- method: "POST",
153
- });
154
-
155
- if (!response.ok) {
156
- throw new Error(`"${name}" destination responded with ${String(response.status)}`);
157
- }
158
- },
159
- };
160
- }
161
-
162
- function renameGroupIdProp(props: Record<string, unknown>): Record<string, unknown> {
163
- const { groupId, ...traits } = props;
164
-
165
- return { group_id: groupId, ...traits };
166
- }
@@ -1,33 +0,0 @@
1
- import type { Destination } from "#/core/destination";
2
-
3
- /**
4
- * @since 0.5.0-canary.4
5
- */
6
- export interface HttpDestinationOptions {
7
- endpoint: string;
8
- headers?: Record<string, string>;
9
- name: string;
10
- }
11
-
12
- /**
13
- * Generic fetch-based `Destination` — the building block for a real provider adapter
14
- * (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
15
- *
16
- * @since 0.5.0-canary.4
17
- */
18
- export function createHttpDestination(options: HttpDestinationOptions): Destination {
19
- return {
20
- name: options.name,
21
- async send(event) {
22
- const response = await fetch(options.endpoint, {
23
- body: JSON.stringify(event),
24
- headers: { "content-type": "application/json", ...options.headers },
25
- method: "POST",
26
- });
27
-
28
- if (!response.ok) {
29
- throw new Error(`"${options.name}" destination responded with ${String(response.status)}`);
30
- }
31
- },
32
- };
33
- }
@@ -1,128 +0,0 @@
1
- import type { z } from "zod";
2
-
3
- import type { Destination } from "#/core/destination";
4
- import type { EventCatalog, EventsOf } from "#/core/event-catalog";
5
- import { generateEventId } from "#/core/event-id";
6
- import type { TrackedEvent } from "#/core/tracked-event";
7
-
8
- /**
9
- * @since 0.5.0-canary.4
10
- */
11
- export interface ServerTrackContext {
12
- anonymousId: string;
13
- userId?: string | undefined;
14
- }
15
-
16
- /**
17
- * @since 0.5.0-canary.4
18
- */
19
- export interface ServerTrackerOptions<Catalog extends EventCatalog> {
20
- catalog: Catalog;
21
- destinations: Array<Destination>;
22
- generateEventId?: () => string;
23
- maxRetries?: number;
24
- onDestinationError?: (error: unknown, destination: Destination, event: TrackedEvent) => void;
25
- retryDelayMs?: number;
26
- }
27
-
28
- /**
29
- * @since 0.5.0-canary.4
30
- */
31
- export interface ServerTracker<Catalog extends EventCatalog> {
32
- /** Explicit anonymous → known-user merge, for when `identify` timing can't do it. */
33
- alias: (previousId: string, userId: string, context: ServerTrackContext) => Promise<void>;
34
- group: (groupId: string, traits: Record<string, unknown> | undefined, context: ServerTrackContext) => Promise<void>;
35
- track: <Name extends keyof EventsOf<Catalog, "server">>(
36
- name: Name,
37
- props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>,
38
- context: ServerTrackContext,
39
- ) => Promise<void>;
40
- }
41
-
42
- function sleep(ms: number): Promise<void> {
43
- return new Promise((resolve) => {
44
- setTimeout(resolve, ms);
45
- });
46
- }
47
-
48
- async function sendWithRetry(
49
- destination: Destination,
50
- event: TrackedEvent,
51
- maxRetries: number,
52
- retryDelayMs: number,
53
- onError: (error: unknown, destination: Destination, event: TrackedEvent) => void,
54
- ): Promise<void> {
55
- for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
56
- try {
57
- await destination.send(event);
58
-
59
- return;
60
- } catch (error) {
61
- if (attempt === maxRetries) {
62
- onError(error, destination, event);
63
-
64
- return;
65
- }
66
-
67
- await sleep(retryDelayMs * 2 ** attempt);
68
- }
69
- }
70
- }
71
-
72
- /**
73
- * No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
74
- * failing after retries is only logged via `onDestinationError`, never re-queued.
75
- *
76
- * @since 0.5.0-canary.4
77
- */
78
- export function createServerTracker<Catalog extends EventCatalog>(
79
- options: ServerTrackerOptions<Catalog>,
80
- ): ServerTracker<Catalog> {
81
- const maxRetries = options.maxRetries ?? 2;
82
- const retryDelayMs = options.retryDelayMs ?? 200;
83
- const createId = options.generateEventId ?? generateEventId;
84
- const onError =
85
- options.onDestinationError ??
86
- ((error: unknown, destination: Destination, event: TrackedEvent): void => {
87
- console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
88
- });
89
-
90
- async function sendEvent(name: string, props: Record<string, unknown>, context: ServerTrackContext): Promise<void> {
91
- const event: TrackedEvent = {
92
- anonymousId: context.anonymousId,
93
- eventId: createId(),
94
- name,
95
- owner: "server",
96
- props,
97
- timestamp: Date.now(),
98
- ...(context.userId === undefined ? {} : { userId: context.userId }),
99
- };
100
-
101
- await Promise.all(
102
- options.destinations.map(async (destination) =>
103
- sendWithRetry(destination, event, maxRetries, retryDelayMs, onError),
104
- ),
105
- );
106
- }
107
-
108
- return {
109
- async alias(previousId, userId, context) {
110
- await sendEvent("$alias", { previousId, userId }, context);
111
- },
112
- async group(groupId, traits, context) {
113
- await sendEvent("$group", { groupId, ...traits }, context);
114
- },
115
- async track(name, props, context) {
116
- // noUncheckedIndexedAccess types this as possibly undefined; the owner check also
117
- // guards callers who bypass the EventsOf filter with an `as` cast.
118
- const definition = options.catalog[name];
119
-
120
- if (!definition || definition.owner !== "server") {
121
- throw new Error(`Unknown server-owned event: ${String(name)}`);
122
- }
123
-
124
- definition.schema.parse(props);
125
- await sendEvent(name as string, props as Record<string, unknown>, context);
126
- },
127
- };
128
- }