@codefast/tracking 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -0
  3. package/dist/client/consent-storage.d.mts +11 -0
  4. package/dist/client/consent-storage.mjs +27 -0
  5. package/dist/client/create-client-tracker.d.mts +27 -0
  6. package/dist/client/create-client-tracker.mjs +53 -0
  7. package/dist/client/gpc.d.mts +8 -0
  8. package/dist/client/gpc.mjs +10 -0
  9. package/dist/client/index.d.mts +8 -0
  10. package/dist/client/index.mjs +8 -0
  11. package/dist/client/lifecycle.d.mts +18 -0
  12. package/dist/client/lifecycle.mjs +28 -0
  13. package/dist/client/local-storage.d.mts +10 -0
  14. package/dist/client/local-storage.mjs +24 -0
  15. package/dist/client/queue.d.mts +42 -0
  16. package/dist/client/queue.mjs +69 -0
  17. package/dist/client/router.d.mts +26 -0
  18. package/dist/client/router.mjs +15 -0
  19. package/dist/core/consent.d.mts +37 -0
  20. package/dist/core/consent.mjs +25 -0
  21. package/dist/core/destination.d.mts +13 -0
  22. package/dist/core/destination.mjs +1 -0
  23. package/dist/core/event-catalog.d.mts +28 -0
  24. package/dist/core/event-catalog.mjs +10 -0
  25. package/dist/core/event-id.d.mts +8 -0
  26. package/dist/core/event-id.mjs +10 -0
  27. package/dist/core/index.d.mts +6 -0
  28. package/dist/core/index.mjs +4 -0
  29. package/dist/core/tracked-event.d.mts +15 -0
  30. package/dist/core/tracked-event.mjs +1 -0
  31. package/dist/destinations/http-destination.d.mts +15 -0
  32. package/dist/destinations/http-destination.mjs +23 -0
  33. package/dist/destinations/index.d.mts +3 -0
  34. package/dist/destinations/index.mjs +3 -0
  35. package/dist/destinations/vercel-analytics.d.mts +11 -0
  36. package/dist/destinations/vercel-analytics.mjs +27 -0
  37. package/dist/index.d.mts +6 -0
  38. package/dist/index.mjs +4 -0
  39. package/dist/react/consent-banner.d.mts +41 -0
  40. package/dist/react/consent-banner.mjs +42 -0
  41. package/dist/react/index.d.mts +3 -0
  42. package/dist/react/index.mjs +3 -0
  43. package/dist/react/use-consent.d.mts +24 -0
  44. package/dist/react/use-consent.mjs +31 -0
  45. package/dist/server/create-server-tracker.d.mts +28 -0
  46. package/dist/server/create-server-tracker.mjs +48 -0
  47. package/dist/server/index.d.mts +3 -0
  48. package/dist/server/index.mjs +3 -0
  49. package/dist/server/region.d.mts +16 -0
  50. package/dist/server/region.mjs +52 -0
  51. package/package.json +242 -0
  52. package/src/client/consent-storage.ts +30 -0
  53. package/src/client/create-client-tracker.ts +97 -0
  54. package/src/client/gpc.ts +11 -0
  55. package/src/client/index.ts +17 -0
  56. package/src/client/lifecycle.ts +45 -0
  57. package/src/client/local-storage.ts +29 -0
  58. package/src/client/queue.ts +110 -0
  59. package/src/client/router.ts +33 -0
  60. package/src/core/consent.ts +58 -0
  61. package/src/core/destination.ts +10 -0
  62. package/src/core/event-catalog.ts +32 -0
  63. package/src/core/event-id.ts +7 -0
  64. package/src/core/index.ts +11 -0
  65. package/src/core/tracked-event.ts +12 -0
  66. package/src/destinations/http-destination.ts +28 -0
  67. package/src/destinations/index.ts +4 -0
  68. package/src/destinations/vercel-analytics.ts +37 -0
  69. package/src/index.ts +13 -0
  70. package/src/react/consent-banner.tsx +64 -0
  71. package/src/react/index.ts +5 -0
  72. package/src/react/use-consent.ts +53 -0
  73. package/src/server/create-server-tracker.ts +105 -0
  74. package/src/server/index.ts +4 -0
  75. package/src/server/region.ts +66 -0
@@ -0,0 +1,10 @@
1
+ import type { TrackedEvent } from "#/core/tracked-event";
2
+
3
+ /**
4
+ * Fan-out target for tracked events (PostHog, GA4, a self-hosted store, ...).
5
+ * Trackers depend only on this interface, never on a specific provider SDK.
6
+ */
7
+ export interface Destination {
8
+ name: string;
9
+ send: (event: TrackedEvent) => Promise<void> | void;
10
+ }
@@ -0,0 +1,32 @@
1
+ import type { z } from "zod";
2
+
3
+ /**
4
+ * One event's Zod schema plus which side of the app is allowed to fire it.
5
+ */
6
+ export interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
7
+ owner: "client" | "server";
8
+ schema: Schema;
9
+ }
10
+
11
+ /**
12
+ * An app-defined map of event name to its definition. `@codefast/tracking` ships no
13
+ * events of its own — every consuming app builds and passes in its own catalog.
14
+ */
15
+ export type EventCatalog = Record<string, EventDefinition>;
16
+
17
+ /**
18
+ * Filters a catalog down to the events a given owner may fire. Client and server
19
+ * trackers are built from this, so calling a server-owned event from client code
20
+ * (or vice versa) is a compile-time error, not a runtime surprise.
21
+ */
22
+ export type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = {
23
+ [Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key];
24
+ };
25
+
26
+ /**
27
+ * Identity helper for declaring a catalog with inference — nicer call-site than
28
+ * `satisfies EventCatalog` when the catalog is assembled across multiple files.
29
+ */
30
+ export function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog {
31
+ return catalog;
32
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Client-owned events use this at enqueue time; server-owned events derive an ID
3
+ * from the request instead so retries of the same request don't double-count.
4
+ */
5
+ export function generateEventId(): string {
6
+ return crypto.randomUUID();
7
+ }
@@ -0,0 +1,11 @@
1
+ export type { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage } from "#/core/consent";
2
+ export { resolveConsentMode, shouldTrackByDefault } from "#/core/consent";
3
+
4
+ export type { Destination } from "#/core/destination";
5
+
6
+ export type { EventCatalog, EventDefinition, EventsOf } from "#/core/event-catalog";
7
+ export { defineEventCatalog } from "#/core/event-catalog";
8
+
9
+ export { generateEventId } from "#/core/event-id";
10
+
11
+ export type { TrackedEvent } from "#/core/tracked-event";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Envelope every tracker (client/server) builds before handing an event to a destination.
3
+ */
4
+ export interface TrackedEvent {
5
+ anonymousId: string;
6
+ eventId: string;
7
+ name: string;
8
+ owner: "client" | "server";
9
+ props: Record<string, unknown>;
10
+ timestamp: number;
11
+ userId?: string | undefined;
12
+ }
@@ -0,0 +1,28 @@
1
+ import type { Destination } from "#/core/destination";
2
+
3
+ export interface HttpDestinationOptions {
4
+ endpoint: string;
5
+ headers?: Record<string, string>;
6
+ name: string;
7
+ }
8
+
9
+ /**
10
+ * Generic fetch-based `Destination` — the building block for a real provider adapter
11
+ * (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
12
+ */
13
+ export function createHttpDestination(options: HttpDestinationOptions): Destination {
14
+ return {
15
+ name: options.name,
16
+ async send(event) {
17
+ const response = await fetch(options.endpoint, {
18
+ body: JSON.stringify(event),
19
+ headers: { "content-type": "application/json", ...options.headers },
20
+ method: "POST",
21
+ });
22
+
23
+ if (!response.ok) {
24
+ throw new Error(`"${options.name}" destination responded with ${String(response.status)}`);
25
+ }
26
+ },
27
+ };
28
+ }
@@ -0,0 +1,4 @@
1
+ export type { HttpDestinationOptions } from "#/destinations/http-destination";
2
+ export { createHttpDestination } from "#/destinations/http-destination";
3
+
4
+ export { createVercelAnalyticsDestination } from "#/destinations/vercel-analytics";
@@ -0,0 +1,37 @@
1
+ import { track } from "@vercel/analytics/react";
2
+
3
+ import type { Destination } from "#/core/destination";
4
+
5
+ type VercelAnalyticsPropertyValue = boolean | number | string | null;
6
+
7
+ /**
8
+ * Vercel's `track()` rejects nested objects/arrays outright — flatten anything else
9
+ * to a string instead of silently dropping it.
10
+ */
11
+ function toVercelAnalyticsProps(props: Record<string, unknown>): Record<string, VercelAnalyticsPropertyValue> {
12
+ const result: Record<string, VercelAnalyticsPropertyValue> = {};
13
+
14
+ for (const [key, value] of Object.entries(props)) {
15
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
16
+ result[key] = value;
17
+ } else if (value !== undefined) {
18
+ result[key] = JSON.stringify(value);
19
+ }
20
+ }
21
+
22
+ return result;
23
+ }
24
+
25
+ /**
26
+ * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`) — it
27
+ * never rejects, so this destination never triggers `EventQueue`'s retry path. Requires
28
+ * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
29
+ */
30
+ export function createVercelAnalyticsDestination(name = "vercel-analytics"): Destination {
31
+ return {
32
+ name,
33
+ send(event) {
34
+ track(event.name, toVercelAnalyticsProps(event.props));
35
+ },
36
+ };
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * \@codefast/tracking
3
+ *
4
+ * Fullstack, type-safe event tracking: apps define a Zod event catalog tagged with an
5
+ * owner ("client" | "server"), then build trackers from it that only allow firing
6
+ * events owned by that side — enforced at compile time, not by convention.
7
+ *
8
+ * - **Root** (this module): isomorphic catalog types, `Destination`, consent helpers — safe to import from both client and server code.
9
+ * - **`@codefast/tracking/client`**: `createClientTracker` — batching, offline queue, retry.
10
+ * - **`@codefast/tracking/server`**: `createServerTracker`, region detection for consent.
11
+ * - **`@codefast/tracking/destinations`**: `createHttpDestination` and the `Destination` building block.
12
+ */
13
+ export * from "#/core";
@@ -0,0 +1,64 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ import type { UseConsentResult } from "#/react/use-consent";
4
+
5
+ export interface ConsentBannerProps {
6
+ acceptLabel?: string;
7
+ className?: string;
8
+ consent: UseConsentResult;
9
+ message?: string;
10
+ rejectLabel?: string;
11
+ }
12
+
13
+ /**
14
+ * Blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
15
+ * exists or the region defaults to opt-out (`consent.needsPrompt` covers both). No
16
+ * styling is baked in; pass `className` to match the host app's design system.
17
+ */
18
+ export function ConsentBanner({
19
+ acceptLabel = "Accept",
20
+ className,
21
+ consent,
22
+ message = "We use cookies to understand how you use this site.",
23
+ rejectLabel = "Reject",
24
+ }: ConsentBannerProps): ReactNode {
25
+ if (!consent.needsPrompt) {
26
+ return null;
27
+ }
28
+
29
+ return (
30
+ <dialog aria-live="polite" className={className} open>
31
+ <p>{message}</p>
32
+ <button onClick={consent.grant} type="button">
33
+ {acceptLabel}
34
+ </button>
35
+ <button onClick={consent.deny} type="button">
36
+ {rejectLabel}
37
+ </button>
38
+ </dialog>
39
+ );
40
+ }
41
+
42
+ export interface ConsentToggleProps {
43
+ allowLabel?: string;
44
+ className?: string;
45
+ consent: UseConsentResult;
46
+ denyLabel?: string;
47
+ }
48
+
49
+ /**
50
+ * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
51
+ * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
52
+ */
53
+ export function ConsentToggle({
54
+ allowLabel = "Allow tracking",
55
+ className,
56
+ consent,
57
+ denyLabel = "Do Not Sell or Share My Personal Information",
58
+ }: ConsentToggleProps): ReactNode {
59
+ return (
60
+ <button className={className} onClick={consent.isTrackingAllowed ? consent.deny : consent.grant} type="button">
61
+ {consent.isTrackingAllowed ? denyLabel : allowLabel}
62
+ </button>
63
+ );
64
+ }
@@ -0,0 +1,5 @@
1
+ export type { ConsentBannerProps, ConsentToggleProps } from "#/react/consent-banner";
2
+ export { ConsentBanner, ConsentToggle } from "#/react/consent-banner";
3
+
4
+ export type { UseConsentOptions, UseConsentResult } from "#/react/use-consent";
5
+ export { useConsent } from "#/react/use-consent";
@@ -0,0 +1,53 @@
1
+ import { useCallback, useState } from "react";
2
+
3
+ import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
4
+ import { shouldTrackByDefault } from "#/core/consent";
5
+
6
+ export interface UseConsentOptions {
7
+ hasGlobalPrivacyControlSignal?: boolean;
8
+ mode: ConsentMode;
9
+ onDecision?: (decision: ConsentDecision) => void;
10
+ policyVersion: string;
11
+ storage: ConsentStorage;
12
+ }
13
+
14
+ export interface UseConsentResult {
15
+ deny: () => void;
16
+ grant: () => void;
17
+ isTrackingAllowed: boolean;
18
+ /** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
19
+ needsPrompt: boolean;
20
+ }
21
+
22
+ /**
23
+ * Bridges `resolveConsentMode`/`shouldTrackByDefault` (core, region-aware) to React state,
24
+ * persisting the visitor's decision via the given `ConsentStorage`.
25
+ */
26
+ export function useConsent(options: UseConsentOptions): UseConsentResult {
27
+ const [decision, setDecision] = useState<ConsentDecision | undefined>(() => options.storage.load()?.decision);
28
+
29
+ const decide = useCallback(
30
+ (next: ConsentDecision): void => {
31
+ options.storage.save({ decision: next, policyVersion: options.policyVersion, timestamp: Date.now() });
32
+ setDecision(next);
33
+ options.onDecision?.(next);
34
+ },
35
+ [options],
36
+ );
37
+
38
+ const isTrackingAllowed =
39
+ decision === undefined
40
+ ? shouldTrackByDefault(options.mode, options.hasGlobalPrivacyControlSignal ?? false)
41
+ : decision === "granted";
42
+
43
+ return {
44
+ deny: () => {
45
+ decide("denied");
46
+ },
47
+ grant: () => {
48
+ decide("granted");
49
+ },
50
+ isTrackingAllowed,
51
+ needsPrompt: options.mode === "opt-in" && decision === undefined,
52
+ };
53
+ }
@@ -0,0 +1,105 @@
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
+ export interface ServerTrackContext {
9
+ anonymousId: string;
10
+ userId?: string | undefined;
11
+ }
12
+
13
+ export interface ServerTrackerOptions<Catalog extends EventCatalog> {
14
+ catalog: Catalog;
15
+ destinations: Array<Destination>;
16
+ generateEventId?: () => string;
17
+ maxRetries?: number;
18
+ onDestinationError?: (error: unknown, destination: Destination, event: TrackedEvent) => void;
19
+ retryDelayMs?: number;
20
+ }
21
+
22
+ export interface ServerTracker<Catalog extends EventCatalog> {
23
+ track: <Name extends keyof EventsOf<Catalog, "server">>(
24
+ name: Name,
25
+ props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>,
26
+ context: ServerTrackContext,
27
+ ) => Promise<void>;
28
+ }
29
+
30
+ function sleep(ms: number): Promise<void> {
31
+ return new Promise((resolve) => {
32
+ setTimeout(resolve, ms);
33
+ });
34
+ }
35
+
36
+ async function sendWithRetry(
37
+ destination: Destination,
38
+ event: TrackedEvent,
39
+ maxRetries: number,
40
+ retryDelayMs: number,
41
+ onError: (error: unknown, destination: Destination, event: TrackedEvent) => void,
42
+ ): Promise<void> {
43
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
44
+ try {
45
+ await destination.send(event);
46
+
47
+ return;
48
+ } catch (error) {
49
+ if (attempt === maxRetries) {
50
+ onError(error, destination, event);
51
+
52
+ return;
53
+ }
54
+
55
+ await sleep(retryDelayMs * 2 ** attempt);
56
+ }
57
+ }
58
+ }
59
+
60
+ /**
61
+ * No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
62
+ * failing after retries is only logged via `onDestinationError`, never re-queued.
63
+ */
64
+ export function createServerTracker<Catalog extends EventCatalog>(
65
+ options: ServerTrackerOptions<Catalog>,
66
+ ): ServerTracker<Catalog> {
67
+ const maxRetries = options.maxRetries ?? 2;
68
+ const retryDelayMs = options.retryDelayMs ?? 200;
69
+ const createId = options.generateEventId ?? generateEventId;
70
+ const onError =
71
+ options.onDestinationError ??
72
+ ((error: unknown, destination: Destination, event: TrackedEvent): void => {
73
+ console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
74
+ });
75
+
76
+ return {
77
+ async track(name, props, context) {
78
+ // noUncheckedIndexedAccess types this as possibly undefined; the owner check also
79
+ // guards callers who bypass the EventsOf filter with an `as` cast.
80
+ const definition = options.catalog[name];
81
+
82
+ if (!definition || definition.owner !== "server") {
83
+ throw new Error(`Unknown server-owned event: ${String(name)}`);
84
+ }
85
+
86
+ definition.schema.parse(props);
87
+
88
+ const event: TrackedEvent = {
89
+ anonymousId: context.anonymousId,
90
+ eventId: createId(),
91
+ name: name as string,
92
+ owner: "server",
93
+ props: props as Record<string, unknown>,
94
+ timestamp: Date.now(),
95
+ ...(context.userId === undefined ? {} : { userId: context.userId }),
96
+ };
97
+
98
+ await Promise.all(
99
+ options.destinations.map(async (destination) =>
100
+ sendWithRetry(destination, event, maxRetries, retryDelayMs, onError),
101
+ ),
102
+ );
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,4 @@
1
+ export type { ServerTrackContext, ServerTracker, ServerTrackerOptions } from "#/server/create-server-tracker";
2
+ export { createServerTracker } from "#/server/create-server-tracker";
3
+
4
+ export { resolveRegion, resolveRegionFromCountryCode } from "#/server/region";
@@ -0,0 +1,66 @@
1
+ import type { ConsentRegion } from "#/core/consent";
2
+
3
+ const EU_COUNTRY_CODES = new Set([
4
+ "AT",
5
+ "BE",
6
+ "BG",
7
+ "HR",
8
+ "CY",
9
+ "CZ",
10
+ "DK",
11
+ "EE",
12
+ "FI",
13
+ "FR",
14
+ "DE",
15
+ "GR",
16
+ "HU",
17
+ "IE",
18
+ "IT",
19
+ "LV",
20
+ "LT",
21
+ "LU",
22
+ "MT",
23
+ "NL",
24
+ "PL",
25
+ "PT",
26
+ "RO",
27
+ "SK",
28
+ "SI",
29
+ "ES",
30
+ "SE",
31
+ ]);
32
+
33
+ /**
34
+ * Missing/unrecognized codes fall back to "other", which `resolveConsentMode` treats
35
+ * as opt-out — the least restrictive default, safe only because opt-in regions (EU/VN)
36
+ * are matched explicitly above it.
37
+ */
38
+ export function resolveRegionFromCountryCode(countryCode: string | undefined): ConsentRegion {
39
+ if (!countryCode) {
40
+ return "other";
41
+ }
42
+
43
+ const normalized = countryCode.toUpperCase();
44
+
45
+ if (EU_COUNTRY_CODES.has(normalized)) {
46
+ return "eu";
47
+ }
48
+
49
+ if (normalized === "VN") {
50
+ return "vn";
51
+ }
52
+
53
+ if (normalized === "US") {
54
+ return "us";
55
+ }
56
+
57
+ return "other";
58
+ }
59
+
60
+ /**
61
+ * Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
62
+ * the incoming request's `Headers` from server-function/middleware context.
63
+ */
64
+ export function resolveRegion(headers: Headers, headerName = "x-vercel-ip-country"): ConsentRegion {
65
+ return resolveRegionFromCountryCode(headers.get(headerName) ?? undefined);
66
+ }