@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.
- package/LICENSE +21 -0
- package/README.md +90 -0
- package/dist/client/consent-storage.d.mts +11 -0
- package/dist/client/consent-storage.mjs +27 -0
- package/dist/client/create-client-tracker.d.mts +27 -0
- package/dist/client/create-client-tracker.mjs +53 -0
- package/dist/client/gpc.d.mts +8 -0
- package/dist/client/gpc.mjs +10 -0
- package/dist/client/index.d.mts +8 -0
- package/dist/client/index.mjs +8 -0
- package/dist/client/lifecycle.d.mts +18 -0
- package/dist/client/lifecycle.mjs +28 -0
- package/dist/client/local-storage.d.mts +10 -0
- package/dist/client/local-storage.mjs +24 -0
- package/dist/client/queue.d.mts +42 -0
- package/dist/client/queue.mjs +69 -0
- package/dist/client/router.d.mts +26 -0
- package/dist/client/router.mjs +15 -0
- package/dist/core/consent.d.mts +37 -0
- package/dist/core/consent.mjs +25 -0
- package/dist/core/destination.d.mts +13 -0
- package/dist/core/destination.mjs +1 -0
- package/dist/core/event-catalog.d.mts +28 -0
- package/dist/core/event-catalog.mjs +10 -0
- package/dist/core/event-id.d.mts +8 -0
- package/dist/core/event-id.mjs +10 -0
- package/dist/core/index.d.mts +6 -0
- package/dist/core/index.mjs +4 -0
- package/dist/core/tracked-event.d.mts +15 -0
- package/dist/core/tracked-event.mjs +1 -0
- package/dist/destinations/http-destination.d.mts +15 -0
- package/dist/destinations/http-destination.mjs +23 -0
- package/dist/destinations/index.d.mts +3 -0
- package/dist/destinations/index.mjs +3 -0
- package/dist/destinations/vercel-analytics.d.mts +11 -0
- package/dist/destinations/vercel-analytics.mjs +27 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.mjs +4 -0
- package/dist/react/consent-banner.d.mts +41 -0
- package/dist/react/consent-banner.mjs +42 -0
- package/dist/react/index.d.mts +3 -0
- package/dist/react/index.mjs +3 -0
- package/dist/react/use-consent.d.mts +24 -0
- package/dist/react/use-consent.mjs +31 -0
- package/dist/server/create-server-tracker.d.mts +28 -0
- package/dist/server/create-server-tracker.mjs +48 -0
- package/dist/server/index.d.mts +3 -0
- package/dist/server/index.mjs +3 -0
- package/dist/server/region.d.mts +16 -0
- package/dist/server/region.mjs +52 -0
- package/package.json +242 -0
- package/src/client/consent-storage.ts +30 -0
- package/src/client/create-client-tracker.ts +97 -0
- package/src/client/gpc.ts +11 -0
- package/src/client/index.ts +17 -0
- package/src/client/lifecycle.ts +45 -0
- package/src/client/local-storage.ts +29 -0
- package/src/client/queue.ts +110 -0
- package/src/client/router.ts +33 -0
- package/src/core/consent.ts +58 -0
- package/src/core/destination.ts +10 -0
- package/src/core/event-catalog.ts +32 -0
- package/src/core/event-id.ts +7 -0
- package/src/core/index.ts +11 -0
- package/src/core/tracked-event.ts +12 -0
- package/src/destinations/http-destination.ts +28 -0
- package/src/destinations/index.ts +4 -0
- package/src/destinations/vercel-analytics.ts +37 -0
- package/src/index.ts +13 -0
- package/src/react/consent-banner.tsx +64 -0
- package/src/react/index.ts +5 -0
- package/src/react/use-consent.ts +53 -0
- package/src/server/create-server-tracker.ts +105 -0
- package/src/server/index.ts +4 -0
- package/src/server/region.ts +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 CodeFast Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# @codefast/tracking
|
|
2
|
+
|
|
3
|
+
Fullstack, type-safe event tracking for TanStack Start apps. Each app defines its own Zod
|
|
4
|
+
event catalog tagged with an owner (`"client"` or `"server"`); trackers built from that
|
|
5
|
+
catalog only allow firing events owned by that side — enforced at compile time.
|
|
6
|
+
|
|
7
|
+
See [SPEC.md](./SPEC.md) for the full design (identity correlation, offline queue/retry,
|
|
8
|
+
multi-destination fan-out, region-based consent).
|
|
9
|
+
|
|
10
|
+
## Status
|
|
11
|
+
|
|
12
|
+
Early scaffold. `core`, `client`, `server`, and `react` (headless consent) implement the
|
|
13
|
+
shapes described in the spec. Vendor-specific destinations (PostHog, GA4) are not built
|
|
14
|
+
yet — use `createHttpDestination` or implement the `Destination` interface directly.
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { defineEventCatalog } from "@codefast/tracking";
|
|
20
|
+
import { createClientTracker, createLocalStorageQueueStorage } from "@codefast/tracking/client";
|
|
21
|
+
import { createHttpDestination } from "@codefast/tracking/destinations";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
|
|
24
|
+
export const catalog = defineEventCatalog({
|
|
25
|
+
button_clicked: { owner: "client", schema: z.object({ id: z.string() }) },
|
|
26
|
+
order_completed: { owner: "server", schema: z.object({ orderId: z.string(), amount: z.number() }) },
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const tracker = createClientTracker({
|
|
30
|
+
anonymousId: crypto.randomUUID(),
|
|
31
|
+
catalog,
|
|
32
|
+
destinations: [createHttpDestination({ name: "internal", endpoint: "/api/events" })],
|
|
33
|
+
storage: createLocalStorageQueueStorage("tracking-queue"),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
tracker.track("button_clicked", { id: "cta" });
|
|
37
|
+
// tracker.track("order_completed", { orderId: "o1", amount: 10 }); // compile error — server-owned
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { createServerTracker } from "@codefast/tracking/server";
|
|
42
|
+
|
|
43
|
+
const serverTracker = createServerTracker({
|
|
44
|
+
catalog,
|
|
45
|
+
destinations: [
|
|
46
|
+
/* ... */
|
|
47
|
+
],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
await serverTracker.track("order_completed", { orderId: "o1", amount: 10 }, { anonymousId, userId });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Router page views + unload flush
|
|
54
|
+
|
|
55
|
+
`attachRouterPageTracking` is duck-typed against `Router["subscribe"]`, so it takes a real
|
|
56
|
+
`@tanstack/react-router` instance without this package depending on it. `attachClientLifecycle`
|
|
57
|
+
wires the periodic flush and the `sendBeacon` unload flush — `EventQueue` itself already
|
|
58
|
+
auto-flushes once a batch hits its size threshold.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { attachClientLifecycle, attachRouterPageTracking } from "@codefast/tracking/client";
|
|
62
|
+
|
|
63
|
+
attachRouterPageTracking(tracker, router); // router: your app's TanStack Router instance
|
|
64
|
+
attachClientLifecycle(tracker, { beaconEndpoint: "/api/events", flushIntervalMs: 10_000 });
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Consent (region-based)
|
|
68
|
+
|
|
69
|
+
Resolve the region/mode server-side (`resolveRegion` + `resolveConsentMode` from
|
|
70
|
+
`@codefast/tracking/server` and `@codefast/tracking`) and pass `mode` down to the client.
|
|
71
|
+
`ConsentBanner`/`ConsentToggle` are headless — no `@codefast/ui` dependency, style them
|
|
72
|
+
with your own `className`.
|
|
73
|
+
|
|
74
|
+
```tsx
|
|
75
|
+
import { createLocalStorageConsentStorage } from "@codefast/tracking/client";
|
|
76
|
+
import { ConsentBanner, ConsentToggle, useConsent } from "@codefast/tracking/react";
|
|
77
|
+
|
|
78
|
+
function ConsentGate({ mode }: { mode: "opt-in" | "opt-out" }) {
|
|
79
|
+
const consent = useConsent({
|
|
80
|
+
mode,
|
|
81
|
+
onDecision: (decision) => {
|
|
82
|
+
if (decision === "denied") tracker.clear(); // stop tracking + drop the pending queue
|
|
83
|
+
},
|
|
84
|
+
policyVersion: "2026-01",
|
|
85
|
+
storage: createLocalStorageConsentStorage("tracking-consent"),
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
return mode === "opt-in" ? <ConsentBanner consent={consent} /> : <ConsentToggle consent={consent} />;
|
|
89
|
+
}
|
|
90
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ConsentStorage } from "../core/consent.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/client/consent-storage.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* `localStorage`-backed consent storage — corrupt/missing state is treated as "no
|
|
6
|
+
* decision yet" rather than thrown, so a storage glitch degrades to re-prompting for
|
|
7
|
+
* consent instead of crashing the app.
|
|
8
|
+
*/
|
|
9
|
+
declare function createLocalStorageConsentStorage(storageKey: string): ConsentStorage;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { createLocalStorageConsentStorage };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
//#region src/client/consent-storage.ts
|
|
2
|
+
/**
|
|
3
|
+
* `localStorage`-backed consent storage — corrupt/missing state is treated as "no
|
|
4
|
+
* decision yet" rather than thrown, so a storage glitch degrades to re-prompting for
|
|
5
|
+
* consent instead of crashing the app.
|
|
6
|
+
*/
|
|
7
|
+
function createLocalStorageConsentStorage(storageKey) {
|
|
8
|
+
return {
|
|
9
|
+
clear() {
|
|
10
|
+
localStorage.removeItem(storageKey);
|
|
11
|
+
},
|
|
12
|
+
load() {
|
|
13
|
+
const raw = localStorage.getItem(storageKey);
|
|
14
|
+
if (!raw) return;
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(raw);
|
|
17
|
+
} catch {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
save(record) {
|
|
22
|
+
localStorage.setItem(storageKey, JSON.stringify(record));
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { createLocalStorageConsentStorage };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Destination } from "../core/destination.mjs";
|
|
2
|
+
import { EventQueueStorage } from "./queue.mjs";
|
|
3
|
+
import { EventCatalog, EventsOf } from "../core/event-catalog.mjs";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
//#region src/client/create-client-tracker.d.ts
|
|
7
|
+
interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
8
|
+
anonymousId: string;
|
|
9
|
+
catalog: Catalog;
|
|
10
|
+
destinations: Array<Destination>;
|
|
11
|
+
maxQueueSize?: number;
|
|
12
|
+
maxRetries?: number;
|
|
13
|
+
storage: EventQueueStorage;
|
|
14
|
+
}
|
|
15
|
+
interface ClientTracker<Catalog extends EventCatalog> {
|
|
16
|
+
/** Drops every pending event without sending it — call this when consent is revoked. */
|
|
17
|
+
clear: () => void;
|
|
18
|
+
flush: () => Promise<void>;
|
|
19
|
+
/** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
|
|
20
|
+
flushWithBeacon: (endpoint: string) => void;
|
|
21
|
+
identify: (userId: string, traits?: Record<string, unknown>) => void;
|
|
22
|
+
page: (name?: string, props?: Record<string, unknown>) => void;
|
|
23
|
+
track: <Name extends keyof EventsOf<Catalog, "client">>(name: Name, props: z.infer<EventsOf<Catalog, "client">[Name]["schema"]>) => void;
|
|
24
|
+
}
|
|
25
|
+
declare function createClientTracker<Catalog extends EventCatalog>(options: ClientTrackerOptions<Catalog>): ClientTracker<Catalog>;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { ClientTracker, ClientTrackerOptions, createClientTracker };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { generateEventId } from "../core/event-id.mjs";
|
|
2
|
+
import { EventQueue } from "./queue.mjs";
|
|
3
|
+
//#region src/client/create-client-tracker.ts
|
|
4
|
+
function createClientTracker(options) {
|
|
5
|
+
const queue = new EventQueue({
|
|
6
|
+
destinations: options.destinations,
|
|
7
|
+
maxQueueSize: options.maxQueueSize,
|
|
8
|
+
maxRetries: options.maxRetries,
|
|
9
|
+
storage: options.storage
|
|
10
|
+
});
|
|
11
|
+
let userId;
|
|
12
|
+
function enqueue(name, props) {
|
|
13
|
+
const envelope = {
|
|
14
|
+
anonymousId: options.anonymousId,
|
|
15
|
+
eventId: generateEventId(),
|
|
16
|
+
name,
|
|
17
|
+
owner: "client",
|
|
18
|
+
props,
|
|
19
|
+
timestamp: Date.now(),
|
|
20
|
+
...userId === void 0 ? {} : { userId }
|
|
21
|
+
};
|
|
22
|
+
queue.enqueue(envelope);
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
clear: () => {
|
|
26
|
+
queue.clear();
|
|
27
|
+
},
|
|
28
|
+
flush: () => queue.flush(),
|
|
29
|
+
flushWithBeacon(endpoint) {
|
|
30
|
+
const events = queue.drain();
|
|
31
|
+
if (events.length === 0) return;
|
|
32
|
+
if (!navigator.sendBeacon(endpoint, JSON.stringify(events))) for (const event of events) queue.enqueue(event);
|
|
33
|
+
},
|
|
34
|
+
identify(id, traits = {}) {
|
|
35
|
+
userId = id;
|
|
36
|
+
enqueue("$identify", traits);
|
|
37
|
+
},
|
|
38
|
+
page(name, props = {}) {
|
|
39
|
+
enqueue("$page_viewed", name === void 0 ? props : {
|
|
40
|
+
name,
|
|
41
|
+
...props
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
track(name, props) {
|
|
45
|
+
const definition = options.catalog[name];
|
|
46
|
+
if (!definition || definition.owner !== "client") throw new Error(`Unknown client-owned event: ${String(name)}`);
|
|
47
|
+
definition.schema.parse(props);
|
|
48
|
+
enqueue(name, props);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { createClientTracker };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/client/gpc.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
|
|
4
|
+
* CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
|
|
5
|
+
*/
|
|
6
|
+
declare function hasGlobalPrivacyControlSignal(): boolean;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { hasGlobalPrivacyControlSignal };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/client/gpc.ts
|
|
2
|
+
/**
|
|
3
|
+
* Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
|
|
4
|
+
* CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
|
|
5
|
+
*/
|
|
6
|
+
function hasGlobalPrivacyControlSignal() {
|
|
7
|
+
return navigator.globalPrivacyControl === true;
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { hasGlobalPrivacyControlSignal };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
|
|
2
|
+
import { EventQueue, EventQueueOptions, EventQueueStorage } from "./queue.mjs";
|
|
3
|
+
import { ClientTracker, ClientTrackerOptions, createClientTracker } from "./create-client-tracker.mjs";
|
|
4
|
+
import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
|
|
5
|
+
import { ClientLifecycleOptions, attachClientLifecycle } from "./lifecycle.mjs";
|
|
6
|
+
import { createLocalStorageQueueStorage } from "./local-storage.mjs";
|
|
7
|
+
import { RouterLike, attachRouterPageTracking } from "./router.mjs";
|
|
8
|
+
export { type ClientLifecycleOptions, type ClientTracker, type ClientTrackerOptions, EventQueue, type EventQueueOptions, type EventQueueStorage, type RouterLike, attachClientLifecycle, attachRouterPageTracking, createClientTracker, createLocalStorageConsentStorage, createLocalStorageQueueStorage, hasGlobalPrivacyControlSignal };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
|
|
2
|
+
import { EventQueue } from "./queue.mjs";
|
|
3
|
+
import { createClientTracker } from "./create-client-tracker.mjs";
|
|
4
|
+
import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
|
|
5
|
+
import { attachClientLifecycle } from "./lifecycle.mjs";
|
|
6
|
+
import { createLocalStorageQueueStorage } from "./local-storage.mjs";
|
|
7
|
+
import { attachRouterPageTracking } from "./router.mjs";
|
|
8
|
+
export { EventQueue, attachClientLifecycle, attachRouterPageTracking, createClientTracker, createLocalStorageConsentStorage, createLocalStorageQueueStorage, hasGlobalPrivacyControlSignal };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { EventCatalog } from "../core/event-catalog.mjs";
|
|
2
|
+
import { ClientTracker } from "./create-client-tracker.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/client/lifecycle.d.ts
|
|
5
|
+
interface ClientLifecycleOptions {
|
|
6
|
+
/** `sendBeacon` target used on unload — omit to skip the unload flush entirely. */
|
|
7
|
+
beaconEndpoint?: string;
|
|
8
|
+
flushIntervalMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Wires the two flush triggers the queue itself can't own (batch-size is handled inside
|
|
12
|
+
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
13
|
+
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
14
|
+
* Returns a cleanup function to remove all listeners/timers.
|
|
15
|
+
*/
|
|
16
|
+
declare function attachClientLifecycle<Catalog extends EventCatalog>(tracker: Pick<ClientTracker<Catalog>, "flush" | "flushWithBeacon">, options?: ClientLifecycleOptions): () => void;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { ClientLifecycleOptions, attachClientLifecycle };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/client/lifecycle.ts
|
|
2
|
+
/**
|
|
3
|
+
* Wires the two flush triggers the queue itself can't own (batch-size is handled inside
|
|
4
|
+
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
5
|
+
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
6
|
+
* Returns a cleanup function to remove all listeners/timers.
|
|
7
|
+
*/
|
|
8
|
+
function attachClientLifecycle(tracker, options = {}) {
|
|
9
|
+
const flushIntervalMs = options.flushIntervalMs ?? 1e4;
|
|
10
|
+
const intervalId = setInterval(() => {
|
|
11
|
+
tracker.flush();
|
|
12
|
+
}, flushIntervalMs);
|
|
13
|
+
function flushOnUnload() {
|
|
14
|
+
if (options.beaconEndpoint !== void 0) tracker.flushWithBeacon(options.beaconEndpoint);
|
|
15
|
+
}
|
|
16
|
+
function handleVisibilityChange() {
|
|
17
|
+
if (document.visibilityState === "hidden") flushOnUnload();
|
|
18
|
+
}
|
|
19
|
+
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
20
|
+
window.addEventListener("pagehide", flushOnUnload);
|
|
21
|
+
return () => {
|
|
22
|
+
clearInterval(intervalId);
|
|
23
|
+
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
|
24
|
+
window.removeEventListener("pagehide", flushOnUnload);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { attachClientLifecycle };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { EventQueueStorage } from "./queue.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/client/local-storage.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* `localStorage`-backed queue storage — corrupt/missing state is treated as empty
|
|
6
|
+
* rather than thrown, since a lost offline queue is preferable to a crashing app.
|
|
7
|
+
*/
|
|
8
|
+
declare function createLocalStorageQueueStorage(storageKey: string): EventQueueStorage;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { createLocalStorageQueueStorage };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/client/local-storage.ts
|
|
2
|
+
/**
|
|
3
|
+
* `localStorage`-backed queue storage — corrupt/missing state is treated as empty
|
|
4
|
+
* rather than thrown, since a lost offline queue is preferable to a crashing app.
|
|
5
|
+
*/
|
|
6
|
+
function createLocalStorageQueueStorage(storageKey) {
|
|
7
|
+
return {
|
|
8
|
+
load() {
|
|
9
|
+
const raw = localStorage.getItem(storageKey);
|
|
10
|
+
if (!raw) return [];
|
|
11
|
+
try {
|
|
12
|
+
const parsed = JSON.parse(raw);
|
|
13
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
14
|
+
} catch {
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
save(events) {
|
|
19
|
+
localStorage.setItem(storageKey, JSON.stringify(events));
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { createLocalStorageQueueStorage };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { TrackedEvent } from "../core/tracked-event.mjs";
|
|
2
|
+
import { Destination } from "../core/destination.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/client/queue.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Persistence backend for the offline queue — a thin wrapper so tests and non-browser
|
|
7
|
+
* environments can swap in an in-memory implementation instead of real `localStorage`.
|
|
8
|
+
*/
|
|
9
|
+
interface EventQueueStorage {
|
|
10
|
+
load: () => Array<TrackedEvent>;
|
|
11
|
+
save: (events: Array<TrackedEvent>) => void;
|
|
12
|
+
}
|
|
13
|
+
interface EventQueueOptions {
|
|
14
|
+
destinations: Array<Destination>;
|
|
15
|
+
flushBatchSize?: number | undefined;
|
|
16
|
+
maxQueueSize?: number | undefined;
|
|
17
|
+
maxRetries?: number | undefined;
|
|
18
|
+
storage: EventQueueStorage;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Client-side batching/offline queue: persists across reloads, caps its size
|
|
22
|
+
* (drop-oldest), and retries a failed batch up to `maxRetries` times.
|
|
23
|
+
*/
|
|
24
|
+
declare class EventQueue {
|
|
25
|
+
private readonly destinations;
|
|
26
|
+
private readonly flushBatchSize;
|
|
27
|
+
private readonly maxQueueSize;
|
|
28
|
+
private readonly maxRetries;
|
|
29
|
+
private pending;
|
|
30
|
+
private readonly storage;
|
|
31
|
+
constructor(options: EventQueueOptions);
|
|
32
|
+
get size(): number;
|
|
33
|
+
/** Drops every pending event without sending it — used on consent revoke. */
|
|
34
|
+
clear(): void;
|
|
35
|
+
/** Empties the queue synchronously for `navigator.sendBeacon`, which can't be awaited. */
|
|
36
|
+
drain(): Array<TrackedEvent>;
|
|
37
|
+
enqueue(event: TrackedEvent): void;
|
|
38
|
+
flush(): Promise<void>;
|
|
39
|
+
private persist;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { EventQueue, EventQueueOptions, EventQueueStorage };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region src/client/queue.ts
|
|
2
|
+
/**
|
|
3
|
+
* Client-side batching/offline queue: persists across reloads, caps its size
|
|
4
|
+
* (drop-oldest), and retries a failed batch up to `maxRetries` times.
|
|
5
|
+
*/
|
|
6
|
+
var EventQueue = class {
|
|
7
|
+
destinations;
|
|
8
|
+
flushBatchSize;
|
|
9
|
+
maxQueueSize;
|
|
10
|
+
maxRetries;
|
|
11
|
+
pending;
|
|
12
|
+
storage;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.destinations = options.destinations;
|
|
15
|
+
this.storage = options.storage;
|
|
16
|
+
this.maxQueueSize = options.maxQueueSize ?? 500;
|
|
17
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
18
|
+
this.flushBatchSize = options.flushBatchSize ?? 20;
|
|
19
|
+
this.pending = this.storage.load().map((event) => ({
|
|
20
|
+
attempts: 0,
|
|
21
|
+
event
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
get size() {
|
|
25
|
+
return this.pending.length;
|
|
26
|
+
}
|
|
27
|
+
/** Drops every pending event without sending it — used on consent revoke. */
|
|
28
|
+
clear() {
|
|
29
|
+
this.pending = [];
|
|
30
|
+
this.persist();
|
|
31
|
+
}
|
|
32
|
+
/** Empties the queue synchronously for `navigator.sendBeacon`, which can't be awaited. */
|
|
33
|
+
drain() {
|
|
34
|
+
const events = this.pending.map((queued) => queued.event);
|
|
35
|
+
this.pending = [];
|
|
36
|
+
this.persist();
|
|
37
|
+
return events;
|
|
38
|
+
}
|
|
39
|
+
enqueue(event) {
|
|
40
|
+
this.pending.push({
|
|
41
|
+
attempts: 0,
|
|
42
|
+
event
|
|
43
|
+
});
|
|
44
|
+
if (this.pending.length > this.maxQueueSize) this.pending = this.pending.slice(this.pending.length - this.maxQueueSize);
|
|
45
|
+
this.persist();
|
|
46
|
+
if (this.pending.length >= this.flushBatchSize) this.flush();
|
|
47
|
+
}
|
|
48
|
+
async flush() {
|
|
49
|
+
if (this.pending.length === 0) return;
|
|
50
|
+
const batch = this.pending;
|
|
51
|
+
this.pending = [];
|
|
52
|
+
const results = await Promise.allSettled(batch.map(async (queued) => {
|
|
53
|
+
await Promise.all(this.destinations.map(async (destination) => destination.send(queued.event)));
|
|
54
|
+
}));
|
|
55
|
+
for (const [index, result] of results.entries()) {
|
|
56
|
+
const queued = batch[index];
|
|
57
|
+
if (result.status === "rejected" && queued && queued.attempts < this.maxRetries) this.pending.push({
|
|
58
|
+
attempts: queued.attempts + 1,
|
|
59
|
+
event: queued.event
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
this.persist();
|
|
63
|
+
}
|
|
64
|
+
persist() {
|
|
65
|
+
this.storage.save(this.pending.map((queued) => queued.event));
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
//#endregion
|
|
69
|
+
export { EventQueue };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { EventCatalog } from "../core/event-catalog.mjs";
|
|
2
|
+
import { ClientTracker } from "./create-client-tracker.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/client/router.d.ts
|
|
5
|
+
interface ResolvedNavigation {
|
|
6
|
+
toLocation: {
|
|
7
|
+
href: string;
|
|
8
|
+
pathname: string;
|
|
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
|
+
interface RouterLike {
|
|
16
|
+
subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* `onResolved` (not `popstate`) is what fires on SPA navigation in TanStack Router;
|
|
20
|
+
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
21
|
+
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
22
|
+
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
23
|
+
*/
|
|
24
|
+
declare function attachRouterPageTracking<Catalog extends EventCatalog>(tracker: Pick<ClientTracker<Catalog>, "flush" | "page">, router: RouterLike): () => void;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { RouterLike, attachRouterPageTracking };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/client/router.ts
|
|
2
|
+
/**
|
|
3
|
+
* `onResolved` (not `popstate`) is what fires on SPA navigation in TanStack Router;
|
|
4
|
+
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
5
|
+
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
6
|
+
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
7
|
+
*/
|
|
8
|
+
function attachRouterPageTracking(tracker, router) {
|
|
9
|
+
return router.subscribe("onResolved", (event) => {
|
|
10
|
+
tracker.page(event.toLocation.pathname, { href: event.toLocation.href });
|
|
11
|
+
tracker.flush();
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { attachRouterPageTracking };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/core/consent.d.ts
|
|
2
|
+
type ConsentRegion = "eu" | "other" | "us" | "vn";
|
|
3
|
+
type ConsentMode = "opt-in" | "opt-out";
|
|
4
|
+
/**
|
|
5
|
+
* GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
|
|
6
|
+
* tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
|
|
7
|
+
* that satisfies both, so the mode is resolved per region.
|
|
8
|
+
*/
|
|
9
|
+
declare function resolveConsentMode(region: ConsentRegion): ConsentMode;
|
|
10
|
+
/**
|
|
11
|
+
* Under CCPA/CPRA, a Global Privacy Control signal must be honored as an opt-out even
|
|
12
|
+
* though the region default is opt-out. Under opt-in regions, tracking never starts
|
|
13
|
+
* until consent is explicitly granted, GPC signal or not.
|
|
14
|
+
*/
|
|
15
|
+
declare function shouldTrackByDefault(mode: ConsentMode, hasGlobalPrivacyControlSignal: boolean): boolean;
|
|
16
|
+
type ConsentDecision = "denied" | "granted";
|
|
17
|
+
/**
|
|
18
|
+
* NĐ 13/2023 and GDPR both expect a record of *when* and *under what policy* consent
|
|
19
|
+
* was given, not just a yes/no flag — `policyVersion` lets a later policy change
|
|
20
|
+
* invalidate stale consent.
|
|
21
|
+
*/
|
|
22
|
+
interface ConsentRecord {
|
|
23
|
+
decision: ConsentDecision;
|
|
24
|
+
policyVersion: string;
|
|
25
|
+
timestamp: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Persistence backend for the visitor's consent decision — mirrors `EventQueueStorage`
|
|
29
|
+
* so a non-browser environment can swap in its own implementation.
|
|
30
|
+
*/
|
|
31
|
+
interface ConsentStorage {
|
|
32
|
+
clear: () => void;
|
|
33
|
+
load: () => ConsentRecord | undefined;
|
|
34
|
+
save: (record: ConsentRecord) => void;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, resolveConsentMode, shouldTrackByDefault };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/core/consent.ts
|
|
2
|
+
/**
|
|
3
|
+
* GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
|
|
4
|
+
* tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
|
|
5
|
+
* that satisfies both, so the mode is resolved per region.
|
|
6
|
+
*/
|
|
7
|
+
function resolveConsentMode(region) {
|
|
8
|
+
switch (region) {
|
|
9
|
+
case "eu":
|
|
10
|
+
case "vn": return "opt-in";
|
|
11
|
+
case "other":
|
|
12
|
+
case "us": return "opt-out";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Under CCPA/CPRA, a Global Privacy Control signal must be honored as an opt-out even
|
|
17
|
+
* though the region default is opt-out. Under opt-in regions, tracking never starts
|
|
18
|
+
* until consent is explicitly granted, GPC signal or not.
|
|
19
|
+
*/
|
|
20
|
+
function shouldTrackByDefault(mode, hasGlobalPrivacyControlSignal) {
|
|
21
|
+
if (mode === "opt-in") return false;
|
|
22
|
+
return !hasGlobalPrivacyControlSignal;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
export { resolveConsentMode, shouldTrackByDefault };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { TrackedEvent } from "./tracked-event.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/destination.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fan-out target for tracked events (PostHog, GA4, a self-hosted store, ...).
|
|
6
|
+
* Trackers depend only on this interface, never on a specific provider SDK.
|
|
7
|
+
*/
|
|
8
|
+
interface Destination {
|
|
9
|
+
name: string;
|
|
10
|
+
send: (event: TrackedEvent) => Promise<void> | void;
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
export { Destination };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
//#region src/core/event-catalog.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* One event's Zod schema plus which side of the app is allowed to fire it.
|
|
6
|
+
*/
|
|
7
|
+
interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
|
|
8
|
+
owner: "client" | "server";
|
|
9
|
+
schema: Schema;
|
|
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
|
+
type EventCatalog = Record<string, EventDefinition>;
|
|
16
|
+
/**
|
|
17
|
+
* Filters a catalog down to the events a given owner may fire. Client and server
|
|
18
|
+
* trackers are built from this, so calling a server-owned event from client code
|
|
19
|
+
* (or vice versa) is a compile-time error, not a runtime surprise.
|
|
20
|
+
*/
|
|
21
|
+
type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = { [Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key] };
|
|
22
|
+
/**
|
|
23
|
+
* Identity helper for declaring a catalog with inference — nicer call-site than
|
|
24
|
+
* `satisfies EventCatalog` when the catalog is assembled across multiple files.
|
|
25
|
+
*/
|
|
26
|
+
declare function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { EventCatalog, EventDefinition, EventsOf, defineEventCatalog };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/core/event-catalog.ts
|
|
2
|
+
/**
|
|
3
|
+
* Identity helper for declaring a catalog with inference — nicer call-site than
|
|
4
|
+
* `satisfies EventCatalog` when the catalog is assembled across multiple files.
|
|
5
|
+
*/
|
|
6
|
+
function defineEventCatalog(catalog) {
|
|
7
|
+
return catalog;
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { defineEventCatalog };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/core/event-id.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Client-owned events use this at enqueue time; server-owned events derive an ID
|
|
4
|
+
* from the request instead so retries of the same request don't double-count.
|
|
5
|
+
*/
|
|
6
|
+
declare function generateEventId(): string;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { generateEventId };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/core/event-id.ts
|
|
2
|
+
/**
|
|
3
|
+
* Client-owned events use this at enqueue time; server-owned events derive an ID
|
|
4
|
+
* from the request instead so retries of the same request don't double-count.
|
|
5
|
+
*/
|
|
6
|
+
function generateEventId() {
|
|
7
|
+
return crypto.randomUUID();
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { generateEventId };
|