@codefast/tracking 0.0.0 → 0.5.0-canary.4
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/CHANGELOG.md +38 -0
- package/README.md +46 -8
- package/dist/client/consent-storage.d.mts +11 -3
- package/dist/client/consent-storage.mjs +45 -9
- package/dist/client/create-client-tracker.d.mts +10 -0
- package/dist/client/create-client-tracker.mjs +14 -1
- package/dist/client/gpc.d.mts +2 -0
- package/dist/client/gpc.mjs +2 -0
- package/dist/client/lifecycle.d.mts +5 -0
- package/dist/client/lifecycle.mjs +2 -0
- package/dist/client/local-storage.d.mts +5 -2
- package/dist/client/local-storage.mjs +12 -5
- package/dist/client/queue.d.mts +7 -0
- package/dist/client/queue.mjs +2 -0
- package/dist/client/router.d.mts +4 -0
- package/dist/client/router.mjs +2 -0
- package/dist/core/consent.d.mts +61 -9
- package/dist/core/consent.mjs +39 -7
- package/dist/core/destination.d.mts +10 -0
- package/dist/core/event-catalog.d.mts +8 -0
- package/dist/core/event-catalog.mjs +2 -0
- package/dist/core/event-id.d.mts +2 -0
- package/dist/core/event-id.mjs +2 -0
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +2 -2
- package/dist/core/tracked-event.d.mts +2 -0
- package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
- package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
- package/dist/destinations/google-analytics.d.mts +98 -0
- package/dist/destinations/google-analytics.mjs +126 -0
- package/dist/destinations/http-destination.d.mts +5 -0
- package/dist/destinations/http-destination.mjs +2 -0
- package/dist/destinations/index.d.mts +3 -1
- package/dist/destinations/index.mjs +3 -1
- package/dist/destinations/vercel-analytics.d.mts +4 -2
- package/dist/destinations/vercel-analytics.mjs +5 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/react/consent-banner.d.mts +48 -14
- package/dist/react/consent-banner.mjs +94 -22
- package/dist/react/index.d.mts +2 -2
- package/dist/react/use-consent.d.mts +30 -5
- package/dist/react/use-consent.mjs +38 -15
- package/dist/server/create-server-tracker.d.mts +14 -0
- package/dist/server/create-server-tracker.mjs +24 -5
- package/dist/server/region.d.mts +4 -0
- package/dist/server/region.mjs +4 -0
- package/package.json +12 -2
- package/src/client/consent-storage.ts +75 -10
- package/src/client/create-client-tracker.ts +30 -1
- package/src/client/gpc.ts +2 -0
- package/src/client/lifecycle.ts +5 -0
- package/src/client/local-storage.ts +21 -6
- package/src/client/queue.ts +7 -0
- package/src/client/router.ts +4 -0
- package/src/core/consent.ts +85 -11
- package/src/core/destination.ts +10 -0
- package/src/core/event-catalog.ts +8 -0
- package/src/core/event-id.ts +2 -0
- package/src/core/index.ts +15 -2
- package/src/core/tracked-event.ts +2 -0
- package/src/destinations/ga4-measurement-protocol.ts +166 -0
- package/src/destinations/google-analytics.ts +233 -0
- package/src/destinations/http-destination.ts +5 -0
- package/src/destinations/index.ts +16 -0
- package/src/destinations/vercel-analytics.ts +5 -2
- package/src/react/consent-banner.tsx +121 -22
- package/src/react/index.ts +1 -1
- package/src/react/use-consent.ts +81 -23
- package/src/server/create-server-tracker.ts +39 -16
- package/src/server/region.ts +4 -0
|
@@ -1,27 +1,94 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CONSENT_CATEGORIES } from "../core/consent.mjs";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
2
4
|
//#region src/react/consent-banner.tsx
|
|
3
5
|
/**
|
|
4
|
-
*
|
|
5
|
-
* exists or the region defaults to opt-out (`consent.needsPrompt` covers both).
|
|
6
|
-
*
|
|
6
|
+
* Non-blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
|
|
7
|
+
* exists or the region defaults to opt-out (`consent.needsPrompt` covers both). Accept
|
|
8
|
+
* grants only the categories the app requested (`useConsent`'s `categories`), and the
|
|
9
|
+
* optional `categories` prop adds a second layer of per-category checkboxes — GDPR
|
|
10
|
+
* consent must be granular per purpose, not a single yes/no. Rendered as a labeled
|
|
11
|
+
* region, not a `<dialog>`: an open non-modal dialog neither traps focus nor blocks the
|
|
12
|
+
* page, so the dialog semantics would over-promise. No styling is baked in — target the
|
|
13
|
+
* root via `className` and the parts via their `data-slot` attributes (`consent-message`,
|
|
14
|
+
* `consent-actions`, `consent-action`, `consent-preferences`, `consent-category`).
|
|
15
|
+
*
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
7
17
|
*/
|
|
8
|
-
function ConsentBanner({ acceptLabel = "Accept",
|
|
18
|
+
function ConsentBanner({ acceptLabel = "Accept", categories, consent, customizeLabel = "Customize", message = "We use cookies to understand how you use this site.", rejectLabel = "Reject", saveLabel = "Save preferences", ...props }) {
|
|
19
|
+
const [pending, setPending] = useState(void 0);
|
|
9
20
|
if (!consent.needsPrompt) return null;
|
|
10
|
-
return /* @__PURE__ */ jsxs("
|
|
11
|
-
"aria-
|
|
12
|
-
|
|
13
|
-
|
|
21
|
+
return /* @__PURE__ */ jsxs("section", {
|
|
22
|
+
"aria-label": "Cookie consent",
|
|
23
|
+
"data-slot": "consent-banner",
|
|
24
|
+
...props,
|
|
14
25
|
children: [
|
|
15
|
-
/* @__PURE__ */ jsx("p", {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
type: "button",
|
|
19
|
-
children: acceptLabel
|
|
26
|
+
/* @__PURE__ */ jsx("p", {
|
|
27
|
+
"data-slot": "consent-message",
|
|
28
|
+
children: message
|
|
20
29
|
}),
|
|
21
|
-
/* @__PURE__ */ jsx("
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
30
|
+
pending !== void 0 && categories !== void 0 ? /* @__PURE__ */ jsx("div", {
|
|
31
|
+
"data-slot": "consent-preferences",
|
|
32
|
+
children: categories.map((option) => /* @__PURE__ */ jsxs("label", {
|
|
33
|
+
"data-slot": "consent-category",
|
|
34
|
+
children: [
|
|
35
|
+
/* @__PURE__ */ jsx("input", {
|
|
36
|
+
checked: pending[option.category],
|
|
37
|
+
"data-slot": "consent-category-checkbox",
|
|
38
|
+
onChange: (event) => {
|
|
39
|
+
setPending({
|
|
40
|
+
...pending,
|
|
41
|
+
[option.category]: event.target.checked
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
type: "checkbox"
|
|
45
|
+
}),
|
|
46
|
+
/* @__PURE__ */ jsx("span", {
|
|
47
|
+
"data-slot": "consent-category-label",
|
|
48
|
+
children: option.label
|
|
49
|
+
}),
|
|
50
|
+
option.description === void 0 ? null : /* @__PURE__ */ jsx("span", {
|
|
51
|
+
"data-slot": "consent-category-description",
|
|
52
|
+
children: option.description
|
|
53
|
+
})
|
|
54
|
+
]
|
|
55
|
+
}, option.category))
|
|
56
|
+
}) : null,
|
|
57
|
+
/* @__PURE__ */ jsx("div", {
|
|
58
|
+
"data-slot": "consent-actions",
|
|
59
|
+
children: pending === void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
60
|
+
/* @__PURE__ */ jsx("button", {
|
|
61
|
+
"data-action": "accept",
|
|
62
|
+
"data-slot": "consent-action",
|
|
63
|
+
onClick: consent.grantAll,
|
|
64
|
+
type: "button",
|
|
65
|
+
children: acceptLabel
|
|
66
|
+
}),
|
|
67
|
+
/* @__PURE__ */ jsx("button", {
|
|
68
|
+
"data-action": "reject",
|
|
69
|
+
"data-slot": "consent-action",
|
|
70
|
+
onClick: consent.denyAll,
|
|
71
|
+
type: "button",
|
|
72
|
+
children: rejectLabel
|
|
73
|
+
}),
|
|
74
|
+
categories !== void 0 && categories.length > 0 ? /* @__PURE__ */ jsx("button", {
|
|
75
|
+
"data-action": "customize",
|
|
76
|
+
"data-slot": "consent-action",
|
|
77
|
+
onClick: () => {
|
|
78
|
+
setPending(consent.effectiveConsent);
|
|
79
|
+
},
|
|
80
|
+
type: "button",
|
|
81
|
+
children: customizeLabel
|
|
82
|
+
}) : null
|
|
83
|
+
] }) : /* @__PURE__ */ jsx("button", {
|
|
84
|
+
"data-action": "save",
|
|
85
|
+
"data-slot": "consent-action",
|
|
86
|
+
onClick: () => {
|
|
87
|
+
consent.save(pending);
|
|
88
|
+
},
|
|
89
|
+
type: "button",
|
|
90
|
+
children: saveLabel
|
|
91
|
+
})
|
|
25
92
|
})
|
|
26
93
|
]
|
|
27
94
|
});
|
|
@@ -29,13 +96,18 @@ function ConsentBanner({ acceptLabel = "Accept", className, consent, message = "
|
|
|
29
96
|
/**
|
|
30
97
|
* Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
|
|
31
98
|
* "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
|
|
99
|
+
* Flips between denying everything and re-granting the app's requested categories.
|
|
100
|
+
*
|
|
101
|
+
* @since 0.5.0-canary.4
|
|
32
102
|
*/
|
|
33
|
-
function ConsentToggle({ allowLabel = "Allow tracking",
|
|
103
|
+
function ConsentToggle({ allowLabel = "Allow tracking", consent, denyLabel = "Do Not Sell or Share My Personal Information", ...props }) {
|
|
104
|
+
const anyAllowed = CONSENT_CATEGORIES.some((category) => consent.effectiveConsent[category]);
|
|
34
105
|
return /* @__PURE__ */ jsx("button", {
|
|
35
|
-
|
|
36
|
-
|
|
106
|
+
"data-slot": "consent-toggle",
|
|
107
|
+
...props,
|
|
108
|
+
onClick: anyAllowed ? consent.denyAll : consent.grantAll,
|
|
37
109
|
type: "button",
|
|
38
|
-
children:
|
|
110
|
+
children: anyAllowed ? denyLabel : allowLabel
|
|
39
111
|
});
|
|
40
112
|
}
|
|
41
113
|
//#endregion
|
package/dist/react/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { UseConsentOptions, UseConsentResult, useConsent } from "./use-consent.mjs";
|
|
2
|
-
import { ConsentBanner, ConsentBannerProps, ConsentToggle, ConsentToggleProps } from "./consent-banner.mjs";
|
|
3
|
-
export { ConsentBanner, type ConsentBannerProps, ConsentToggle, type ConsentToggleProps, type UseConsentOptions, type UseConsentResult, useConsent };
|
|
2
|
+
import { ConsentBanner, ConsentBannerProps, ConsentCategoryOption, ConsentToggle, ConsentToggleProps } from "./consent-banner.mjs";
|
|
3
|
+
export { ConsentBanner, type ConsentBannerProps, type ConsentCategoryOption, ConsentToggle, type ConsentToggleProps, type UseConsentOptions, type UseConsentResult, useConsent };
|
|
@@ -1,23 +1,48 @@
|
|
|
1
|
-
import { ConsentDecision, ConsentMode, ConsentStorage } from "../core/consent.mjs";
|
|
1
|
+
import { ConsentCategory, ConsentDecision, ConsentMode, ConsentStorage } from "../core/consent.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/react/use-consent.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* @since 0.5.0-canary.4
|
|
6
|
+
*/
|
|
4
7
|
interface UseConsentOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Categories the app's prompt actually asks about — `grantAll` grants exactly these,
|
|
10
|
+
* so an analytics-only banner can never grant ads consent it never asked for.
|
|
11
|
+
* Defaults to `["analytics"]`.
|
|
12
|
+
*/
|
|
13
|
+
categories?: ReadonlyArray<ConsentCategory>;
|
|
5
14
|
hasGlobalPrivacyControlSignal?: boolean;
|
|
6
15
|
mode: ConsentMode;
|
|
7
16
|
onDecision?: (decision: ConsentDecision) => void;
|
|
8
17
|
policyVersion: string;
|
|
18
|
+
/** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
|
|
9
19
|
storage: ConsentStorage;
|
|
10
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* @since 0.5.0-canary.4
|
|
23
|
+
*/
|
|
11
24
|
interface UseConsentResult {
|
|
12
|
-
|
|
13
|
-
|
|
25
|
+
/** The stored decision under the current policy version — `undefined` until the visitor makes one. */
|
|
26
|
+
decision: ConsentDecision | undefined;
|
|
27
|
+
denyAll: () => void;
|
|
28
|
+
/** What tags must obey right now — the stored decision, or the region default before one exists. */
|
|
29
|
+
effectiveConsent: ConsentDecision;
|
|
30
|
+
grantAll: () => void;
|
|
31
|
+
/** Effective `analytics` consent — gates this package's own tracker pipeline. */
|
|
14
32
|
isTrackingAllowed: boolean;
|
|
15
33
|
/** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
|
|
16
34
|
needsPrompt: boolean;
|
|
35
|
+
/** Persist a granular per-category choice, e.g. from a preferences panel. */
|
|
36
|
+
save: (decision: ConsentDecision) => void;
|
|
17
37
|
}
|
|
18
38
|
/**
|
|
19
|
-
* Bridges `resolveConsentMode`/`
|
|
20
|
-
*
|
|
39
|
+
* Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
|
|
40
|
+
* `useSyncExternalStore`: the stored record is the single source of truth, hydration is
|
|
41
|
+
* safe by construction (the server snapshot is always "no decision yet", matching what
|
|
42
|
+
* prerendered HTML could know), and a decision made in another tab syncs through the
|
|
43
|
+
* storage subscription.
|
|
44
|
+
*
|
|
45
|
+
* @since 0.5.0-canary.4
|
|
21
46
|
*/
|
|
22
47
|
declare function useConsent(options: UseConsentOptions): UseConsentResult;
|
|
23
48
|
//#endregion
|
|
@@ -1,30 +1,53 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveDefaultConsent } from "../core/consent.mjs";
|
|
2
|
+
import { useRef, useSyncExternalStore } from "react";
|
|
3
3
|
//#region src/react/use-consent.ts
|
|
4
|
+
const DEFAULT_CATEGORIES = ["analytics"];
|
|
4
5
|
/**
|
|
5
|
-
* Bridges `resolveConsentMode`/`
|
|
6
|
-
*
|
|
6
|
+
* Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
|
|
7
|
+
* `useSyncExternalStore`: the stored record is the single source of truth, hydration is
|
|
8
|
+
* safe by construction (the server snapshot is always "no decision yet", matching what
|
|
9
|
+
* prerendered HTML could know), and a decision made in another tab syncs through the
|
|
10
|
+
* storage subscription.
|
|
11
|
+
*
|
|
12
|
+
* @since 0.5.0-canary.4
|
|
7
13
|
*/
|
|
8
14
|
function useConsent(options) {
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
15
|
+
const { storage } = options;
|
|
16
|
+
const categories = options.categories ?? DEFAULT_CATEGORIES;
|
|
17
|
+
const cachedDecision = useRef(void 0);
|
|
18
|
+
const decision = useSyncExternalStore(storage.subscribe, () => {
|
|
19
|
+
const record = storage.load();
|
|
20
|
+
if (record?.policyVersion !== options.policyVersion || !isConsentDecision(record.decision)) {
|
|
21
|
+
cachedDecision.current = void 0;
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const stored = record.decision;
|
|
25
|
+
const cached = cachedDecision.current;
|
|
26
|
+
if (cached !== void 0 && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) return cached;
|
|
27
|
+
cachedDecision.current = createConsentDecision(CONSENT_CATEGORIES.filter((category) => stored[category]));
|
|
28
|
+
return cachedDecision.current;
|
|
29
|
+
}, () => void 0);
|
|
30
|
+
function save(next) {
|
|
31
|
+
storage.save({
|
|
12
32
|
decision: next,
|
|
13
33
|
policyVersion: options.policyVersion,
|
|
14
34
|
timestamp: Date.now()
|
|
15
35
|
});
|
|
16
|
-
setDecision(next);
|
|
17
36
|
options.onDecision?.(next);
|
|
18
|
-
}
|
|
37
|
+
}
|
|
38
|
+
const effectiveConsent = decision ?? resolveDefaultConsent(options.mode, categories, options.hasGlobalPrivacyControlSignal ?? false);
|
|
19
39
|
return {
|
|
20
|
-
|
|
21
|
-
|
|
40
|
+
decision,
|
|
41
|
+
denyAll: () => {
|
|
42
|
+
save(createConsentDecision([]));
|
|
22
43
|
},
|
|
23
|
-
|
|
24
|
-
|
|
44
|
+
effectiveConsent,
|
|
45
|
+
grantAll: () => {
|
|
46
|
+
save(createConsentDecision(categories));
|
|
25
47
|
},
|
|
26
|
-
isTrackingAllowed:
|
|
27
|
-
needsPrompt: options.mode === "opt-in" && decision === void 0
|
|
48
|
+
isTrackingAllowed: effectiveConsent.analytics,
|
|
49
|
+
needsPrompt: options.mode === "opt-in" && decision === void 0,
|
|
50
|
+
save
|
|
28
51
|
};
|
|
29
52
|
}
|
|
30
53
|
//#endregion
|
|
@@ -4,10 +4,16 @@ import { EventCatalog, EventsOf } from "../core/event-catalog.mjs";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
|
|
6
6
|
//#region src/server/create-server-tracker.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* @since 0.5.0-canary.4
|
|
9
|
+
*/
|
|
7
10
|
interface ServerTrackContext {
|
|
8
11
|
anonymousId: string;
|
|
9
12
|
userId?: string | undefined;
|
|
10
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* @since 0.5.0-canary.4
|
|
16
|
+
*/
|
|
11
17
|
interface ServerTrackerOptions<Catalog extends EventCatalog> {
|
|
12
18
|
catalog: Catalog;
|
|
13
19
|
destinations: Array<Destination>;
|
|
@@ -16,12 +22,20 @@ interface ServerTrackerOptions<Catalog extends EventCatalog> {
|
|
|
16
22
|
onDestinationError?: (error: unknown, destination: Destination, event: TrackedEvent) => void;
|
|
17
23
|
retryDelayMs?: number;
|
|
18
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* @since 0.5.0-canary.4
|
|
27
|
+
*/
|
|
19
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>;
|
|
20
32
|
track: <Name extends keyof EventsOf<Catalog, "server">>(name: Name, props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>, context: ServerTrackContext) => Promise<void>;
|
|
21
33
|
}
|
|
22
34
|
/**
|
|
23
35
|
* No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
|
|
24
36
|
* failing after retries is only logged via `onDestinationError`, never re-queued.
|
|
37
|
+
*
|
|
38
|
+
* @since 0.5.0-canary.4
|
|
25
39
|
*/
|
|
26
40
|
declare function createServerTracker<Catalog extends EventCatalog>(options: ServerTrackerOptions<Catalog>): ServerTracker<Catalog>;
|
|
27
41
|
//#endregion
|
|
@@ -20,6 +20,8 @@ async function sendWithRetry(destination, event, maxRetries, retryDelayMs, onErr
|
|
|
20
20
|
/**
|
|
21
21
|
* No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
|
|
22
22
|
* failing after retries is only logged via `onDestinationError`, never re-queued.
|
|
23
|
+
*
|
|
24
|
+
* @since 0.5.0-canary.4
|
|
23
25
|
*/
|
|
24
26
|
function createServerTracker(options) {
|
|
25
27
|
const maxRetries = options.maxRetries ?? 2;
|
|
@@ -28,10 +30,7 @@ function createServerTracker(options) {
|
|
|
28
30
|
const onError = options.onDestinationError ?? ((error, destination, event) => {
|
|
29
31
|
console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
|
|
30
32
|
});
|
|
31
|
-
|
|
32
|
-
const definition = options.catalog[name];
|
|
33
|
-
if (!definition || definition.owner !== "server") throw new Error(`Unknown server-owned event: ${String(name)}`);
|
|
34
|
-
definition.schema.parse(props);
|
|
33
|
+
async function sendEvent(name, props, context) {
|
|
35
34
|
const event = {
|
|
36
35
|
anonymousId: context.anonymousId,
|
|
37
36
|
eventId: createId(),
|
|
@@ -42,7 +41,27 @@ function createServerTracker(options) {
|
|
|
42
41
|
...context.userId === void 0 ? {} : { userId: context.userId }
|
|
43
42
|
};
|
|
44
43
|
await Promise.all(options.destinations.map(async (destination) => sendWithRetry(destination, event, maxRetries, retryDelayMs, onError)));
|
|
45
|
-
}
|
|
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
|
+
};
|
|
46
65
|
}
|
|
47
66
|
//#endregion
|
|
48
67
|
export { createServerTracker };
|
package/dist/server/region.d.mts
CHANGED
|
@@ -5,11 +5,15 @@ import { ConsentRegion } from "../core/consent.mjs";
|
|
|
5
5
|
* Missing/unrecognized codes fall back to "other", which `resolveConsentMode` treats
|
|
6
6
|
* as opt-out — the least restrictive default, safe only because opt-in regions (EU/VN)
|
|
7
7
|
* are matched explicitly above it.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
8
10
|
*/
|
|
9
11
|
declare function resolveRegionFromCountryCode(countryCode: string | undefined): ConsentRegion;
|
|
10
12
|
/**
|
|
11
13
|
* Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
|
|
12
14
|
* the incoming request's `Headers` from server-function/middleware context.
|
|
15
|
+
*
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
13
17
|
*/
|
|
14
18
|
declare function resolveRegion(headers: Headers, headerName?: string): ConsentRegion;
|
|
15
19
|
//#endregion
|
package/dist/server/region.mjs
CHANGED
|
@@ -32,6 +32,8 @@ const EU_COUNTRY_CODES = /* @__PURE__ */ new Set([
|
|
|
32
32
|
* Missing/unrecognized codes fall back to "other", which `resolveConsentMode` treats
|
|
33
33
|
* as opt-out — the least restrictive default, safe only because opt-in regions (EU/VN)
|
|
34
34
|
* are matched explicitly above it.
|
|
35
|
+
*
|
|
36
|
+
* @since 0.5.0-canary.4
|
|
35
37
|
*/
|
|
36
38
|
function resolveRegionFromCountryCode(countryCode) {
|
|
37
39
|
if (!countryCode) return "other";
|
|
@@ -44,6 +46,8 @@ function resolveRegionFromCountryCode(countryCode) {
|
|
|
44
46
|
/**
|
|
45
47
|
* Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
|
|
46
48
|
* the incoming request's `Headers` from server-function/middleware context.
|
|
49
|
+
*
|
|
50
|
+
* @since 0.5.0-canary.4
|
|
47
51
|
*/
|
|
48
52
|
function resolveRegion(headers, headerName = "x-vercel-ip-country") {
|
|
49
53
|
return resolveRegionFromCountryCode(headers.get(headerName) ?? void 0);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codefast/tracking",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.5.0-canary.4",
|
|
4
4
|
"description": "Fullstack, type-safe event tracking for TanStack Start — isomorphic client/server trackers over a per-app Zod event catalog",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"analytics",
|
|
@@ -131,6 +131,16 @@
|
|
|
131
131
|
"types": "./dist/destinations/index.d.mts",
|
|
132
132
|
"import": "./dist/destinations/index.mjs"
|
|
133
133
|
},
|
|
134
|
+
"./destinations/ga4-measurement-protocol": {
|
|
135
|
+
"source": "./src/destinations/ga4-measurement-protocol.ts",
|
|
136
|
+
"types": "./dist/destinations/ga4-measurement-protocol.d.mts",
|
|
137
|
+
"import": "./dist/destinations/ga4-measurement-protocol.mjs"
|
|
138
|
+
},
|
|
139
|
+
"./destinations/google-analytics": {
|
|
140
|
+
"source": "./src/destinations/google-analytics.ts",
|
|
141
|
+
"types": "./dist/destinations/google-analytics.d.mts",
|
|
142
|
+
"import": "./dist/destinations/google-analytics.mjs"
|
|
143
|
+
},
|
|
134
144
|
"./destinations/http-destination": {
|
|
135
145
|
"source": "./src/destinations/http-destination.ts",
|
|
136
146
|
"types": "./dist/destinations/http-destination.d.mts",
|
|
@@ -198,7 +208,7 @@
|
|
|
198
208
|
"tsdown": "^0.22.3",
|
|
199
209
|
"typescript": "^6.0.3",
|
|
200
210
|
"vitest": "^4.1.9",
|
|
201
|
-
"@codefast/typescript-config": "0.5.0-canary.
|
|
211
|
+
"@codefast/typescript-config": "0.5.0-canary.4"
|
|
202
212
|
},
|
|
203
213
|
"peerDependencies": {
|
|
204
214
|
"@types/react": ">=19.0.0",
|
|
@@ -1,30 +1,95 @@
|
|
|
1
1
|
import type { ConsentRecord, ConsentStorage } from "#/core/consent";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* `localStorage`-backed consent storage
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
|
|
5
|
+
* `window` (SSR) degrades to an in-memory record — the visitor's decision still applies
|
|
6
|
+
* for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
|
|
7
|
+
* writes and, via the `storage` event, for decisions made in other tabs.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
|
|
11
|
+
* pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
|
|
12
|
+
* decision synchronously before any tag fires.
|
|
13
|
+
*
|
|
14
|
+
* @since 0.5.0-canary.4
|
|
7
15
|
*/
|
|
8
16
|
export function createLocalStorageConsentStorage(storageKey: string): ConsentStorage {
|
|
17
|
+
const listeners = new Set<() => void>();
|
|
18
|
+
let memoryRecord: ConsentRecord | undefined;
|
|
19
|
+
|
|
20
|
+
function notify(): void {
|
|
21
|
+
for (const listener of listeners) {
|
|
22
|
+
listener();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
return {
|
|
10
27
|
clear(): void {
|
|
11
|
-
|
|
28
|
+
if (typeof globalThis.window === "undefined") {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
memoryRecord = undefined;
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
globalThis.window.localStorage.removeItem(storageKey);
|
|
36
|
+
} catch {
|
|
37
|
+
/* storage blocked (private mode / quota) */
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
notify();
|
|
12
41
|
},
|
|
13
42
|
load(): ConsentRecord | undefined {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (!raw) {
|
|
43
|
+
if (typeof globalThis.window === "undefined") {
|
|
17
44
|
return undefined;
|
|
18
45
|
}
|
|
19
46
|
|
|
20
47
|
try {
|
|
21
|
-
|
|
48
|
+
const raw = globalThis.window.localStorage.getItem(storageKey);
|
|
49
|
+
|
|
50
|
+
return raw ? (JSON.parse(raw) as ConsentRecord) : memoryRecord;
|
|
22
51
|
} catch {
|
|
23
|
-
return
|
|
52
|
+
return memoryRecord;
|
|
24
53
|
}
|
|
25
54
|
},
|
|
26
55
|
save(record: ConsentRecord): void {
|
|
27
|
-
|
|
56
|
+
if (typeof globalThis.window === "undefined") {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
|
|
62
|
+
// localStorage is authoritative now — a lingering memory copy would shadow an
|
|
63
|
+
// external clear (e.g. the visitor wiping site data).
|
|
64
|
+
memoryRecord = undefined;
|
|
65
|
+
} catch {
|
|
66
|
+
// Storage blocked (private mode / quota) — keep the decision for this session.
|
|
67
|
+
memoryRecord = record;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
notify();
|
|
71
|
+
},
|
|
72
|
+
subscribe(listener: () => void): () => void {
|
|
73
|
+
listeners.add(listener);
|
|
74
|
+
|
|
75
|
+
// The `storage` event only fires in *other* tabs; same-tab writes go through notify().
|
|
76
|
+
function handleStorageEvent(event: StorageEvent): void {
|
|
77
|
+
if (event.key === null || event.key === storageKey) {
|
|
78
|
+
listener();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (typeof globalThis.window !== "undefined") {
|
|
83
|
+
globalThis.window.addEventListener("storage", handleStorageEvent);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return () => {
|
|
87
|
+
listeners.delete(listener);
|
|
88
|
+
|
|
89
|
+
if (typeof globalThis.window !== "undefined") {
|
|
90
|
+
globalThis.window.removeEventListener("storage", handleStorageEvent);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
28
93
|
},
|
|
29
94
|
};
|
|
30
95
|
}
|
|
@@ -6,6 +6,9 @@ import type { EventCatalog, EventsOf } from "#/core/event-catalog";
|
|
|
6
6
|
import { generateEventId } from "#/core/event-id";
|
|
7
7
|
import type { TrackedEvent } from "#/core/tracked-event";
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* @since 0.5.0-canary.4
|
|
11
|
+
*/
|
|
9
12
|
export interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
10
13
|
anonymousId: string;
|
|
11
14
|
catalog: Catalog;
|
|
@@ -15,12 +18,16 @@ export interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
|
15
18
|
storage: EventQueueStorage;
|
|
16
19
|
}
|
|
17
20
|
|
|
21
|
+
/**
|
|
22
|
+
* @since 0.5.0-canary.4
|
|
23
|
+
*/
|
|
18
24
|
export interface ClientTracker<Catalog extends EventCatalog> {
|
|
19
25
|
/** Drops every pending event without sending it — call this when consent is revoked. */
|
|
20
26
|
clear: () => void;
|
|
21
27
|
flush: () => Promise<void>;
|
|
22
28
|
/** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
|
|
23
29
|
flushWithBeacon: (endpoint: string) => void;
|
|
30
|
+
group: (groupId: string, traits?: Record<string, unknown>) => void;
|
|
24
31
|
identify: (userId: string, traits?: Record<string, unknown>) => void;
|
|
25
32
|
page: (name?: string, props?: Record<string, unknown>) => void;
|
|
26
33
|
track: <Name extends keyof EventsOf<Catalog, "client">>(
|
|
@@ -29,11 +36,18 @@ export interface ClientTracker<Catalog extends EventCatalog> {
|
|
|
29
36
|
) => void;
|
|
30
37
|
}
|
|
31
38
|
|
|
39
|
+
/**
|
|
40
|
+
* @since 0.5.0-canary.4
|
|
41
|
+
*/
|
|
32
42
|
export function createClientTracker<Catalog extends EventCatalog>(
|
|
33
43
|
options: ClientTrackerOptions<Catalog>,
|
|
34
44
|
): ClientTracker<Catalog> {
|
|
45
|
+
// SDK-backed destinations own their batching/unload delivery — routing them through
|
|
46
|
+
// the queue would only delay events and replay stale ones next session.
|
|
47
|
+
const immediateDestinations = options.destinations.filter((destination) => destination.delivery === "immediate");
|
|
48
|
+
const queuedDestinations = options.destinations.filter((destination) => destination.delivery !== "immediate");
|
|
35
49
|
const queue = new EventQueue({
|
|
36
|
-
destinations:
|
|
50
|
+
destinations: queuedDestinations,
|
|
37
51
|
maxQueueSize: options.maxQueueSize,
|
|
38
52
|
maxRetries: options.maxRetries,
|
|
39
53
|
storage: options.storage,
|
|
@@ -51,6 +65,18 @@ export function createClientTracker<Catalog extends EventCatalog>(
|
|
|
51
65
|
...(userId === undefined ? {} : { userId }),
|
|
52
66
|
};
|
|
53
67
|
|
|
68
|
+
for (const destination of immediateDestinations) {
|
|
69
|
+
try {
|
|
70
|
+
void Promise.resolve(destination.send(envelope)).catch(() => {
|
|
71
|
+
/* an immediate destination owns its transport — no retry path here */
|
|
72
|
+
});
|
|
73
|
+
} catch {
|
|
74
|
+
/* a sync throw must never break the tracked interaction */
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Still enqueued unconditionally — the queue also feeds `flushWithBeacon`, which
|
|
79
|
+
// ships raw envelopes to a custom endpoint independently of any destination.
|
|
54
80
|
queue.enqueue(envelope);
|
|
55
81
|
}
|
|
56
82
|
|
|
@@ -74,6 +100,9 @@ export function createClientTracker<Catalog extends EventCatalog>(
|
|
|
74
100
|
}
|
|
75
101
|
}
|
|
76
102
|
},
|
|
103
|
+
group(groupId, traits = {}) {
|
|
104
|
+
enqueue("$group", { groupId, ...traits });
|
|
105
|
+
},
|
|
77
106
|
identify(id, traits = {}) {
|
|
78
107
|
userId = id;
|
|
79
108
|
enqueue("$identify", traits);
|
package/src/client/gpc.ts
CHANGED
|
@@ -5,6 +5,8 @@ interface NavigatorWithGpc extends Navigator {
|
|
|
5
5
|
/**
|
|
6
6
|
* Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
|
|
7
7
|
* CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
8
10
|
*/
|
|
9
11
|
export function hasGlobalPrivacyControlSignal(): boolean {
|
|
10
12
|
return (navigator as NavigatorWithGpc).globalPrivacyControl === true;
|
package/src/client/lifecycle.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import type { ClientTracker } from "#/client/create-client-tracker";
|
|
2
2
|
import type { EventCatalog } from "#/core/event-catalog";
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* @since 0.5.0-canary.4
|
|
6
|
+
*/
|
|
4
7
|
export interface ClientLifecycleOptions {
|
|
5
8
|
/** `sendBeacon` target used on unload — omit to skip the unload flush entirely. */
|
|
6
9
|
beaconEndpoint?: string;
|
|
@@ -12,6 +15,8 @@ export interface ClientLifecycleOptions {
|
|
|
12
15
|
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
13
16
|
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
14
17
|
* Returns a cleanup function to remove all listeners/timers.
|
|
18
|
+
*
|
|
19
|
+
* @since 0.5.0-canary.4
|
|
15
20
|
*/
|
|
16
21
|
export function attachClientLifecycle<Catalog extends EventCatalog>(
|
|
17
22
|
tracker: Pick<ClientTracker<Catalog>, "flush" | "flushWithBeacon">,
|