1- /**
2- * Databuddy SDK Client-side Tracker
3- * Provides type-safe tracking functions
4- */
5-
61import type { DatabuddyTracker } from "./types" ;
72
83/**
9- * Check if the Databuddy tracker is available
4+ * Checks if the Databuddy tracker script has loaded and is available.
5+ * Use this before calling tracking functions in conditional scenarios.
6+ *
7+ * @returns `true` if tracker is available, `false` if not loaded or on server
8+ *
9+ * @example
10+ * ```ts
11+ * import { isTrackerAvailable, track } from "@databuddy/sdk";
12+ *
13+ * if (isTrackerAvailable()) {
14+ * track("feature_used", { feature: "export" });
15+ * }
16+ * ```
1017 */
1118export function isTrackerAvailable ( ) : boolean {
1219 return typeof window !== "undefined" && ( ! ! window . databuddy || ! ! window . db ) ;
1320}
1421
1522/**
16- * Get the Databuddy tracker instance
23+ * Returns the raw Databuddy tracker instance for advanced use cases.
24+ * Prefer using the exported functions (`track`, `flush`, etc.) instead.
25+ *
26+ * @returns Tracker instance or `null` if not available
27+ *
28+ * @example
29+ * ```ts
30+ * import { getTracker } from "@databuddy/sdk";
31+ *
32+ * const tracker = getTracker();
33+ * if (tracker) {
34+ * console.log("Anonymous ID:", tracker.anonymousId);
35+ * console.log("Session ID:", tracker.sessionId);
36+ * }
37+ * ```
1738 */
1839export function getTracker ( ) : DatabuddyTracker | null {
1940 if ( typeof window === "undefined" ) {
@@ -23,18 +44,46 @@ export function getTracker(): DatabuddyTracker | null {
2344}
2445
2546/**
26- * Track a custom event (lean, goes to custom_event_spans table)
47+ * Tracks a custom event with optional properties.
48+ * Events are batched and sent efficiently to minimize network overhead.
49+ * Safe to call on server (no-op) or before tracker loads.
50+ *
51+ * @param name - Event name (e.g., "button_click", "purchase", "signup")
52+ * @param properties - Key-value pairs of event data
53+ *
54+ * @example
55+ * ```ts
56+ * import { track } from "@databuddy/sdk";
57+ *
58+ * // Simple event
59+ * track("signup_started");
60+ *
61+ * // Event with properties
62+ * track("item_purchased", {
63+ * itemId: "sku-123",
64+ * price: 29.99,
65+ * currency: "USD"
66+ * });
67+ *
68+ * // In a React component
69+ * function CheckoutButton() {
70+ * return (
71+ * <button onClick={() => track("checkout_clicked", { cartSize: 3 }) }>
72+ * Checkout
73+ * </button>
74+ * );
75+ * }
76+ * ```
2777 */
28- export function trackCustomEvent (
78+ export function track (
2979 name : string ,
3080 properties ?: Record < string , unknown >
3181) : void {
3282 if ( typeof window === "undefined" ) {
3383 return ;
3484 }
3585
36- const tracker =
37- window . db ?. trackCustomEvent || window . databuddy ?. trackCustomEvent ;
86+ const tracker = window . db ?. track || window . databuddy ?. track ;
3887
3988 if ( ! tracker ) {
4089 return ;
@@ -43,23 +92,32 @@ export function trackCustomEvent(
4392 try {
4493 tracker ( name , properties ) ;
4594 } catch ( error ) {
46- console . error ( "Databuddy trackCustomEvent error:" , error ) ;
95+ console . error ( "Databuddy track error:" , error ) ;
4796 }
4897}
4998
50- /**
51- * Track a custom event (alias for trackCustomEvent)
52- * Goes to the lean custom_event_spans table
53- */
54- export function track (
55- eventName : string ,
99+ /** @deprecated Use `track()` instead. Will be removed in v3.0. */
100+ export function trackCustomEvent (
101+ name : string ,
56102 properties ?: Record < string , unknown >
57103) : void {
58- trackCustomEvent ( eventName , properties ) ;
104+ track ( name , properties ) ;
59105}
60106
61107/**
62- * Clear the current session
108+ * Clears the current user session and generates new anonymous/session IDs.
109+ * Use after logout to ensure the next user gets a fresh identity.
110+ *
111+ * @example
112+ * ```ts
113+ * import { clear } from "@databuddy/sdk";
114+ *
115+ * async function handleLogout() {
116+ * await signOut();
117+ * clear(); // Reset tracking identity
118+ * router.push("/login");
119+ * }
120+ * ```
63121 */
64122export function clear ( ) : void {
65123 if ( typeof window === "undefined" ) {
@@ -80,7 +138,19 @@ export function clear(): void {
80138}
81139
82140/**
83- * Flush any queued events
141+ * Forces all queued events to be sent immediately.
142+ * Useful before navigation or when you need to ensure events are captured.
143+ *
144+ * @example
145+ * ```ts
146+ * import { track, flush } from "@databuddy/sdk";
147+ *
148+ * function handleExternalLink(url: string) {
149+ * track("external_link_clicked", { url });
150+ * flush(); // Ensure event is sent before leaving
151+ * window.location.href = url;
152+ * }
153+ * ```
84154 */
85155export function flush ( ) : void {
86156 if ( typeof window === "undefined" ) {
@@ -101,7 +171,25 @@ export function flush(): void {
101171}
102172
103173/**
104- * Track an error event
174+ * Tracks an error event. Convenience wrapper around `track("error", ...)`.
175+ *
176+ * @param message - Error message
177+ * @param properties - Additional error context (filename, line number, stack trace)
178+ *
179+ * @example
180+ * ```ts
181+ * import { trackError } from "@databuddy/sdk";
182+ *
183+ * try {
184+ * await riskyOperation();
185+ * } catch (error) {
186+ * trackError(error.message, {
187+ * stack: error.stack,
188+ * error_type: error.name,
189+ * context: "checkout_flow"
190+ * });
191+ * }
192+ * ```
105193 */
106194export function trackError (
107195 message : string ,
@@ -118,8 +206,30 @@ export function trackError(
118206}
119207
120208/**
121- * Get anonymous ID from multiple sources
122- * Priority: URL params > tracker instance > localStorage
209+ * Gets the anonymous user ID. Persists across sessions via localStorage.
210+ * Useful for server-side identification or cross-domain tracking.
211+ *
212+ * @param urlParams - Optional URLSearchParams to check for `anonId` param (highest priority)
213+ * @returns Anonymous ID or `null` if unavailable
214+ *
215+ * Priority: URL params → tracker instance → localStorage
216+ *
217+ * @example
218+ * ```ts
219+ * import { getAnonymousId } from "@databuddy/sdk";
220+ *
221+ * // Get from tracker
222+ * const anonId = getAnonymousId();
223+ *
224+ * // Check URL params first (for cross-domain tracking)
225+ * const params = new URLSearchParams(window.location.search);
226+ * const anonId = getAnonymousId(params);
227+ *
228+ * // Pass to server
229+ * await fetch("/api/identify", {
230+ * body: JSON.stringify({ anonId })
231+ * });
232+ * ```
123233 */
124234export function getAnonymousId ( urlParams ?: URLSearchParams ) : string | null {
125235 if ( typeof window === "undefined" ) {
@@ -134,8 +244,21 @@ export function getAnonymousId(urlParams?: URLSearchParams): string | null {
134244}
135245
136246/**
137- * Get session ID from multiple sources
138- * Priority: URL params > tracker instance > sessionStorage
247+ * Gets the current session ID. Resets after 30 min of inactivity.
248+ * Useful for correlating events within a single browsing session.
249+ *
250+ * @param urlParams - Optional URLSearchParams to check for `sessionId` param (highest priority)
251+ * @returns Session ID or `null` if unavailable
252+ *
253+ * Priority: URL params → tracker instance → sessionStorage
254+ *
255+ * @example
256+ * ```ts
257+ * import { getSessionId } from "@databuddy/sdk";
258+ *
259+ * const sessionId = getSessionId();
260+ * console.log("Current session:", sessionId);
261+ * ```
139262 */
140263export function getSessionId ( urlParams ?: URLSearchParams ) : string | null {
141264 if ( typeof window === "undefined" ) {
@@ -150,8 +273,20 @@ export function getSessionId(urlParams?: URLSearchParams): string | null {
150273}
151274
152275/**
153- * Get tracking IDs (anonymous ID and session ID) from multiple sources
154- * Priority: URL params > tracker instance > localStorage/sessionStorage
276+ * Gets both anonymous ID and session ID in a single call.
277+ *
278+ * @param urlParams - Optional URLSearchParams to check for tracking params
279+ * @returns Object with `anonId` and `sessionId` (either may be null)
280+ *
281+ * @example
282+ * ```ts
283+ * import { getTrackingIds } from "@databuddy/sdk";
284+ *
285+ * const { anonId, sessionId } = getTrackingIds();
286+ *
287+ * // Send to your backend
288+ * await api.identify({ anonId, sessionId, userId: user.id });
289+ * ```
155290 */
156291export function getTrackingIds ( urlParams ?: URLSearchParams ) : {
157292 anonId : string | null ;
@@ -164,7 +299,25 @@ export function getTrackingIds(urlParams?: URLSearchParams): {
164299}
165300
166301/**
167- * Get tracking IDs as URL search params string
302+ * Returns tracking IDs as a URL query string for cross-domain tracking.
303+ * Append to URLs when linking to other domains you own.
304+ *
305+ * @param urlParams - Optional URLSearchParams to preserve existing params
306+ * @returns Query string like `"anonId=xxx&sessionId=yyy"` or empty string
307+ *
308+ * @example
309+ * ```ts
310+ * import { getTrackingParams } from "@databuddy/sdk";
311+ *
312+ * // Link to subdomain with tracking continuity
313+ * const params = getTrackingParams();
314+ * const url = `https://app.example.com/dashboard${params ? `?${params}` : "" }`;
315+ *
316+ * // In a component
317+ * <a href={`https://shop.example.com?${getTrackingParams()}` }>
318+ * Visit Shop
319+ * </a>
320+ * ```
168321 */
169322export function getTrackingParams ( urlParams ?: URLSearchParams ) : string {
170323 const anonId = getAnonymousId ( urlParams ) ;
0 commit comments