@codefast/tracking 0.5.0-canary.4 → 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.
- package/CHANGELOG.md +171 -0
- package/README.md +123 -96
- package/dist/client/browser-cookie.d.mts +11 -0
- package/dist/client/browser-cookie.mjs +15 -0
- package/dist/client/consent-runtime.d.mts +56 -0
- package/dist/client/consent-runtime.mjs +35 -0
- package/dist/client/consent-storage.d.mts +5 -0
- package/dist/client/consent-storage.mjs +20 -1
- package/dist/client/consent-withdrawal.d.mts +21 -0
- package/dist/client/consent-withdrawal.mjs +17 -0
- package/dist/client/cookie-anonymous-id.d.mts +37 -0
- package/dist/client/cookie-anonymous-id.mjs +46 -0
- package/dist/client/create-client-tracker.d.mts +11 -16
- package/dist/client/create-client-tracker.mjs +27 -53
- package/dist/client/gpc.d.mts +2 -0
- package/dist/client/gpc.mjs +3 -1
- package/dist/client/index.d.mts +7 -5
- package/dist/client/index.mjs +8 -6
- package/dist/client/initial-consent-store.d.mts +66 -0
- package/dist/client/initial-consent-store.mjs +119 -0
- package/dist/client/is-analytics-allowed.d.mts +29 -0
- package/dist/client/is-analytics-allowed.mjs +23 -0
- package/dist/client/server-persisted-anonymous-id.d.mts +33 -0
- package/dist/client/server-persisted-anonymous-id.mjs +50 -0
- package/dist/core/consent-config.d.mts +27 -0
- package/dist/core/consent-config.mjs +11 -0
- package/dist/core/consent.d.mts +99 -4
- package/dist/core/consent.mjs +99 -4
- package/dist/core/cookie.d.mts +17 -0
- package/dist/core/cookie.mjs +23 -0
- package/dist/core/destination.d.mts +10 -8
- package/dist/core/event-catalog.d.mts +16 -13
- package/dist/core/event-catalog.mjs +19 -1
- package/dist/core/event-id.d.mts +1 -2
- package/dist/core/event-id.mjs +1 -2
- package/dist/core/index.d.mts +6 -4
- package/dist/core/index.mjs +5 -3
- package/dist/core/tracked-event.d.mts +21 -8
- package/dist/destinations/google-analytics.d.mts +100 -48
- package/dist/destinations/google-analytics.mjs +89 -85
- package/dist/destinations/google-consent.d.mts +64 -0
- package/dist/destinations/google-consent.mjs +102 -0
- package/dist/destinations/index.d.mts +2 -5
- package/dist/destinations/index.mjs +2 -5
- package/dist/destinations/shared.d.mts +20 -0
- package/dist/destinations/shared.mjs +13 -0
- package/dist/destinations/vercel-analytics.d.mts +19 -4
- package/dist/destinations/vercel-analytics.mjs +11 -18
- package/dist/import-protection.d.mts +19 -0
- package/dist/import-protection.mjs +23 -0
- package/dist/index.d.mts +6 -4
- package/dist/index.mjs +5 -3
- package/dist/react/consent-banner.d.mts +143 -38
- package/dist/react/consent-banner.mjs +192 -92
- package/dist/react/gtag-consent-bootstrap.d.mts +27 -0
- package/dist/react/gtag-consent-bootstrap.mjs +29 -0
- package/dist/react/index.d.mts +5 -2
- package/dist/react/index.mjs +5 -2
- package/dist/react/use-consent.d.mts +9 -13
- package/dist/react/use-consent.mjs +42 -25
- package/dist/react/use-google-consent-sync.d.mts +23 -0
- package/dist/react/use-google-consent-sync.mjs +24 -0
- package/dist/react/use-initial-consent.d.mts +14 -0
- package/dist/react/use-initial-consent.mjs +19 -0
- package/dist/server/anonymous-id-cookie.d.mts +46 -0
- package/dist/server/anonymous-id-cookie.mjs +51 -0
- package/dist/server/index.d.mts +5 -3
- package/dist/server/index.mjs +4 -3
- package/dist/server/initial-consent.d.mts +29 -0
- package/dist/server/initial-consent.mjs +31 -0
- package/dist/server/region.d.mts +21 -4
- package/dist/server/region.mjs +26 -5
- package/dist/tanstack-start/index.d.mts +58 -0
- package/dist/tanstack-start/index.mjs +45 -0
- package/package.json +27 -110
- package/src/client/browser-cookie.ts +16 -0
- package/src/client/consent-runtime.ts +80 -0
- package/src/client/consent-storage.ts +31 -1
- package/src/client/consent-withdrawal.ts +32 -0
- package/src/client/cookie-anonymous-id.ts +93 -0
- package/src/client/create-client-tracker.ts +56 -85
- package/src/client/gpc.ts +4 -2
- package/src/client/index.ts +19 -8
- package/src/client/initial-consent-store.ts +218 -0
- package/src/client/is-analytics-allowed.ts +43 -0
- package/src/client/server-persisted-anonymous-id.ts +99 -0
- package/src/core/consent-config.ts +27 -0
- package/src/core/consent.ts +164 -10
- package/src/core/cookie.ts +29 -0
- package/src/core/destination.ts +10 -8
- package/src/core/event-catalog.ts +28 -15
- package/src/core/event-id.ts +1 -2
- package/src/core/index.ts +19 -3
- package/src/core/tracked-event.ts +22 -7
- package/src/css/consent.css +119 -0
- package/src/destinations/google-analytics.ts +196 -133
- package/src/destinations/google-consent.ts +164 -0
- package/src/destinations/index.ts +14 -15
- package/src/destinations/shared.ts +45 -0
- package/src/destinations/vercel-analytics.ts +23 -24
- package/src/import-protection.ts +20 -0
- package/src/index.ts +46 -8
- package/src/react/consent-banner.tsx +308 -111
- package/src/react/gtag-consent-bootstrap.tsx +48 -0
- package/src/react/index.ts +34 -2
- package/src/react/use-consent.ts +53 -45
- package/src/react/use-google-consent-sync.ts +38 -0
- package/src/react/use-initial-consent.ts +22 -0
- package/src/server/anonymous-id-cookie.ts +76 -0
- package/src/server/index.ts +15 -3
- package/src/server/initial-consent.ts +48 -0
- package/src/server/region.ts +22 -5
- package/src/tanstack-start/index.ts +83 -0
- package/dist/client/lifecycle.d.mts +0 -23
- package/dist/client/lifecycle.mjs +0 -30
- package/dist/client/local-storage.d.mts +0 -13
- package/dist/client/local-storage.mjs +0 -31
- package/dist/client/queue.d.mts +0 -49
- package/dist/client/queue.mjs +0 -71
- package/dist/client/router.d.mts +0 -30
- package/dist/client/router.mjs +0 -17
- package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
- package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
- package/dist/destinations/http-destination.d.mts +0 -20
- package/dist/destinations/http-destination.mjs +0 -25
- package/dist/server/create-server-tracker.d.mts +0 -42
- package/dist/server/create-server-tracker.mjs +0 -67
- package/src/client/lifecycle.ts +0 -50
- package/src/client/local-storage.ts +0 -44
- package/src/client/queue.ts +0 -117
- package/src/client/router.ts +0 -37
- package/src/destinations/ga4-measurement-protocol.ts +0 -166
- package/src/destinations/http-destination.ts +0 -33
- package/src/server/create-server-tracker.ts +0 -128
package/dist/client/queue.mjs
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
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
|
-
* @since 0.5.0-canary.4
|
|
7
|
-
*/
|
|
8
|
-
var EventQueue = class {
|
|
9
|
-
destinations;
|
|
10
|
-
flushBatchSize;
|
|
11
|
-
maxQueueSize;
|
|
12
|
-
maxRetries;
|
|
13
|
-
pending;
|
|
14
|
-
storage;
|
|
15
|
-
constructor(options) {
|
|
16
|
-
this.destinations = options.destinations;
|
|
17
|
-
this.storage = options.storage;
|
|
18
|
-
this.maxQueueSize = options.maxQueueSize ?? 500;
|
|
19
|
-
this.maxRetries = options.maxRetries ?? 3;
|
|
20
|
-
this.flushBatchSize = options.flushBatchSize ?? 20;
|
|
21
|
-
this.pending = this.storage.load().map((event) => ({
|
|
22
|
-
attempts: 0,
|
|
23
|
-
event
|
|
24
|
-
}));
|
|
25
|
-
}
|
|
26
|
-
get size() {
|
|
27
|
-
return this.pending.length;
|
|
28
|
-
}
|
|
29
|
-
/** Drops every pending event without sending it — used on consent revoke. */
|
|
30
|
-
clear() {
|
|
31
|
-
this.pending = [];
|
|
32
|
-
this.persist();
|
|
33
|
-
}
|
|
34
|
-
/** Empties the queue synchronously for `navigator.sendBeacon`, which can't be awaited. */
|
|
35
|
-
drain() {
|
|
36
|
-
const events = this.pending.map((queued) => queued.event);
|
|
37
|
-
this.pending = [];
|
|
38
|
-
this.persist();
|
|
39
|
-
return events;
|
|
40
|
-
}
|
|
41
|
-
enqueue(event) {
|
|
42
|
-
this.pending.push({
|
|
43
|
-
attempts: 0,
|
|
44
|
-
event
|
|
45
|
-
});
|
|
46
|
-
if (this.pending.length > this.maxQueueSize) this.pending = this.pending.slice(this.pending.length - this.maxQueueSize);
|
|
47
|
-
this.persist();
|
|
48
|
-
if (this.pending.length >= this.flushBatchSize) this.flush();
|
|
49
|
-
}
|
|
50
|
-
async flush() {
|
|
51
|
-
if (this.pending.length === 0) return;
|
|
52
|
-
const batch = this.pending;
|
|
53
|
-
this.pending = [];
|
|
54
|
-
const results = await Promise.allSettled(batch.map(async (queued) => {
|
|
55
|
-
await Promise.all(this.destinations.map(async (destination) => destination.send(queued.event)));
|
|
56
|
-
}));
|
|
57
|
-
for (const [index, result] of results.entries()) {
|
|
58
|
-
const queued = batch[index];
|
|
59
|
-
if (result.status === "rejected" && queued && queued.attempts < this.maxRetries) this.pending.push({
|
|
60
|
-
attempts: queued.attempts + 1,
|
|
61
|
-
event: queued.event
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
this.persist();
|
|
65
|
-
}
|
|
66
|
-
persist() {
|
|
67
|
-
this.storage.save(this.pending.map((queued) => queued.event));
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
//#endregion
|
|
71
|
-
export { EventQueue };
|
package/dist/client/router.d.mts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
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
|
-
* @since 0.5.0-canary.4
|
|
16
|
-
*/
|
|
17
|
-
interface RouterLike {
|
|
18
|
-
subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* `onResolved` (not `popstate`) is what fires on SPA navigation in TanStack Router;
|
|
22
|
-
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
23
|
-
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
24
|
-
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
25
|
-
*
|
|
26
|
-
* @since 0.5.0-canary.4
|
|
27
|
-
*/
|
|
28
|
-
declare function attachRouterPageTracking<Catalog extends EventCatalog>(tracker: Pick<ClientTracker<Catalog>, "flush" | "page">, router: RouterLike): () => void;
|
|
29
|
-
//#endregion
|
|
30
|
-
export { RouterLike, attachRouterPageTracking };
|
package/dist/client/router.mjs
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
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
|
-
* @since 0.5.0-canary.4
|
|
9
|
-
*/
|
|
10
|
-
function attachRouterPageTracking(tracker, router) {
|
|
11
|
-
return router.subscribe("onResolved", (event) => {
|
|
12
|
-
tracker.page(event.toLocation.pathname, { href: event.toLocation.href });
|
|
13
|
-
tracker.flush();
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
//#endregion
|
|
17
|
-
export { attachRouterPageTracking };
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { Destination } from "../core/destination.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/destinations/ga4-measurement-protocol.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
|
|
6
|
-
* `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
|
|
7
|
-
* pass it as `clientId` to make server events land on the same user as the visitor's
|
|
8
|
-
* client-side hits.
|
|
9
|
-
*
|
|
10
|
-
* @since 0.5.0-canary.4
|
|
11
|
-
*/
|
|
12
|
-
declare function extractGa4ClientId(cookieHeader: string | undefined): string | undefined;
|
|
13
|
-
/**
|
|
14
|
-
* Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
|
|
15
|
-
* (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
|
|
16
|
-
* `$`-delimited `GS2` value formats.
|
|
17
|
-
*
|
|
18
|
-
* @since 0.5.0-canary.4
|
|
19
|
-
*/
|
|
20
|
-
declare function extractGa4SessionId(cookieHeader: string | undefined, measurementId: string): string | undefined;
|
|
21
|
-
/**
|
|
22
|
-
* @since 0.5.0-canary.4
|
|
23
|
-
*/
|
|
24
|
-
interface Ga4MeasurementProtocolDestinationOptions {
|
|
25
|
-
apiSecret: string;
|
|
26
|
-
/**
|
|
27
|
-
* gtag.js's client ID for this visitor (see `extractGa4ClientId`). Without it the
|
|
28
|
-
* event falls back to the tracker's anonymous ID, which GA4 treats as a *different
|
|
29
|
-
* user* than the visitor's client-side hits — pass it whenever the request carries a
|
|
30
|
-
* `_ga` cookie.
|
|
31
|
-
*/
|
|
32
|
-
clientId?: string | undefined;
|
|
33
|
-
/** Routes to GA4's `/debug/mp/collect` validation endpoint — hits are validated but never recorded. */
|
|
34
|
-
debug?: boolean;
|
|
35
|
-
measurementId: string;
|
|
36
|
-
name?: string;
|
|
37
|
-
/**
|
|
38
|
-
* Current GA4 session for this visitor (see `extractGa4SessionId`). Without a
|
|
39
|
-
* `session_id`, GA4 accepts the event but leaves it out of session-scoped and realtime
|
|
40
|
-
* reporting.
|
|
41
|
-
*/
|
|
42
|
-
sessionId?: string | undefined;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
|
|
46
|
-
* signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
|
|
47
|
-
* to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
|
|
48
|
-
* `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
|
|
49
|
-
*
|
|
50
|
-
* @since 0.5.0-canary.4
|
|
51
|
-
*/
|
|
52
|
-
declare function createGa4MeasurementProtocolDestination(options: Ga4MeasurementProtocolDestinationOptions): Destination;
|
|
53
|
-
//#endregion
|
|
54
|
-
export { Ga4MeasurementProtocolDestinationOptions, createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId };
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
//#region src/destinations/ga4-measurement-protocol.ts
|
|
2
|
-
/**
|
|
3
|
-
* Measurement Protocol event params must be flat string/number/boolean — stringify
|
|
4
|
-
* anything else instead of letting GA4 silently drop it.
|
|
5
|
-
*/
|
|
6
|
-
function toMeasurementProtocolParams(props) {
|
|
7
|
-
const result = {};
|
|
8
|
-
for (const [key, value] of Object.entries(props)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
|
|
9
|
-
else if (value !== void 0 && value !== null) result[key] = JSON.stringify(value);
|
|
10
|
-
return result;
|
|
11
|
-
}
|
|
12
|
-
function readCookie(cookieHeader, cookieName) {
|
|
13
|
-
if (!cookieHeader) return;
|
|
14
|
-
for (const part of cookieHeader.split(";")) {
|
|
15
|
-
const separatorIndex = part.indexOf("=");
|
|
16
|
-
if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) return part.slice(separatorIndex + 1).trim();
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
|
|
21
|
-
* `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
|
|
22
|
-
* pass it as `clientId` to make server events land on the same user as the visitor's
|
|
23
|
-
* client-side hits.
|
|
24
|
-
*
|
|
25
|
-
* @since 0.5.0-canary.4
|
|
26
|
-
*/
|
|
27
|
-
function extractGa4ClientId(cookieHeader) {
|
|
28
|
-
const value = readCookie(cookieHeader, "_ga");
|
|
29
|
-
if (!value) return;
|
|
30
|
-
const segments = value.split(".");
|
|
31
|
-
return segments.length >= 4 ? segments.slice(-2).join(".") : void 0;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
|
|
35
|
-
* (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
|
|
36
|
-
* `$`-delimited `GS2` value formats.
|
|
37
|
-
*
|
|
38
|
-
* @since 0.5.0-canary.4
|
|
39
|
-
*/
|
|
40
|
-
function extractGa4SessionId(cookieHeader, measurementId) {
|
|
41
|
-
const value = readCookie(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
|
|
42
|
-
if (!value) return;
|
|
43
|
-
return /^GS\d+\.\d+\.s?(\d+)/.exec(value)?.[1];
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
|
|
47
|
-
* signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
|
|
48
|
-
* to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
|
|
49
|
-
* `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
|
|
50
|
-
*
|
|
51
|
-
* @since 0.5.0-canary.4
|
|
52
|
-
*/
|
|
53
|
-
function createGa4MeasurementProtocolDestination(options) {
|
|
54
|
-
const name = options.name ?? "ga4-measurement-protocol";
|
|
55
|
-
const endpoint = `${options.debug ? "https://www.google-analytics.com/debug/mp/collect" : "https://www.google-analytics.com/mp/collect"}?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
|
|
56
|
-
return {
|
|
57
|
-
name,
|
|
58
|
-
async send(event) {
|
|
59
|
-
if (event.name === "$alias") return;
|
|
60
|
-
const eventName = event.name === "$group" ? "join_group" : event.name;
|
|
61
|
-
const params = toMeasurementProtocolParams(event.name === "$group" ? renameGroupIdProp(event.props) : event.props);
|
|
62
|
-
if (options.sessionId !== void 0 && params.session_id === void 0) params.session_id = options.sessionId;
|
|
63
|
-
params.engagement_time_msec ??= 100;
|
|
64
|
-
const response = await fetch(endpoint, {
|
|
65
|
-
body: JSON.stringify({
|
|
66
|
-
client_id: options.clientId ?? event.anonymousId,
|
|
67
|
-
events: [{
|
|
68
|
-
name: eventName,
|
|
69
|
-
params
|
|
70
|
-
}],
|
|
71
|
-
timestamp_micros: event.timestamp * 1e3,
|
|
72
|
-
...event.userId === void 0 ? {} : { user_id: event.userId }
|
|
73
|
-
}),
|
|
74
|
-
headers: { "content-type": "application/json" },
|
|
75
|
-
method: "POST"
|
|
76
|
-
});
|
|
77
|
-
if (!response.ok) throw new Error(`"${name}" destination responded with ${String(response.status)}`);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
function renameGroupIdProp(props) {
|
|
82
|
-
const { groupId, ...traits } = props;
|
|
83
|
-
return {
|
|
84
|
-
group_id: groupId,
|
|
85
|
-
...traits
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
//#endregion
|
|
89
|
-
export { createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId };
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { Destination } from "../core/destination.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/destinations/http-destination.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* @since 0.5.0-canary.4
|
|
6
|
-
*/
|
|
7
|
-
interface HttpDestinationOptions {
|
|
8
|
-
endpoint: string;
|
|
9
|
-
headers?: Record<string, string>;
|
|
10
|
-
name: string;
|
|
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
|
-
declare function createHttpDestination(options: HttpDestinationOptions): Destination;
|
|
19
|
-
//#endregion
|
|
20
|
-
export { HttpDestinationOptions, createHttpDestination };
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
//#region src/destinations/http-destination.ts
|
|
2
|
-
/**
|
|
3
|
-
* Generic fetch-based `Destination` — the building block for a real provider adapter
|
|
4
|
-
* (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
|
|
5
|
-
*
|
|
6
|
-
* @since 0.5.0-canary.4
|
|
7
|
-
*/
|
|
8
|
-
function createHttpDestination(options) {
|
|
9
|
-
return {
|
|
10
|
-
name: options.name,
|
|
11
|
-
async send(event) {
|
|
12
|
-
const response = await fetch(options.endpoint, {
|
|
13
|
-
body: JSON.stringify(event),
|
|
14
|
-
headers: {
|
|
15
|
-
"content-type": "application/json",
|
|
16
|
-
...options.headers
|
|
17
|
-
},
|
|
18
|
-
method: "POST"
|
|
19
|
-
});
|
|
20
|
-
if (!response.ok) throw new Error(`"${options.name}" destination responded with ${String(response.status)}`);
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
//#endregion
|
|
25
|
-
export { createHttpDestination };
|
|
@@ -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 };
|
package/src/client/lifecycle.ts
DELETED
|
@@ -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
|
-
}
|
package/src/client/queue.ts
DELETED
|
@@ -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
|
-
}
|
package/src/client/router.ts
DELETED
|
@@ -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
|
-
}
|