@databuddy/sdk 2.2.0 → 2.2.1

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.
@@ -0,0 +1,12 @@
1
+ import { LanguageModelV2 } from '@ai-sdk/provider';
2
+ import { db as Databuddy } from '../../node/index.mjs';
3
+
4
+ /**
5
+ * Wrap a Vercel language model with Databuddy middleware
6
+ * @param model - The Vercel language model to wrap, if you are using the Vercel AI Gateway, please use the LanguageModelV2 type e.g. gateway('xai/grok-3') instead of the string type e.g. 'xai/grok-3'
7
+ * @param buddy - The Databuddy instance to use
8
+ * @returns The wrapped language model, can be used in e.g. generateText from the ai package
9
+ */
10
+ declare const wrapVercelLanguageModel: (model: LanguageModelV2, buddy: Databuddy) => LanguageModelV2;
11
+
12
+ export { wrapVercelLanguageModel as withBuddy };
@@ -0,0 +1,12 @@
1
+ import { LanguageModelV2 } from '@ai-sdk/provider';
2
+ import { db as Databuddy } from '../../node/index.js';
3
+
4
+ /**
5
+ * Wrap a Vercel language model with Databuddy middleware
6
+ * @param model - The Vercel language model to wrap, if you are using the Vercel AI Gateway, please use the LanguageModelV2 type e.g. gateway('xai/grok-3') instead of the string type e.g. 'xai/grok-3'
7
+ * @param buddy - The Databuddy instance to use
8
+ * @returns The wrapped language model, can be used in e.g. generateText from the ai package
9
+ */
10
+ declare const wrapVercelLanguageModel: (model: LanguageModelV2, buddy: Databuddy) => LanguageModelV2;
11
+
12
+ export { wrapVercelLanguageModel as withBuddy };
@@ -0,0 +1,45 @@
1
+ import { wrapLanguageModel } from 'ai';
2
+ import { computeCostUSD } from 'tokenlens';
3
+
4
+ const buddyWare = (buddy) => {
5
+ return {
6
+ wrapGenerate: async ({ doGenerate, model }) => {
7
+ const result = await doGenerate();
8
+ const isToolCall = (part) => part.type === "tool-call";
9
+ const isToolResult = (part) => part.type === "tool-result";
10
+ const toolCalls = result.content.filter(isToolCall);
11
+ const toolResults = result.content.filter(isToolResult);
12
+ const toolCallNames = Array.from(
13
+ new Set(toolCalls.map((c) => c.toolName))
14
+ );
15
+ const costs = await computeCostUSD({
16
+ modelId: model.modelId,
17
+ provider: model.provider,
18
+ usage: result.usage
19
+ });
20
+ const payload = {
21
+ inputTokens: result.usage.inputTokens,
22
+ outputTokens: result.usage.outputTokens,
23
+ totalTokens: result.usage.totalTokens,
24
+ cachedInputTokens: result.usage.cachedInputTokens,
25
+ finishReason: result.finishReason,
26
+ toolCallCount: toolCalls.length,
27
+ toolResultCount: toolResults.length,
28
+ inputTokenCostUSD: costs.inputTokenCostUSD,
29
+ outputTokenCostUSD: costs.outputTokenCostUSD,
30
+ totalTokenCostUSD: costs.totalTokenCostUSD,
31
+ toolCallNames
32
+ };
33
+ console.log("payload", payload);
34
+ return result;
35
+ }
36
+ };
37
+ };
38
+ const wrapVercelLanguageModel = (model, buddy) => {
39
+ return wrapLanguageModel({
40
+ model,
41
+ middleware: buddyWare()
42
+ });
43
+ };
44
+
45
+ export { wrapVercelLanguageModel as withBuddy };
@@ -1,7 +1,7 @@
1
1
  import { S as StorageInterface, F as FlagsManager, a as FlagsManagerOptions, b as FlagResult, c as FlagState, d as FlagsConfig } from '../shared/@databuddy/sdk.YfiY9DoZ.mjs';
2
2
  export { e as FlagsContext } from '../shared/@databuddy/sdk.YfiY9DoZ.mjs';
3
- import { D as DatabuddyConfig, a as DatabuddyTracker, T as TrackFunction, b as Databuddy$1 } from '../shared/@databuddy/sdk.C8T93n5r.mjs';
4
- export { B as BaseEventProperties, e as DataAttributes, d as EventName, E as EventProperties, c as EventTypeMap, P as PropertiesForEvent, S as ScreenViewFunction, f as SetGlobalPropertiesFunction } from '../shared/@databuddy/sdk.C8T93n5r.mjs';
3
+ import { D as DatabuddyConfig, a as DatabuddyTracker, T as TrackFunction } from '../shared/@databuddy/sdk.DNing6--.mjs';
4
+ export { B as BaseEventProperties, d as DataAttributes, c as EventName, E as EventProperties, b as EventTypeMap, P as PropertiesForEvent, S as ScreenViewFunction, e as SetGlobalPropertiesFunction } from '../shared/@databuddy/sdk.DNing6--.mjs';
5
5
 
6
6
  /**
7
7
  * Auto-detect Databuddy client ID from environment variables
@@ -84,12 +84,29 @@ declare function trackError(message: string, properties?: {
84
84
  colno?: number;
85
85
  stack?: string;
86
86
  error_type?: string;
87
- [key: string]: any;
87
+ [key: string]: string | number | boolean | null | undefined;
88
88
  }): Promise<void>;
89
-
90
89
  /**
91
- * @deprecated Use Databuddy from `@databuddy/sdk/react` instead
90
+ * Get anonymous ID from multiple sources
91
+ * Priority: URL params > tracker instance > localStorage
92
+ */
93
+ declare function getAnonymousId(urlParams?: URLSearchParams): string | null;
94
+ /**
95
+ * Get session ID from multiple sources
96
+ * Priority: URL params > tracker instance > sessionStorage
97
+ */
98
+ declare function getSessionId(urlParams?: URLSearchParams): string | null;
99
+ /**
100
+ * Get tracking IDs (anonymous ID and session ID) from multiple sources
101
+ * Priority: URL params > tracker instance > localStorage/sessionStorage
102
+ */
103
+ declare function getTrackingIds(urlParams?: URLSearchParams): {
104
+ anonId: string | null;
105
+ sessionId: string | null;
106
+ };
107
+ /**
108
+ * Get tracking IDs as URL search params string
92
109
  */
93
- declare const Databuddy: typeof Databuddy$1;
110
+ declare function getTrackingParams(urlParams?: URLSearchParams): string;
94
111
 
95
- export { BrowserFlagStorage, CoreFlagsManager, Databuddy, DatabuddyConfig, DatabuddyTracker, FlagResult, FlagState, FlagsConfig, FlagsManager, FlagsManagerOptions, StorageInterface, TrackFunction, clear, createScript, detectClientId, flush, getTracker, isScriptInjected, isTrackerAvailable, track, trackError };
112
+ export { BrowserFlagStorage, CoreFlagsManager, DatabuddyConfig, DatabuddyTracker, FlagResult, FlagState, FlagsConfig, FlagsManager, FlagsManagerOptions, StorageInterface, TrackFunction, clear, createScript, detectClientId, flush, getAnonymousId, getSessionId, getTracker, getTrackingIds, getTrackingParams, isScriptInjected, isTrackerAvailable, track, trackError };
@@ -1,7 +1,7 @@
1
1
  import { S as StorageInterface, F as FlagsManager, a as FlagsManagerOptions, b as FlagResult, c as FlagState, d as FlagsConfig } from '../shared/@databuddy/sdk.YfiY9DoZ.js';
2
2
  export { e as FlagsContext } from '../shared/@databuddy/sdk.YfiY9DoZ.js';
3
- import { D as DatabuddyConfig, a as DatabuddyTracker, T as TrackFunction, b as Databuddy$1 } from '../shared/@databuddy/sdk.C8T93n5r.js';
4
- export { B as BaseEventProperties, e as DataAttributes, d as EventName, E as EventProperties, c as EventTypeMap, P as PropertiesForEvent, S as ScreenViewFunction, f as SetGlobalPropertiesFunction } from '../shared/@databuddy/sdk.C8T93n5r.js';
3
+ import { D as DatabuddyConfig, a as DatabuddyTracker, T as TrackFunction } from '../shared/@databuddy/sdk.DNing6--.js';
4
+ export { B as BaseEventProperties, d as DataAttributes, c as EventName, E as EventProperties, b as EventTypeMap, P as PropertiesForEvent, S as ScreenViewFunction, e as SetGlobalPropertiesFunction } from '../shared/@databuddy/sdk.DNing6--.js';
5
5
 
6
6
  /**
7
7
  * Auto-detect Databuddy client ID from environment variables
@@ -84,12 +84,29 @@ declare function trackError(message: string, properties?: {
84
84
  colno?: number;
85
85
  stack?: string;
86
86
  error_type?: string;
87
- [key: string]: any;
87
+ [key: string]: string | number | boolean | null | undefined;
88
88
  }): Promise<void>;
89
-
90
89
  /**
91
- * @deprecated Use Databuddy from `@databuddy/sdk/react` instead
90
+ * Get anonymous ID from multiple sources
91
+ * Priority: URL params > tracker instance > localStorage
92
+ */
93
+ declare function getAnonymousId(urlParams?: URLSearchParams): string | null;
94
+ /**
95
+ * Get session ID from multiple sources
96
+ * Priority: URL params > tracker instance > sessionStorage
97
+ */
98
+ declare function getSessionId(urlParams?: URLSearchParams): string | null;
99
+ /**
100
+ * Get tracking IDs (anonymous ID and session ID) from multiple sources
101
+ * Priority: URL params > tracker instance > localStorage/sessionStorage
102
+ */
103
+ declare function getTrackingIds(urlParams?: URLSearchParams): {
104
+ anonId: string | null;
105
+ sessionId: string | null;
106
+ };
107
+ /**
108
+ * Get tracking IDs as URL search params string
92
109
  */
93
- declare const Databuddy: typeof Databuddy$1;
110
+ declare function getTrackingParams(urlParams?: URLSearchParams): string;
94
111
 
95
- export { BrowserFlagStorage, CoreFlagsManager, Databuddy, DatabuddyConfig, DatabuddyTracker, FlagResult, FlagState, FlagsConfig, FlagsManager, FlagsManagerOptions, StorageInterface, TrackFunction, clear, createScript, detectClientId, flush, getTracker, isScriptInjected, isTrackerAvailable, track, trackError };
112
+ export { BrowserFlagStorage, CoreFlagsManager, DatabuddyConfig, DatabuddyTracker, FlagResult, FlagState, FlagsConfig, FlagsManager, FlagsManagerOptions, StorageInterface, TrackFunction, clear, createScript, detectClientId, flush, getAnonymousId, getSessionId, getTracker, getTrackingIds, getTrackingParams, isScriptInjected, isTrackerAvailable, track, trackError };
@@ -1,5 +1,4 @@
1
- import { D as Databuddy$1 } from '../shared/@databuddy/sdk.aVQee-4k.mjs';
2
- export { d as detectClientId } from '../shared/@databuddy/sdk.aVQee-4k.mjs';
1
+ export { d as detectClientId } from '../shared/@databuddy/sdk.BUsPV0LH.mjs';
3
2
  export { B as BrowserFlagStorage, C as CoreFlagsManager, c as createScript, i as isScriptInjected } from '../shared/@databuddy/sdk.tFAHtL2M.mjs';
4
3
 
5
4
  function isTrackerAvailable() {
@@ -21,7 +20,8 @@ const track = async (eventName, properties) => {
21
20
  }
22
21
  try {
23
22
  await tracker(eventName, properties);
24
- } catch (_error) {
23
+ } catch (error) {
24
+ console.error("Databuddy tracking error:", error);
25
25
  }
26
26
  };
27
27
  function clear() {
@@ -34,7 +34,8 @@ function clear() {
34
34
  }
35
35
  try {
36
36
  tracker();
37
- } catch (_error) {
37
+ } catch (error) {
38
+ console.error("Databuddy clear error:", error);
38
39
  }
39
40
  }
40
41
  function flush() {
@@ -47,13 +48,34 @@ function flush() {
47
48
  }
48
49
  try {
49
50
  tracker();
50
- } catch (_error) {
51
+ } catch (error) {
52
+ console.error("Databuddy flush error:", error);
51
53
  }
52
54
  }
53
55
  function trackError(message, properties) {
54
56
  return track("error", { message, ...properties });
55
57
  }
58
+ function getAnonymousId(urlParams) {
59
+ if (typeof window === "undefined") return null;
60
+ return urlParams?.get("anonId") || window.databuddy?.anonymousId || localStorage.getItem("did") || null;
61
+ }
62
+ function getSessionId(urlParams) {
63
+ if (typeof window === "undefined") return null;
64
+ return urlParams?.get("sessionId") || window.databuddy?.sessionId || sessionStorage.getItem("did_session") || null;
65
+ }
66
+ function getTrackingIds(urlParams) {
67
+ return {
68
+ anonId: getAnonymousId(urlParams),
69
+ sessionId: getSessionId(urlParams)
70
+ };
71
+ }
72
+ function getTrackingParams(urlParams) {
73
+ const anonId = getAnonymousId(urlParams);
74
+ const sessionId = getSessionId(urlParams);
75
+ const params = new URLSearchParams();
76
+ if (anonId) params.set("anonId", anonId);
77
+ if (sessionId) params.set("sessionId", sessionId);
78
+ return params.toString();
79
+ }
56
80
 
57
- const Databuddy = Databuddy$1;
58
-
59
- export { Databuddy, clear, flush, getTracker, isTrackerAvailable, track, trackError };
81
+ export { clear, flush, getAnonymousId, getSessionId, getTracker, getTrackingIds, getTrackingParams, isTrackerAvailable, track, trackError };
@@ -5,57 +5,85 @@ interface Logger {
5
5
  debug(msg: string, data?: Record<string, unknown>): void;
6
6
  }
7
7
 
8
+ /**
9
+ * Middleware function that can transform or filter events
10
+ * Return null to drop the event, or return a modified event
11
+ */
12
+ type Middleware = (event: BatchEventInput) => BatchEventInput | null | Promise<BatchEventInput | null>;
8
13
  interface DatabuddyConfig {
14
+ /** Client ID from Databuddy dashboard */
9
15
  clientId: string;
16
+ /** Custom API endpoint (default: https://basket.databuddy.cc) */
10
17
  apiUrl?: string;
18
+ /** Enable debug logging */
11
19
  debug?: boolean;
20
+ /** Custom logger instance */
12
21
  logger?: Logger;
13
- /**
14
- * Enable automatic batching of events
15
- * Default: true
16
- */
22
+ /** Enable automatic batching (default: true) */
17
23
  enableBatching?: boolean;
18
- /**
19
- * Number of events to batch before auto-flushing
20
- * Default: 10, Max: 100
21
- */
24
+ /** Number of events to batch before flushing (default: 10, max: 100) */
22
25
  batchSize?: number;
23
- /**
24
- * Time in milliseconds before auto-flushing batched events
25
- * Default: 2000ms (2 seconds)
26
- */
26
+ /** Time in ms before auto-flushing batched events (default: 2000) */
27
27
  batchTimeout?: number;
28
- /**
29
- * Maximum number of events to queue before auto-flushing
30
- * Default: 1000
31
- */
28
+ /** Maximum number of events to queue (default: 1000) */
32
29
  maxQueueSize?: number;
30
+ /** Middleware functions to transform events */
31
+ middleware?: Middleware[];
32
+ /** Enable event deduplication based on eventId (default: true) */
33
+ enableDeduplication?: boolean;
34
+ /** Maximum deduplication cache size (default: 10000) */
35
+ maxDeduplicationCacheSize?: number;
33
36
  }
34
37
  interface CustomEventInput {
38
+ /** Event name (required) */
35
39
  name: string;
40
+ /** Unique event ID for deduplication */
36
41
  eventId?: string;
42
+ /** Anonymous user ID */
37
43
  anonymousId?: string | null;
44
+ /** Session ID */
38
45
  sessionId?: string | null;
46
+ /** Event timestamp in milliseconds */
39
47
  timestamp?: number | null;
48
+ /** Event properties/metadata */
40
49
  properties?: Record<string, unknown> | null;
41
50
  }
42
51
  interface EventResponse {
52
+ /** Whether the event was successfully sent */
43
53
  success: boolean;
54
+ /** Server-assigned event ID */
44
55
  eventId?: string;
56
+ /** Error message if failed */
45
57
  error?: string;
46
58
  }
47
59
  interface BatchEventInput {
60
+ /** Event type */
48
61
  type: 'custom';
62
+ /** Event name */
49
63
  name: string;
64
+ /** Unique event ID for deduplication */
50
65
  eventId?: string;
66
+ /** Anonymous user ID */
51
67
  anonymousId?: string | null;
68
+ /** Session ID */
52
69
  sessionId?: string | null;
70
+ /** Event timestamp in milliseconds */
53
71
  timestamp?: number | null;
72
+ /** Event properties/metadata */
54
73
  properties?: Record<string, unknown> | null;
55
74
  }
75
+ /**
76
+ * Global properties that will be attached to all events
77
+ */
78
+ interface GlobalProperties {
79
+ [key: string]: unknown;
80
+ }
56
81
  interface BatchEventResponse {
82
+ /** Whether the batch was successfully sent */
57
83
  success: boolean;
84
+ /** Number of events processed */
58
85
  processed?: number;
86
+ /** Results for each event in the batch */
59
87
  results?: Array<{
60
88
  status: string;
61
89
  type?: string;
@@ -63,6 +91,7 @@ interface BatchEventResponse {
63
91
  message?: string;
64
92
  error?: string;
65
93
  }>;
94
+ /** Error message if batch failed */
66
95
  error?: string;
67
96
  }
68
97
 
@@ -75,20 +104,21 @@ declare class Databuddy {
75
104
  private batchTimeout;
76
105
  private queue;
77
106
  private flushTimer;
107
+ private globalProperties;
108
+ private middleware;
109
+ private enableDeduplication;
110
+ private deduplicationCache;
111
+ private maxDeduplicationCacheSize;
78
112
  constructor(config: DatabuddyConfig);
79
113
  /**
80
114
  * Track a custom event
81
- * If batching is enabled, queues the event and auto-flushes when batch size is reached or timeout expires
82
- * If batching is disabled, sends the event immediately
83
- *
84
- * @param event - Custom event data
85
- * @returns Response indicating success or failure
86
- *
115
+ * @param event - Event data to track
116
+ * @returns Promise with success/error response
87
117
  * @example
88
118
  * ```typescript
89
119
  * await client.track({
90
120
  * name: 'user_signup',
91
- * properties: { plan: 'pro' }
121
+ * properties: { plan: 'pro', source: 'web' }
92
122
  * });
93
123
  * ```
94
124
  */
@@ -97,26 +127,19 @@ declare class Databuddy {
97
127
  private scheduleFlush;
98
128
  /**
99
129
  * Manually flush all queued events
100
- * Important for serverless/stateless environments where you need to ensure events are sent before the process exits
101
- *
102
- * @returns Response with batch results
103
- *
130
+ * Useful in serverless environments to ensure events are sent before process exits
131
+ * @returns Promise with batch results
104
132
  * @example
105
133
  * ```typescript
106
- * // In serverless function
107
134
  * await client.track({ name: 'api_call' });
108
- * await client.flush(); // Ensure events are sent before function exits
135
+ * await client.flush(); // Ensure events are sent
109
136
  * ```
110
137
  */
111
138
  flush(): Promise<BatchEventResponse>;
112
139
  /**
113
- * Send multiple custom events in a single batch request
114
- * Max 100 events per batch
115
- * Note: Usually you don't need to call this directly - use track() with batching enabled instead
116
- *
117
- * @param events - Array of custom events
118
- * @returns Response with results for each event
119
- *
140
+ * Send multiple events in a single batch request
141
+ * @param events - Array of events to batch (max 100)
142
+ * @returns Promise with batch results
120
143
  * @example
121
144
  * ```typescript
122
145
  * await client.batch([
@@ -126,7 +149,89 @@ declare class Databuddy {
126
149
  * ```
127
150
  */
128
151
  batch(events: BatchEventInput[]): Promise<BatchEventResponse>;
152
+ /**
153
+ * Set global properties attached to all events
154
+ * Properties are merged with existing globals; event properties override globals
155
+ * @param properties - Properties to merge with existing globals
156
+ * @example
157
+ * ```typescript
158
+ * client.setGlobalProperties({ environment: 'production', version: '1.0.0' });
159
+ * // All subsequent events will include these properties
160
+ * ```
161
+ */
162
+ setGlobalProperties(properties: GlobalProperties): void;
163
+ /**
164
+ * Get current global properties
165
+ * @returns Copy of current global properties
166
+ * @example
167
+ * ```typescript
168
+ * const globals = client.getGlobalProperties();
169
+ * console.log(globals); // { environment: 'production', version: '1.0.0' }
170
+ * ```
171
+ */
172
+ getGlobalProperties(): GlobalProperties;
173
+ /**
174
+ * Clear all global properties
175
+ * @example
176
+ * ```typescript
177
+ * client.clearGlobalProperties();
178
+ * // No more global properties will be attached to events
179
+ * ```
180
+ */
181
+ clearGlobalProperties(): void;
182
+ /**
183
+ * Add middleware to transform events
184
+ * Middleware runs before deduplication and is executed in order
185
+ * Return null to drop the event, or return a modified event
186
+ * @param middleware - Middleware function
187
+ * @example
188
+ * ```typescript
189
+ * client.addMiddleware((event) => {
190
+ * // Add custom field
191
+ * event.properties = { ...event.properties, processed: true };
192
+ * return event;
193
+ * });
194
+ *
195
+ * // Drop events matching a condition
196
+ * client.addMiddleware((event) => {
197
+ * if (event.name === 'unwanted_event') return null;
198
+ * return event;
199
+ * });
200
+ * ```
201
+ */
202
+ addMiddleware(middleware: Middleware): void;
203
+ /**
204
+ * Remove all middleware functions
205
+ * @example
206
+ * ```typescript
207
+ * client.clearMiddleware();
208
+ * // All middleware transformations removed
209
+ * ```
210
+ */
211
+ clearMiddleware(): void;
212
+ /**
213
+ * Get current deduplication cache size
214
+ * @returns Number of event IDs in cache
215
+ * @example
216
+ * ```typescript
217
+ * const size = client.getDeduplicationCacheSize();
218
+ * console.log(`Cache size: ${size}`);
219
+ * ```
220
+ */
221
+ getDeduplicationCacheSize(): number;
222
+ /**
223
+ * Clear the deduplication cache
224
+ * Useful for testing or resetting duplicate detection
225
+ * @example
226
+ * ```typescript
227
+ * client.clearDeduplicationCache();
228
+ * // All cached event IDs cleared
229
+ * ```
230
+ */
231
+ clearDeduplicationCache(): void;
232
+ private applyMiddleware;
233
+ private addToDeduplicationCache;
129
234
  }
130
235
 
131
236
  export { Databuddy, Databuddy as db };
132
- export type { BatchEventInput, BatchEventResponse, CustomEventInput, DatabuddyConfig, EventResponse, Logger };
237
+ export type { BatchEventInput, BatchEventResponse, CustomEventInput, DatabuddyConfig, EventResponse, GlobalProperties, Logger, Middleware };