Skip to content

Commit 9543564

Browse files
feat(tracker): add global properties and event transforms
Signed-off-by: Henry <mail@henrygressmann.de>
1 parent dd2ff51 commit 9543564

10 files changed

Lines changed: 253 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Since this is not a library, this changelog focuses on the changes that are rele
2828
- Bounce-rate and average-time metrics now omit low-sample values from summary cards and breakdowns, with configurable minimum counts under `[limits]`.
2929
- Added support for custom events
3030
- Added support for custom properties
31+
- Added tracker-wide custom properties and a hook to customize events before sending them
3132
- Added authenticated batch event ingestion endpoint
3233
- Added API key management UI
3334
- Added a configurable maximum session duration

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎data/licenses-npm.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎packages/tracker/README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,43 @@ When the script is loaded directly in the browser, it will automatically send pa
3636

3737
Pageviews send a best-effort exit signal when the page becomes hidden. Set `data-exit="false"` to disable exit tracking.
3838

39+
Set `window.liwanProperties` before loading the tracker to include properties on every pageview and custom event. You can update or delete keys later, and properties passed to `event()` take precedence.
40+
41+
```html
42+
<script>
43+
window.liwanProperties = { plan: "pro" };
44+
</script>
45+
<script type="module" src="https://liwan.example.com/script.js" data-entity="example"></script>
46+
```
47+
48+
When importing the tracker, use `setProperties()` to update defaults. Set a key to `null` to remove it:
49+
50+
```ts
51+
import { setProperties } from "@liwan.dev/tracker";
52+
53+
setProperties({ plan: "team" });
54+
setProperties({ plan: null });
55+
```
56+
57+
Globals in server-side environments are shared across requests. Pass request-specific properties to `event()` instead of setting global defaults.
58+
59+
To customize events, define a synchronous `window.liwanTransformEvent` function before the tracker loads. It runs for automatic pageviews and explicit `event()` calls, including custom events. The callback receives the normalized payload, including its `name`, sanitized URL, `entity_id`, and global properties, and should return the payload to send. Exit signals do not call the transformer. If you change the URL, avoid adding query parameters or fragments that contain personal data.
60+
61+
```html
62+
<script>
63+
window.liwanTransformEvent = (payload) => ({
64+
...payload,
65+
properties: {
66+
...payload.properties,
67+
section: new URL(payload.url).pathname.split("/")[1] || "home",
68+
event_type: payload.name,
69+
},
70+
});
71+
</script>
72+
```
73+
74+
Keep property values free of personal data. Events support at most 30 properties, with keys up to 64 characters and values up to 255 characters.
75+
3976
When using the package, call `trackPageviews()` to start automatic pageview tracking:
4077

4178
```ts
@@ -47,6 +84,8 @@ trackPageviews({
4784
});
4885
```
4986

87+
Calling `trackPageviews()` again logs a message and does not add another listener or send a duplicate pageview.
88+
5089
### Custom events
5190

5291
Call `event` when an action happens. In the browser, the tracker uses the current page URL and referrer.
@@ -110,6 +149,9 @@ export type EventOptions = {
110149

111150
export type EventProperties = Record<string, string | number | boolean | null | undefined>;
112151

152+
/** Set default properties for subsequent events. Pass `null` to remove a property. */
153+
export function setProperties(properties: EventProperties): void;
154+
113155
/**
114156
* Sends an event to the Liwan API.
115157
*

‎packages/tracker/lib/script.d.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,30 @@ declare global {
33
interface Window {
44
__liwan_loaded?: boolean;
55
}
6+
/** Default properties included with subsequent events. Set before loading the script to include the first pageview. */
7+
var liwanProperties: EventProperties | undefined;
8+
/** Transform a normalized event payload before it is sent. Not called for exit signals. */
9+
var liwanTransformEvent: ((payload: EventPayload) => EventPayload) | undefined;
610
}
11+
/** Normalized event sent to the API. The event transformer can edit this before it is sent. */
12+
export type EventPayload = {
13+
/** Event name, such as `pageview` or `signup`. */
14+
name: string;
15+
/** Entity associated with the event. */
16+
entity_id?: string;
17+
/** Page URL with unrecognized query parameters and the fragment removed. */
18+
url: string;
19+
/** Referrer supplied by the caller or the document. */
20+
referrer?: string;
21+
/** Screen-width bucket, when available in the browser. */
22+
screen_width?: string;
23+
/** Screen orientation, when available in the browser. */
24+
orientation?: string;
25+
/** Global defaults merged with event-specific properties. */
26+
properties?: EventProperties;
27+
/** Marks a pageview exit signal. */
28+
exit?: boolean;
29+
};
730
export type EventProperties = Record<string, string | number | boolean | null | undefined>;
831
export type EventOptions = {
932
/**
@@ -43,6 +66,8 @@ export type EventOptions = {
4366
*/
4467
properties?: EventProperties;
4568
};
69+
/** Set default properties for subsequent events. Pass `null` to remove a property. */
70+
export declare function setProperties(properties: EventProperties): void;
4671
/**
4772
* Sends an event to the Liwan API.
4873
*
@@ -69,6 +94,7 @@ export declare function event(name?: string, options?: EventOptions): Promise<vo
6994
* navigations using the Navigation API when available, with `popstate` as a fallback.
7095
*
7196
* Calling this function marks Liwan as loaded through `window.__liwan_loaded`.
97+
* Subsequent calls are ignored.
7298
*
7399
* @param options Options passed to each pageview event.
74100
*

‎packages/tracker/lib/script.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/tracker/package.json‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,13 @@
2424
"url": "https://henrygressmann.de"
2525
},
2626
"type": "module",
27-
"scripts": { "build": "tsdown", "typecheck": "tsc --noEmit" },
27+
"scripts": {
28+
"build": "tsdown",
29+
"test": "bun test tests",
30+
"typecheck": "tsc --noEmit"
31+
},
2832
"devDependencies": {
33+
"@types/bun": "^1.4.2",
2934
"tsdown": "^0.23.1",
3035
"typescript": "^7.0.2"
3136
},

‎packages/tracker/src/script.ts‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,31 @@ declare global {
22
interface Window {
33
__liwan_loaded?: boolean;
44
}
5+
/** Default properties included with subsequent events. Set before loading the script to include the first pageview. */
6+
var liwanProperties: EventProperties | undefined;
7+
/** Transform a normalized event payload before it is sent. Not called for exit signals. */
8+
var liwanTransformEvent: ((payload: EventPayload) => EventPayload) | undefined;
59
}
610

7-
type Payload = {
11+
/** Normalized event sent to the API. The event transformer can edit this before it is sent. */
12+
export type EventPayload = {
13+
/** Event name, such as `pageview` or `signup`. */
814
name: string;
15+
/** Entity associated with the event. */
916
entity_id?: string;
17+
/** Page URL with unrecognized query parameters and the fragment removed. */
1018
url: string;
19+
/** Referrer supplied by the caller or the document. */
1120
referrer?: string;
21+
/** Screen-width bucket, when available in the browser. */
1222
screen_width?: string;
23+
/** Screen orientation, when available in the browser. */
1324
orientation?: string;
25+
/** Global defaults merged with event-specific properties. */
1426
properties?: EventProperties;
27+
/** Marks a pageview exit signal. */
1528
exit?: boolean;
16-
// biome-ignore lint/suspicious/noExplicitAny: we want to allow any additional properties to be sent in the payload
17-
} & Record<string, any>;
29+
};
1830

1931
export type EventProperties = Record<string, string | number | boolean | null | undefined>;
2032

@@ -62,13 +74,13 @@ export type EventOptions = {
6274
properties?: EventProperties;
6375
};
6476

77+
const noWindow = typeof window === "undefined";
6578
let scriptEl: HTMLScriptElement | null = null;
6679
let endpoint: string | null = null;
6780
let entity: string | null = null;
6881
let referrer: string | null = null;
6982
let defaultExit = true;
70-
const noWindow = typeof window === "undefined";
71-
let currentExit: { endpoint: string; payload: Payload } | null = null;
83+
let currentExit: { endpoint: string; payload: EventPayload } | null = null;
7284
let exitListenerInstalled = false;
7385
let exitSentWhileHidden = false;
7486

@@ -151,6 +163,16 @@ const sanitizeUrl = (value: string) => {
151163
return url.toString();
152164
};
153165

166+
/** Set default properties for subsequent events. Pass `null` to remove a property. */
167+
export function setProperties(properties: EventProperties): void {
168+
const defaults = { ...globalThis.liwanProperties };
169+
for (const [key, value] of Object.entries(properties)) {
170+
if (value == null) delete defaults[key];
171+
else defaults[key] = value;
172+
}
173+
globalThis.liwanProperties = defaults;
174+
}
175+
154176
/**
155177
* Sends an event to the Liwan API.
156178
*
@@ -194,11 +216,11 @@ export async function event(name: string = "pageview", options?: EventOptions):
194216
const url = options?.url || (!noWindow ? location.href : null);
195217
if (!url) return reject("url is required");
196218

197-
const payload = <Payload>{
219+
let payload: EventPayload = {
198220
name,
199-
properties: options?.properties,
200-
entity_id: options?.entity || entity,
201-
referrer: options?.referrer || referrer,
221+
properties: { ...globalThis.liwanProperties, ...options?.properties },
222+
entity_id: options?.entity || entity || undefined,
223+
referrer: options?.referrer || referrer || undefined,
202224
url: sanitizeUrl(url),
203225
screen_width,
204226
orientation: noWindow
@@ -207,18 +229,21 @@ export async function event(name: string = "pageview", options?: EventOptions):
207229
? "portrait"
208230
: "landscape",
209231
};
232+
if (globalThis.liwanTransformEvent) {
233+
payload = globalThis.liwanTransformEvent(payload);
234+
}
210235
const response = await post(endpoint_url, payload);
211236

212237
if (!response.ok) {
213238
reject(`${response.status} ${response.statusText}`.trim());
214239
}
215240

216-
if (!noWindow && name === "pageview" && (options?.exit ?? defaultExit)) {
241+
if (!noWindow && payload.name === "pageview" && (options?.exit ?? defaultExit)) {
217242
currentExit = { endpoint: endpoint_url, payload };
218243
exitSentWhileHidden = false;
219244
installExitListener();
220245
sendCurrentExit();
221-
} else if (!noWindow && name === "pageview") {
246+
} else if (!noWindow && (name === "pageview" || payload.name === "pageview")) {
222247
currentExit = null;
223248
}
224249
}
@@ -230,6 +255,7 @@ export async function event(name: string = "pageview", options?: EventOptions):
230255
* navigations using the Navigation API when available, with `popstate` as a fallback.
231256
*
232257
* Calling this function marks Liwan as loaded through `window.__liwan_loaded`.
258+
* Subsequent calls are ignored.
233259
*
234260
* @param options Options passed to each pageview event.
235261
*
@@ -244,6 +270,7 @@ export async function event(name: string = "pageview", options?: EventOptions):
244270
* ```
245271
*/
246272
export const trackPageviews = (options?: EventOptions) => {
273+
if (window.__liwan_loaded) return log("Pageview tracking already started");
247274
window.__liwan_loaded = true;
248275
let lastPage: string | undefined;
249276

0 commit comments

Comments
 (0)