@kitbase/analytics-react 0.1.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/README.md ADDED
@@ -0,0 +1,179 @@
1
+ # @kitbase/analytics-react
2
+
3
+ React integration for the Kitbase Analytics SDK. Provides hooks and context provider for easy integration with React applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @kitbase/analytics-react
9
+ # or
10
+ pnpm add @kitbase/analytics-react
11
+ # or
12
+ yarn add @kitbase/analytics-react
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```tsx
18
+ import { KitbaseAnalyticsProvider, useTrack } from '@kitbase/analytics-react';
19
+
20
+ function App() {
21
+ return (
22
+ <KitbaseAnalyticsProvider config={{ sdkKey: 'your-api-key' }}>
23
+ <MyComponent />
24
+ </KitbaseAnalyticsProvider>
25
+ );
26
+ }
27
+
28
+ function MyComponent() {
29
+ const track = useTrack();
30
+
31
+ return (
32
+ <button onClick={() => track({ channel: 'ui', event: 'Button Clicked' })}>
33
+ Click me
34
+ </button>
35
+ );
36
+ }
37
+ ```
38
+
39
+ ## API Reference
40
+
41
+ ### Provider
42
+
43
+ #### `KitbaseAnalyticsProvider`
44
+
45
+ Wrap your app with this provider to initialize Kitbase.
46
+
47
+ ```tsx
48
+ <KitbaseAnalyticsProvider
49
+ config={{
50
+ sdkKey: 'your-api-key',
51
+ debug: true,
52
+ analytics: { autoTrackPageViews: true },
53
+ }}
54
+ >
55
+ <App />
56
+ </KitbaseAnalyticsProvider>
57
+ ```
58
+
59
+ ### Hooks
60
+
61
+ | Hook | Description |
62
+ |------|-------------|
63
+ | `useKitbaseAnalytics()` | Access the KitbaseAnalytics instance directly |
64
+ | `useTrack()` | Track custom events |
65
+ | `useIdentify()` | Identify users |
66
+ | `usePageView()` | Track page views manually |
67
+ | `useAutoPageView(options?, deps?)` | Auto-track page views on mount/deps change |
68
+ | `useRevenue()` | Track revenue events |
69
+ | `useTimeEvent(eventName)` | Track event duration |
70
+ | `useSuperProperties(props, deps?)` | Register super properties |
71
+ | `useUserId()` | Get the identified user ID |
72
+ | `useReset()` | Reset user identity |
73
+
74
+ ### Direct Instance Access
75
+
76
+ For features not covered by the convenience hooks (plugins, debug mode, etc.), use `useKitbaseAnalytics()` to get the raw `KitbaseAnalytics` instance:
77
+
78
+ ```tsx
79
+ import { useKitbaseAnalytics, WebVitalsPlugin } from '@kitbase/analytics-react';
80
+
81
+ function PluginLoader() {
82
+ const kitbase = useKitbaseAnalytics();
83
+
84
+ useEffect(() => {
85
+ kitbase.use(new WebVitalsPlugin());
86
+ console.log('Active plugins:', kitbase.getPlugins());
87
+ }, [kitbase]);
88
+
89
+ return null;
90
+ }
91
+ ```
92
+
93
+ ### Re-exported Types
94
+
95
+ All types, errors, and utilities from `@kitbase/analytics` are re-exported, so you can import everything from a single package:
96
+
97
+ ```tsx
98
+ import {
99
+ type KitbaseConfig,
100
+ type TrackOptions,
101
+ type KitbasePlugin,
102
+ KitbaseError,
103
+ ValidationError,
104
+ } from '@kitbase/analytics-react';
105
+ ```
106
+
107
+ ### Examples
108
+
109
+ #### Track Events
110
+
111
+ ```tsx
112
+ function Button() {
113
+ const track = useTrack();
114
+
115
+ return (
116
+ <button onClick={() => track({
117
+ channel: 'ui',
118
+ event: 'Button Clicked',
119
+ tags: { button_id: 'cta' }
120
+ })}>
121
+ Click me
122
+ </button>
123
+ );
124
+ }
125
+ ```
126
+
127
+ #### Identify Users
128
+
129
+ ```tsx
130
+ function LoginForm() {
131
+ const identify = useIdentify();
132
+
133
+ const handleLogin = async (user: User) => {
134
+ await identify({
135
+ userId: user.id,
136
+ traits: { email: user.email, plan: user.plan }
137
+ });
138
+ };
139
+
140
+ return <form>...</form>;
141
+ }
142
+ ```
143
+
144
+ #### Auto Track Page Views
145
+
146
+ ```tsx
147
+ function ProductPage({ productId }: { productId: string }) {
148
+ useAutoPageView(
149
+ { tags: { product_id: productId } },
150
+ [productId]
151
+ );
152
+
153
+ return <div>Product {productId}</div>;
154
+ }
155
+ ```
156
+
157
+ #### Track Duration
158
+
159
+ ```tsx
160
+ function VideoPlayer() {
161
+ const { start } = useTimeEvent('Video Watched');
162
+ const track = useTrack();
163
+
164
+ return (
165
+ <video
166
+ onPlay={start}
167
+ onEnded={() => track({
168
+ channel: 'engagement',
169
+ event: 'Video Watched',
170
+ // $duration automatically included
171
+ })}
172
+ />
173
+ );
174
+ }
175
+ ```
176
+
177
+ ## License
178
+
179
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.tsx
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ KitbaseAnalyticsProvider: () => KitbaseAnalyticsProvider,
25
+ useAutoPageView: () => useAutoPageView,
26
+ useIdentify: () => useIdentify,
27
+ useKitbaseAnalytics: () => useKitbaseAnalytics,
28
+ usePageView: () => usePageView,
29
+ useReset: () => useReset,
30
+ useRevenue: () => useRevenue,
31
+ useSuperProperties: () => useSuperProperties,
32
+ useTimeEvent: () => useTimeEvent,
33
+ useTrack: () => useTrack,
34
+ useUserId: () => useUserId
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+ var import_react = require("react");
38
+ var import_analytics = require("@kitbase/analytics");
39
+ __reExport(index_exports, require("@kitbase/analytics"), module.exports);
40
+ var import_jsx_runtime = require("react/jsx-runtime");
41
+ var KitbaseAnalyticsContext = (0, import_react.createContext)(null);
42
+ function KitbaseAnalyticsProvider({ config, children }) {
43
+ const kitbaseRef = (0, import_react.useRef)(null);
44
+ if (!kitbaseRef.current) {
45
+ kitbaseRef.current = new import_analytics.KitbaseAnalytics(config);
46
+ }
47
+ (0, import_react.useEffect)(() => {
48
+ return () => {
49
+ kitbaseRef.current?.shutdown();
50
+ };
51
+ }, []);
52
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(KitbaseAnalyticsContext.Provider, { value: kitbaseRef.current, children });
53
+ }
54
+ function useKitbaseAnalytics() {
55
+ const context = (0, import_react.useContext)(KitbaseAnalyticsContext);
56
+ if (!context) {
57
+ throw new Error("useKitbaseAnalytics must be used within a KitbaseAnalyticsProvider");
58
+ }
59
+ return context;
60
+ }
61
+ function useTrack() {
62
+ const kitbase = useKitbaseAnalytics();
63
+ return (0, import_react.useCallback)(
64
+ (options) => {
65
+ return kitbase.track(options);
66
+ },
67
+ [kitbase]
68
+ );
69
+ }
70
+ function useIdentify() {
71
+ const kitbase = useKitbaseAnalytics();
72
+ return (0, import_react.useCallback)(
73
+ (options) => {
74
+ return kitbase.identify(options);
75
+ },
76
+ [kitbase]
77
+ );
78
+ }
79
+ function usePageView() {
80
+ const kitbase = useKitbaseAnalytics();
81
+ return (0, import_react.useCallback)(
82
+ (options) => {
83
+ return kitbase.trackPageView(options);
84
+ },
85
+ [kitbase]
86
+ );
87
+ }
88
+ function useAutoPageView(options, deps = []) {
89
+ const kitbase = useKitbaseAnalytics();
90
+ (0, import_react.useEffect)(() => {
91
+ kitbase.trackPageView(options);
92
+ }, deps);
93
+ }
94
+ function useRevenue() {
95
+ const kitbase = useKitbaseAnalytics();
96
+ return (0, import_react.useCallback)(
97
+ (options) => {
98
+ return kitbase.trackRevenue(options);
99
+ },
100
+ [kitbase]
101
+ );
102
+ }
103
+ function useTimeEvent(eventName) {
104
+ const kitbase = useKitbaseAnalytics();
105
+ return (0, import_react.useMemo)(
106
+ () => ({
107
+ start: () => kitbase.timeEvent(eventName),
108
+ stop: () => kitbase.cancelTimeEvent(eventName),
109
+ getDuration: () => kitbase.getEventDuration(eventName)
110
+ }),
111
+ [kitbase, eventName]
112
+ );
113
+ }
114
+ function useSuperProperties(properties, deps = []) {
115
+ const kitbase = useKitbaseAnalytics();
116
+ (0, import_react.useEffect)(() => {
117
+ kitbase.register(properties);
118
+ }, deps);
119
+ }
120
+ function useUserId() {
121
+ const kitbase = useKitbaseAnalytics();
122
+ return kitbase.getUserId();
123
+ }
124
+ function useReset() {
125
+ const kitbase = useKitbaseAnalytics();
126
+ return (0, import_react.useCallback)(() => {
127
+ kitbase.reset();
128
+ }, [kitbase]);
129
+ }
130
+ // Annotate the CommonJS export names for ESM import in node:
131
+ 0 && (module.exports = {
132
+ KitbaseAnalyticsProvider,
133
+ useAutoPageView,
134
+ useIdentify,
135
+ useKitbaseAnalytics,
136
+ usePageView,
137
+ useReset,
138
+ useRevenue,
139
+ useSuperProperties,
140
+ useTimeEvent,
141
+ useTrack,
142
+ useUserId,
143
+ ...require("@kitbase/analytics")
144
+ });
145
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.tsx"],"sourcesContent":["/**\n * React integration for Kitbase Analytics SDK\n *\n * Provides React hooks and context provider for easy integration\n * with React applications.\n *\n * @example\n * ```tsx\n * import { KitbaseAnalyticsProvider, useKitbaseAnalytics, useTrack } from '@kitbase/analytics-react';\n *\n * function App() {\n * return (\n * <KitbaseAnalyticsProvider config={{ sdkKey: 'your-api-key' }}>\n * <MyComponent />\n * </KitbaseAnalyticsProvider>\n * );\n * }\n *\n * function MyComponent() {\n * const track = useTrack();\n *\n * return (\n * <button onClick={() => track({ channel: 'ui', event: 'Button Clicked' })}>\n * Click me\n * </button>\n * );\n * }\n * ```\n *\n * @packageDocumentation\n */\n\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useMemo,\n useCallback,\n type ReactNode,\n} from 'react';\nimport {\n KitbaseAnalytics,\n type KitbaseConfig,\n type TrackOptions,\n type TrackResponse,\n type PageViewOptions,\n type RevenueOptions,\n type IdentifyOptions,\n type Tags,\n} from '@kitbase/analytics';\n\n// Re-export everything from core\nexport * from '@kitbase/analytics';\n\n// ============================================================\n// Context\n// ============================================================\n\nconst KitbaseAnalyticsContext = createContext<KitbaseAnalytics | null>(null);\n\n/**\n * Props for the KitbaseAnalyticsProvider component\n */\nexport interface KitbaseAnalyticsProviderProps {\n /**\n * KitbaseAnalytics configuration options\n */\n config: KitbaseConfig;\n\n /**\n * React children to render\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that initializes KitbaseAnalytics and makes it available\n * to all child components via React context.\n *\n * @example\n * ```tsx\n * import { KitbaseAnalyticsProvider } from '@kitbase/analytics-react';\n *\n * function App() {\n * return (\n * <KitbaseAnalyticsProvider\n * config={{\n * sdkKey: 'your-api-key',\n * debug: true,\n * analytics: { autoTrackPageViews: true },\n * }}\n * >\n * <YourApp />\n * </KitbaseAnalyticsProvider>\n * );\n * }\n * ```\n */\nexport function KitbaseAnalyticsProvider({ config, children }: KitbaseAnalyticsProviderProps) {\n const kitbaseRef = useRef<KitbaseAnalytics | null>(null);\n\n // Initialize KitbaseAnalytics instance once\n if (!kitbaseRef.current) {\n kitbaseRef.current = new KitbaseAnalytics(config);\n }\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n kitbaseRef.current?.shutdown();\n };\n }, []);\n\n return (\n <KitbaseAnalyticsContext.Provider value={kitbaseRef.current}>\n {children}\n </KitbaseAnalyticsContext.Provider>\n );\n}\n\n// ============================================================\n// Hooks\n// ============================================================\n\n/**\n * Hook to access the KitbaseAnalytics instance directly.\n *\n * @returns The KitbaseAnalytics instance\n * @throws Error if used outside of KitbaseAnalyticsProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const kitbase = useKitbaseAnalytics();\n *\n * useEffect(() => {\n * kitbase.register({ page: 'home' });\n * }, [kitbase]);\n *\n * return <div>My Component</div>;\n * }\n * ```\n */\nexport function useKitbaseAnalytics(): KitbaseAnalytics {\n const context = useContext(KitbaseAnalyticsContext);\n\n if (!context) {\n throw new Error('useKitbaseAnalytics must be used within a KitbaseAnalyticsProvider');\n }\n\n return context;\n}\n\n/**\n * Hook to get a memoized track function.\n *\n * @returns A function to track events\n *\n * @example\n * ```tsx\n * function Button() {\n * const track = useTrack();\n *\n * const handleClick = () => {\n * track({\n * channel: 'ui',\n * event: 'Button Clicked',\n * tags: { button_id: 'cta' },\n * });\n * };\n *\n * return <button onClick={handleClick}>Click me</button>;\n * }\n * ```\n */\nexport function useTrack() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: TrackOptions): Promise<TrackResponse | void> => {\n return kitbase.track(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to get a memoized identify function.\n *\n * @returns A function to identify users\n *\n * @example\n * ```tsx\n * function LoginForm() {\n * const identify = useIdentify();\n *\n * const handleLogin = async (userId: string, email: string) => {\n * await identify({\n * userId,\n * traits: { email },\n * });\n * };\n *\n * return <form>...</form>;\n * }\n * ```\n */\nexport function useIdentify() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: IdentifyOptions): Promise<void> => {\n return kitbase.identify(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to get a memoized page view tracking function.\n *\n * @returns A function to track page views\n *\n * @example\n * ```tsx\n * function Page() {\n * const trackPageView = usePageView();\n *\n * useEffect(() => {\n * trackPageView({ path: '/dashboard', title: 'Dashboard' });\n * }, [trackPageView]);\n *\n * return <div>Dashboard</div>;\n * }\n * ```\n */\nexport function usePageView() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options?: PageViewOptions): Promise<TrackResponse | void> => {\n return kitbase.trackPageView(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to automatically track page views when the component mounts\n * or when dependencies change.\n *\n * @param options - Page view options (optional)\n * @param deps - Dependencies that trigger a new page view when changed\n *\n * @example\n * ```tsx\n * function ProductPage({ productId }: { productId: string }) {\n * // Track page view on mount and when productId changes\n * useAutoPageView(\n * { tags: { product_id: productId } },\n * [productId]\n * );\n *\n * return <div>Product {productId}</div>;\n * }\n * ```\n */\nexport function useAutoPageView(\n options?: PageViewOptions,\n deps: React.DependencyList = []\n) {\n const kitbase = useKitbaseAnalytics();\n\n useEffect(() => {\n kitbase.trackPageView(options);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Hook to get a memoized revenue tracking function.\n *\n * @returns A function to track revenue events\n *\n * @example\n * ```tsx\n * function Checkout() {\n * const trackRevenue = useRevenue();\n *\n * const handlePurchase = async (amount: number) => {\n * await trackRevenue({\n * amount,\n * currency: 'USD',\n * tags: { product: 'premium' },\n * });\n * };\n *\n * return <button onClick={() => handlePurchase(1999)}>Buy</button>;\n * }\n * ```\n */\nexport function useRevenue() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: RevenueOptions): Promise<TrackResponse | void> => {\n return kitbase.trackRevenue(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to track event duration.\n *\n * @param eventName - The name of the event to time\n * @returns Object with start and stop functions\n *\n * @example\n * ```tsx\n * function VideoPlayer() {\n * const { start, stop } = useTimeEvent('Video Watched');\n * const track = useTrack();\n *\n * const handlePlay = () => start();\n * const handleEnd = async () => {\n * await track({\n * channel: 'engagement',\n * event: 'Video Watched',\n * tags: { video_id: '123' },\n * });\n * // $duration is automatically included\n * };\n *\n * return (\n * <video onPlay={handlePlay} onEnded={handleEnd}>\n * ...\n * </video>\n * );\n * }\n * ```\n */\nexport function useTimeEvent(eventName: string) {\n const kitbase = useKitbaseAnalytics();\n\n return useMemo(\n () => ({\n start: () => kitbase.timeEvent(eventName),\n stop: () => kitbase.cancelTimeEvent(eventName),\n getDuration: () => kitbase.getEventDuration(eventName),\n }),\n [kitbase, eventName]\n );\n}\n\n/**\n * Hook to register super properties.\n *\n * @param properties - Properties to register\n * @param deps - Dependencies that trigger re-registration when changed\n *\n * @example\n * ```tsx\n * function App({ user }: { user: User }) {\n * // Register user properties that will be included in all events\n * useSuperProperties(\n * { user_type: user.type, plan: user.plan },\n * [user.type, user.plan]\n * );\n *\n * return <MainContent />;\n * }\n * ```\n */\nexport function useSuperProperties(\n properties: Tags,\n deps: React.DependencyList = []\n) {\n const kitbase = useKitbaseAnalytics();\n\n useEffect(() => {\n kitbase.register(properties);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Hook to get the current user ID (set via identify).\n *\n * @returns The user ID or null\n *\n * @example\n * ```tsx\n * function UserBadge() {\n * const userId = useUserId();\n * if (!userId) return null;\n * return <div>Logged in as: {userId}</div>;\n * }\n * ```\n */\nexport function useUserId(): string | null {\n const kitbase = useKitbaseAnalytics();\n return kitbase.getUserId();\n}\n\n/**\n * Hook to reset the user identity.\n *\n * @returns A function to reset the user\n *\n * @example\n * ```tsx\n * function LogoutButton() {\n * const reset = useReset();\n *\n * const handleLogout = () => {\n * // Clear server session...\n * reset();\n * };\n *\n * return <button onClick={handleLogout}>Logout</button>;\n * }\n * ```\n */\nexport function useReset() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(() => {\n kitbase.reset();\n }, [kitbase]);\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgCA,mBAQO;AACP,uBASO;AAGP,0BAAc,+BArDd;AAmHI;AAxDJ,IAAM,8BAA0B,4BAAuC,IAAI;AAwCpE,SAAS,yBAAyB,EAAE,QAAQ,SAAS,GAAkC;AAC5F,QAAM,iBAAa,qBAAgC,IAAI;AAGvD,MAAI,CAAC,WAAW,SAAS;AACvB,eAAW,UAAU,IAAI,kCAAiB,MAAM;AAAA,EAClD;AAGA,8BAAU,MAAM;AACd,WAAO,MAAM;AACX,iBAAW,SAAS,SAAS;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SACE,4CAAC,wBAAwB,UAAxB,EAAiC,OAAO,WAAW,SACjD,UACH;AAEJ;AAyBO,SAAS,sBAAwC;AACtD,QAAM,cAAU,yBAAW,uBAAuB;AAElD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,oEAAoE;AAAA,EACtF;AAEA,SAAO;AACT;AAwBO,SAAS,WAAW;AACzB,QAAM,UAAU,oBAAoB;AAEpC,aAAO;AAAA,IACL,CAAC,YAAyD;AACxD,aAAO,QAAQ,MAAM,OAAO;AAAA,IAC9B;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAuBO,SAAS,cAAc;AAC5B,QAAM,UAAU,oBAAoB;AAEpC,aAAO;AAAA,IACL,CAAC,YAA4C;AAC3C,aAAO,QAAQ,SAAS,OAAO;AAAA,IACjC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAoBO,SAAS,cAAc;AAC5B,QAAM,UAAU,oBAAoB;AAEpC,aAAO;AAAA,IACL,CAAC,YAA6D;AAC5D,aAAO,QAAQ,cAAc,OAAO;AAAA,IACtC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAsBO,SAAS,gBACd,SACA,OAA6B,CAAC,GAC9B;AACA,QAAM,UAAU,oBAAoB;AAEpC,8BAAU,MAAM;AACd,YAAQ,cAAc,OAAO;AAAA,EAE/B,GAAG,IAAI;AACT;AAwBO,SAAS,aAAa;AAC3B,QAAM,UAAU,oBAAoB;AAEpC,aAAO;AAAA,IACL,CAAC,YAA2D;AAC1D,aAAO,QAAQ,aAAa,OAAO;AAAA,IACrC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAgCO,SAAS,aAAa,WAAmB;AAC9C,QAAM,UAAU,oBAAoB;AAEpC,aAAO;AAAA,IACL,OAAO;AAAA,MACL,OAAO,MAAM,QAAQ,UAAU,SAAS;AAAA,MACxC,MAAM,MAAM,QAAQ,gBAAgB,SAAS;AAAA,MAC7C,aAAa,MAAM,QAAQ,iBAAiB,SAAS;AAAA,IACvD;AAAA,IACA,CAAC,SAAS,SAAS;AAAA,EACrB;AACF;AAqBO,SAAS,mBACd,YACA,OAA6B,CAAC,GAC9B;AACA,QAAM,UAAU,oBAAoB;AAEpC,8BAAU,MAAM;AACd,YAAQ,SAAS,UAAU;AAAA,EAE7B,GAAG,IAAI;AACT;AAgBO,SAAS,YAA2B;AACzC,QAAM,UAAU,oBAAoB;AACpC,SAAO,QAAQ,UAAU;AAC3B;AAqBO,SAAS,WAAW;AACzB,QAAM,UAAU,oBAAoB;AAEpC,aAAO,0BAAY,MAAM;AACvB,YAAQ,MAAM;AAAA,EAChB,GAAG,CAAC,OAAO,CAAC;AACd;","names":[]}
@@ -0,0 +1,262 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ import { KitbaseConfig, KitbaseAnalytics, TrackOptions, TrackResponse, IdentifyOptions, PageViewOptions, RevenueOptions, Tags } from '@kitbase/analytics';
4
+ export * from '@kitbase/analytics';
5
+
6
+ /**
7
+ * Props for the KitbaseAnalyticsProvider component
8
+ */
9
+ interface KitbaseAnalyticsProviderProps {
10
+ /**
11
+ * KitbaseAnalytics configuration options
12
+ */
13
+ config: KitbaseConfig;
14
+ /**
15
+ * React children to render
16
+ */
17
+ children: ReactNode;
18
+ }
19
+ /**
20
+ * Provider component that initializes KitbaseAnalytics and makes it available
21
+ * to all child components via React context.
22
+ *
23
+ * @example
24
+ * ```tsx
25
+ * import { KitbaseAnalyticsProvider } from '@kitbase/analytics-react';
26
+ *
27
+ * function App() {
28
+ * return (
29
+ * <KitbaseAnalyticsProvider
30
+ * config={{
31
+ * sdkKey: 'your-api-key',
32
+ * debug: true,
33
+ * analytics: { autoTrackPageViews: true },
34
+ * }}
35
+ * >
36
+ * <YourApp />
37
+ * </KitbaseAnalyticsProvider>
38
+ * );
39
+ * }
40
+ * ```
41
+ */
42
+ declare function KitbaseAnalyticsProvider({ config, children }: KitbaseAnalyticsProviderProps): react_jsx_runtime.JSX.Element;
43
+ /**
44
+ * Hook to access the KitbaseAnalytics instance directly.
45
+ *
46
+ * @returns The KitbaseAnalytics instance
47
+ * @throws Error if used outside of KitbaseAnalyticsProvider
48
+ *
49
+ * @example
50
+ * ```tsx
51
+ * function MyComponent() {
52
+ * const kitbase = useKitbaseAnalytics();
53
+ *
54
+ * useEffect(() => {
55
+ * kitbase.register({ page: 'home' });
56
+ * }, [kitbase]);
57
+ *
58
+ * return <div>My Component</div>;
59
+ * }
60
+ * ```
61
+ */
62
+ declare function useKitbaseAnalytics(): KitbaseAnalytics;
63
+ /**
64
+ * Hook to get a memoized track function.
65
+ *
66
+ * @returns A function to track events
67
+ *
68
+ * @example
69
+ * ```tsx
70
+ * function Button() {
71
+ * const track = useTrack();
72
+ *
73
+ * const handleClick = () => {
74
+ * track({
75
+ * channel: 'ui',
76
+ * event: 'Button Clicked',
77
+ * tags: { button_id: 'cta' },
78
+ * });
79
+ * };
80
+ *
81
+ * return <button onClick={handleClick}>Click me</button>;
82
+ * }
83
+ * ```
84
+ */
85
+ declare function useTrack(): (options: TrackOptions) => Promise<TrackResponse | void>;
86
+ /**
87
+ * Hook to get a memoized identify function.
88
+ *
89
+ * @returns A function to identify users
90
+ *
91
+ * @example
92
+ * ```tsx
93
+ * function LoginForm() {
94
+ * const identify = useIdentify();
95
+ *
96
+ * const handleLogin = async (userId: string, email: string) => {
97
+ * await identify({
98
+ * userId,
99
+ * traits: { email },
100
+ * });
101
+ * };
102
+ *
103
+ * return <form>...</form>;
104
+ * }
105
+ * ```
106
+ */
107
+ declare function useIdentify(): (options: IdentifyOptions) => Promise<void>;
108
+ /**
109
+ * Hook to get a memoized page view tracking function.
110
+ *
111
+ * @returns A function to track page views
112
+ *
113
+ * @example
114
+ * ```tsx
115
+ * function Page() {
116
+ * const trackPageView = usePageView();
117
+ *
118
+ * useEffect(() => {
119
+ * trackPageView({ path: '/dashboard', title: 'Dashboard' });
120
+ * }, [trackPageView]);
121
+ *
122
+ * return <div>Dashboard</div>;
123
+ * }
124
+ * ```
125
+ */
126
+ declare function usePageView(): (options?: PageViewOptions) => Promise<TrackResponse | void>;
127
+ /**
128
+ * Hook to automatically track page views when the component mounts
129
+ * or when dependencies change.
130
+ *
131
+ * @param options - Page view options (optional)
132
+ * @param deps - Dependencies that trigger a new page view when changed
133
+ *
134
+ * @example
135
+ * ```tsx
136
+ * function ProductPage({ productId }: { productId: string }) {
137
+ * // Track page view on mount and when productId changes
138
+ * useAutoPageView(
139
+ * { tags: { product_id: productId } },
140
+ * [productId]
141
+ * );
142
+ *
143
+ * return <div>Product {productId}</div>;
144
+ * }
145
+ * ```
146
+ */
147
+ declare function useAutoPageView(options?: PageViewOptions, deps?: React.DependencyList): void;
148
+ /**
149
+ * Hook to get a memoized revenue tracking function.
150
+ *
151
+ * @returns A function to track revenue events
152
+ *
153
+ * @example
154
+ * ```tsx
155
+ * function Checkout() {
156
+ * const trackRevenue = useRevenue();
157
+ *
158
+ * const handlePurchase = async (amount: number) => {
159
+ * await trackRevenue({
160
+ * amount,
161
+ * currency: 'USD',
162
+ * tags: { product: 'premium' },
163
+ * });
164
+ * };
165
+ *
166
+ * return <button onClick={() => handlePurchase(1999)}>Buy</button>;
167
+ * }
168
+ * ```
169
+ */
170
+ declare function useRevenue(): (options: RevenueOptions) => Promise<TrackResponse | void>;
171
+ /**
172
+ * Hook to track event duration.
173
+ *
174
+ * @param eventName - The name of the event to time
175
+ * @returns Object with start and stop functions
176
+ *
177
+ * @example
178
+ * ```tsx
179
+ * function VideoPlayer() {
180
+ * const { start, stop } = useTimeEvent('Video Watched');
181
+ * const track = useTrack();
182
+ *
183
+ * const handlePlay = () => start();
184
+ * const handleEnd = async () => {
185
+ * await track({
186
+ * channel: 'engagement',
187
+ * event: 'Video Watched',
188
+ * tags: { video_id: '123' },
189
+ * });
190
+ * // $duration is automatically included
191
+ * };
192
+ *
193
+ * return (
194
+ * <video onPlay={handlePlay} onEnded={handleEnd}>
195
+ * ...
196
+ * </video>
197
+ * );
198
+ * }
199
+ * ```
200
+ */
201
+ declare function useTimeEvent(eventName: string): {
202
+ start: () => void;
203
+ stop: () => void;
204
+ getDuration: () => number | null;
205
+ };
206
+ /**
207
+ * Hook to register super properties.
208
+ *
209
+ * @param properties - Properties to register
210
+ * @param deps - Dependencies that trigger re-registration when changed
211
+ *
212
+ * @example
213
+ * ```tsx
214
+ * function App({ user }: { user: User }) {
215
+ * // Register user properties that will be included in all events
216
+ * useSuperProperties(
217
+ * { user_type: user.type, plan: user.plan },
218
+ * [user.type, user.plan]
219
+ * );
220
+ *
221
+ * return <MainContent />;
222
+ * }
223
+ * ```
224
+ */
225
+ declare function useSuperProperties(properties: Tags, deps?: React.DependencyList): void;
226
+ /**
227
+ * Hook to get the current user ID (set via identify).
228
+ *
229
+ * @returns The user ID or null
230
+ *
231
+ * @example
232
+ * ```tsx
233
+ * function UserBadge() {
234
+ * const userId = useUserId();
235
+ * if (!userId) return null;
236
+ * return <div>Logged in as: {userId}</div>;
237
+ * }
238
+ * ```
239
+ */
240
+ declare function useUserId(): string | null;
241
+ /**
242
+ * Hook to reset the user identity.
243
+ *
244
+ * @returns A function to reset the user
245
+ *
246
+ * @example
247
+ * ```tsx
248
+ * function LogoutButton() {
249
+ * const reset = useReset();
250
+ *
251
+ * const handleLogout = () => {
252
+ * // Clear server session...
253
+ * reset();
254
+ * };
255
+ *
256
+ * return <button onClick={handleLogout}>Logout</button>;
257
+ * }
258
+ * ```
259
+ */
260
+ declare function useReset(): () => void;
261
+
262
+ export { KitbaseAnalyticsProvider, type KitbaseAnalyticsProviderProps, useAutoPageView, useIdentify, useKitbaseAnalytics, usePageView, useReset, useRevenue, useSuperProperties, useTimeEvent, useTrack, useUserId };
@@ -0,0 +1,262 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode } from 'react';
3
+ import { KitbaseConfig, KitbaseAnalytics, TrackOptions, TrackResponse, IdentifyOptions, PageViewOptions, RevenueOptions, Tags } from '@kitbase/analytics';
4
+ export * from '@kitbase/analytics';
5
+
6
+ /**
7
+ * Props for the KitbaseAnalyticsProvider component
8
+ */
9
+ interface KitbaseAnalyticsProviderProps {
10
+ /**
11
+ * KitbaseAnalytics configuration options
12
+ */
13
+ config: KitbaseConfig;
14
+ /**
15
+ * React children to render
16
+ */
17
+ children: ReactNode;
18
+ }
19
+ /**
20
+ * Provider component that initializes KitbaseAnalytics and makes it available
21
+ * to all child components via React context.
22
+ *
23
+ * @example
24
+ * ```tsx
25
+ * import { KitbaseAnalyticsProvider } from '@kitbase/analytics-react';
26
+ *
27
+ * function App() {
28
+ * return (
29
+ * <KitbaseAnalyticsProvider
30
+ * config={{
31
+ * sdkKey: 'your-api-key',
32
+ * debug: true,
33
+ * analytics: { autoTrackPageViews: true },
34
+ * }}
35
+ * >
36
+ * <YourApp />
37
+ * </KitbaseAnalyticsProvider>
38
+ * );
39
+ * }
40
+ * ```
41
+ */
42
+ declare function KitbaseAnalyticsProvider({ config, children }: KitbaseAnalyticsProviderProps): react_jsx_runtime.JSX.Element;
43
+ /**
44
+ * Hook to access the KitbaseAnalytics instance directly.
45
+ *
46
+ * @returns The KitbaseAnalytics instance
47
+ * @throws Error if used outside of KitbaseAnalyticsProvider
48
+ *
49
+ * @example
50
+ * ```tsx
51
+ * function MyComponent() {
52
+ * const kitbase = useKitbaseAnalytics();
53
+ *
54
+ * useEffect(() => {
55
+ * kitbase.register({ page: 'home' });
56
+ * }, [kitbase]);
57
+ *
58
+ * return <div>My Component</div>;
59
+ * }
60
+ * ```
61
+ */
62
+ declare function useKitbaseAnalytics(): KitbaseAnalytics;
63
+ /**
64
+ * Hook to get a memoized track function.
65
+ *
66
+ * @returns A function to track events
67
+ *
68
+ * @example
69
+ * ```tsx
70
+ * function Button() {
71
+ * const track = useTrack();
72
+ *
73
+ * const handleClick = () => {
74
+ * track({
75
+ * channel: 'ui',
76
+ * event: 'Button Clicked',
77
+ * tags: { button_id: 'cta' },
78
+ * });
79
+ * };
80
+ *
81
+ * return <button onClick={handleClick}>Click me</button>;
82
+ * }
83
+ * ```
84
+ */
85
+ declare function useTrack(): (options: TrackOptions) => Promise<TrackResponse | void>;
86
+ /**
87
+ * Hook to get a memoized identify function.
88
+ *
89
+ * @returns A function to identify users
90
+ *
91
+ * @example
92
+ * ```tsx
93
+ * function LoginForm() {
94
+ * const identify = useIdentify();
95
+ *
96
+ * const handleLogin = async (userId: string, email: string) => {
97
+ * await identify({
98
+ * userId,
99
+ * traits: { email },
100
+ * });
101
+ * };
102
+ *
103
+ * return <form>...</form>;
104
+ * }
105
+ * ```
106
+ */
107
+ declare function useIdentify(): (options: IdentifyOptions) => Promise<void>;
108
+ /**
109
+ * Hook to get a memoized page view tracking function.
110
+ *
111
+ * @returns A function to track page views
112
+ *
113
+ * @example
114
+ * ```tsx
115
+ * function Page() {
116
+ * const trackPageView = usePageView();
117
+ *
118
+ * useEffect(() => {
119
+ * trackPageView({ path: '/dashboard', title: 'Dashboard' });
120
+ * }, [trackPageView]);
121
+ *
122
+ * return <div>Dashboard</div>;
123
+ * }
124
+ * ```
125
+ */
126
+ declare function usePageView(): (options?: PageViewOptions) => Promise<TrackResponse | void>;
127
+ /**
128
+ * Hook to automatically track page views when the component mounts
129
+ * or when dependencies change.
130
+ *
131
+ * @param options - Page view options (optional)
132
+ * @param deps - Dependencies that trigger a new page view when changed
133
+ *
134
+ * @example
135
+ * ```tsx
136
+ * function ProductPage({ productId }: { productId: string }) {
137
+ * // Track page view on mount and when productId changes
138
+ * useAutoPageView(
139
+ * { tags: { product_id: productId } },
140
+ * [productId]
141
+ * );
142
+ *
143
+ * return <div>Product {productId}</div>;
144
+ * }
145
+ * ```
146
+ */
147
+ declare function useAutoPageView(options?: PageViewOptions, deps?: React.DependencyList): void;
148
+ /**
149
+ * Hook to get a memoized revenue tracking function.
150
+ *
151
+ * @returns A function to track revenue events
152
+ *
153
+ * @example
154
+ * ```tsx
155
+ * function Checkout() {
156
+ * const trackRevenue = useRevenue();
157
+ *
158
+ * const handlePurchase = async (amount: number) => {
159
+ * await trackRevenue({
160
+ * amount,
161
+ * currency: 'USD',
162
+ * tags: { product: 'premium' },
163
+ * });
164
+ * };
165
+ *
166
+ * return <button onClick={() => handlePurchase(1999)}>Buy</button>;
167
+ * }
168
+ * ```
169
+ */
170
+ declare function useRevenue(): (options: RevenueOptions) => Promise<TrackResponse | void>;
171
+ /**
172
+ * Hook to track event duration.
173
+ *
174
+ * @param eventName - The name of the event to time
175
+ * @returns Object with start and stop functions
176
+ *
177
+ * @example
178
+ * ```tsx
179
+ * function VideoPlayer() {
180
+ * const { start, stop } = useTimeEvent('Video Watched');
181
+ * const track = useTrack();
182
+ *
183
+ * const handlePlay = () => start();
184
+ * const handleEnd = async () => {
185
+ * await track({
186
+ * channel: 'engagement',
187
+ * event: 'Video Watched',
188
+ * tags: { video_id: '123' },
189
+ * });
190
+ * // $duration is automatically included
191
+ * };
192
+ *
193
+ * return (
194
+ * <video onPlay={handlePlay} onEnded={handleEnd}>
195
+ * ...
196
+ * </video>
197
+ * );
198
+ * }
199
+ * ```
200
+ */
201
+ declare function useTimeEvent(eventName: string): {
202
+ start: () => void;
203
+ stop: () => void;
204
+ getDuration: () => number | null;
205
+ };
206
+ /**
207
+ * Hook to register super properties.
208
+ *
209
+ * @param properties - Properties to register
210
+ * @param deps - Dependencies that trigger re-registration when changed
211
+ *
212
+ * @example
213
+ * ```tsx
214
+ * function App({ user }: { user: User }) {
215
+ * // Register user properties that will be included in all events
216
+ * useSuperProperties(
217
+ * { user_type: user.type, plan: user.plan },
218
+ * [user.type, user.plan]
219
+ * );
220
+ *
221
+ * return <MainContent />;
222
+ * }
223
+ * ```
224
+ */
225
+ declare function useSuperProperties(properties: Tags, deps?: React.DependencyList): void;
226
+ /**
227
+ * Hook to get the current user ID (set via identify).
228
+ *
229
+ * @returns The user ID or null
230
+ *
231
+ * @example
232
+ * ```tsx
233
+ * function UserBadge() {
234
+ * const userId = useUserId();
235
+ * if (!userId) return null;
236
+ * return <div>Logged in as: {userId}</div>;
237
+ * }
238
+ * ```
239
+ */
240
+ declare function useUserId(): string | null;
241
+ /**
242
+ * Hook to reset the user identity.
243
+ *
244
+ * @returns A function to reset the user
245
+ *
246
+ * @example
247
+ * ```tsx
248
+ * function LogoutButton() {
249
+ * const reset = useReset();
250
+ *
251
+ * const handleLogout = () => {
252
+ * // Clear server session...
253
+ * reset();
254
+ * };
255
+ *
256
+ * return <button onClick={handleLogout}>Logout</button>;
257
+ * }
258
+ * ```
259
+ */
260
+ declare function useReset(): () => void;
261
+
262
+ export { KitbaseAnalyticsProvider, type KitbaseAnalyticsProviderProps, useAutoPageView, useIdentify, useKitbaseAnalytics, usePageView, useReset, useRevenue, useSuperProperties, useTimeEvent, useTrack, useUserId };
package/dist/index.js ADDED
@@ -0,0 +1,117 @@
1
+ // src/index.tsx
2
+ import {
3
+ createContext,
4
+ useContext,
5
+ useEffect,
6
+ useRef,
7
+ useMemo,
8
+ useCallback
9
+ } from "react";
10
+ import {
11
+ KitbaseAnalytics
12
+ } from "@kitbase/analytics";
13
+ export * from "@kitbase/analytics";
14
+ import { jsx } from "react/jsx-runtime";
15
+ var KitbaseAnalyticsContext = createContext(null);
16
+ function KitbaseAnalyticsProvider({ config, children }) {
17
+ const kitbaseRef = useRef(null);
18
+ if (!kitbaseRef.current) {
19
+ kitbaseRef.current = new KitbaseAnalytics(config);
20
+ }
21
+ useEffect(() => {
22
+ return () => {
23
+ kitbaseRef.current?.shutdown();
24
+ };
25
+ }, []);
26
+ return /* @__PURE__ */ jsx(KitbaseAnalyticsContext.Provider, { value: kitbaseRef.current, children });
27
+ }
28
+ function useKitbaseAnalytics() {
29
+ const context = useContext(KitbaseAnalyticsContext);
30
+ if (!context) {
31
+ throw new Error("useKitbaseAnalytics must be used within a KitbaseAnalyticsProvider");
32
+ }
33
+ return context;
34
+ }
35
+ function useTrack() {
36
+ const kitbase = useKitbaseAnalytics();
37
+ return useCallback(
38
+ (options) => {
39
+ return kitbase.track(options);
40
+ },
41
+ [kitbase]
42
+ );
43
+ }
44
+ function useIdentify() {
45
+ const kitbase = useKitbaseAnalytics();
46
+ return useCallback(
47
+ (options) => {
48
+ return kitbase.identify(options);
49
+ },
50
+ [kitbase]
51
+ );
52
+ }
53
+ function usePageView() {
54
+ const kitbase = useKitbaseAnalytics();
55
+ return useCallback(
56
+ (options) => {
57
+ return kitbase.trackPageView(options);
58
+ },
59
+ [kitbase]
60
+ );
61
+ }
62
+ function useAutoPageView(options, deps = []) {
63
+ const kitbase = useKitbaseAnalytics();
64
+ useEffect(() => {
65
+ kitbase.trackPageView(options);
66
+ }, deps);
67
+ }
68
+ function useRevenue() {
69
+ const kitbase = useKitbaseAnalytics();
70
+ return useCallback(
71
+ (options) => {
72
+ return kitbase.trackRevenue(options);
73
+ },
74
+ [kitbase]
75
+ );
76
+ }
77
+ function useTimeEvent(eventName) {
78
+ const kitbase = useKitbaseAnalytics();
79
+ return useMemo(
80
+ () => ({
81
+ start: () => kitbase.timeEvent(eventName),
82
+ stop: () => kitbase.cancelTimeEvent(eventName),
83
+ getDuration: () => kitbase.getEventDuration(eventName)
84
+ }),
85
+ [kitbase, eventName]
86
+ );
87
+ }
88
+ function useSuperProperties(properties, deps = []) {
89
+ const kitbase = useKitbaseAnalytics();
90
+ useEffect(() => {
91
+ kitbase.register(properties);
92
+ }, deps);
93
+ }
94
+ function useUserId() {
95
+ const kitbase = useKitbaseAnalytics();
96
+ return kitbase.getUserId();
97
+ }
98
+ function useReset() {
99
+ const kitbase = useKitbaseAnalytics();
100
+ return useCallback(() => {
101
+ kitbase.reset();
102
+ }, [kitbase]);
103
+ }
104
+ export {
105
+ KitbaseAnalyticsProvider,
106
+ useAutoPageView,
107
+ useIdentify,
108
+ useKitbaseAnalytics,
109
+ usePageView,
110
+ useReset,
111
+ useRevenue,
112
+ useSuperProperties,
113
+ useTimeEvent,
114
+ useTrack,
115
+ useUserId
116
+ };
117
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.tsx"],"sourcesContent":["/**\n * React integration for Kitbase Analytics SDK\n *\n * Provides React hooks and context provider for easy integration\n * with React applications.\n *\n * @example\n * ```tsx\n * import { KitbaseAnalyticsProvider, useKitbaseAnalytics, useTrack } from '@kitbase/analytics-react';\n *\n * function App() {\n * return (\n * <KitbaseAnalyticsProvider config={{ sdkKey: 'your-api-key' }}>\n * <MyComponent />\n * </KitbaseAnalyticsProvider>\n * );\n * }\n *\n * function MyComponent() {\n * const track = useTrack();\n *\n * return (\n * <button onClick={() => track({ channel: 'ui', event: 'Button Clicked' })}>\n * Click me\n * </button>\n * );\n * }\n * ```\n *\n * @packageDocumentation\n */\n\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useMemo,\n useCallback,\n type ReactNode,\n} from 'react';\nimport {\n KitbaseAnalytics,\n type KitbaseConfig,\n type TrackOptions,\n type TrackResponse,\n type PageViewOptions,\n type RevenueOptions,\n type IdentifyOptions,\n type Tags,\n} from '@kitbase/analytics';\n\n// Re-export everything from core\nexport * from '@kitbase/analytics';\n\n// ============================================================\n// Context\n// ============================================================\n\nconst KitbaseAnalyticsContext = createContext<KitbaseAnalytics | null>(null);\n\n/**\n * Props for the KitbaseAnalyticsProvider component\n */\nexport interface KitbaseAnalyticsProviderProps {\n /**\n * KitbaseAnalytics configuration options\n */\n config: KitbaseConfig;\n\n /**\n * React children to render\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that initializes KitbaseAnalytics and makes it available\n * to all child components via React context.\n *\n * @example\n * ```tsx\n * import { KitbaseAnalyticsProvider } from '@kitbase/analytics-react';\n *\n * function App() {\n * return (\n * <KitbaseAnalyticsProvider\n * config={{\n * sdkKey: 'your-api-key',\n * debug: true,\n * analytics: { autoTrackPageViews: true },\n * }}\n * >\n * <YourApp />\n * </KitbaseAnalyticsProvider>\n * );\n * }\n * ```\n */\nexport function KitbaseAnalyticsProvider({ config, children }: KitbaseAnalyticsProviderProps) {\n const kitbaseRef = useRef<KitbaseAnalytics | null>(null);\n\n // Initialize KitbaseAnalytics instance once\n if (!kitbaseRef.current) {\n kitbaseRef.current = new KitbaseAnalytics(config);\n }\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n kitbaseRef.current?.shutdown();\n };\n }, []);\n\n return (\n <KitbaseAnalyticsContext.Provider value={kitbaseRef.current}>\n {children}\n </KitbaseAnalyticsContext.Provider>\n );\n}\n\n// ============================================================\n// Hooks\n// ============================================================\n\n/**\n * Hook to access the KitbaseAnalytics instance directly.\n *\n * @returns The KitbaseAnalytics instance\n * @throws Error if used outside of KitbaseAnalyticsProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const kitbase = useKitbaseAnalytics();\n *\n * useEffect(() => {\n * kitbase.register({ page: 'home' });\n * }, [kitbase]);\n *\n * return <div>My Component</div>;\n * }\n * ```\n */\nexport function useKitbaseAnalytics(): KitbaseAnalytics {\n const context = useContext(KitbaseAnalyticsContext);\n\n if (!context) {\n throw new Error('useKitbaseAnalytics must be used within a KitbaseAnalyticsProvider');\n }\n\n return context;\n}\n\n/**\n * Hook to get a memoized track function.\n *\n * @returns A function to track events\n *\n * @example\n * ```tsx\n * function Button() {\n * const track = useTrack();\n *\n * const handleClick = () => {\n * track({\n * channel: 'ui',\n * event: 'Button Clicked',\n * tags: { button_id: 'cta' },\n * });\n * };\n *\n * return <button onClick={handleClick}>Click me</button>;\n * }\n * ```\n */\nexport function useTrack() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: TrackOptions): Promise<TrackResponse | void> => {\n return kitbase.track(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to get a memoized identify function.\n *\n * @returns A function to identify users\n *\n * @example\n * ```tsx\n * function LoginForm() {\n * const identify = useIdentify();\n *\n * const handleLogin = async (userId: string, email: string) => {\n * await identify({\n * userId,\n * traits: { email },\n * });\n * };\n *\n * return <form>...</form>;\n * }\n * ```\n */\nexport function useIdentify() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: IdentifyOptions): Promise<void> => {\n return kitbase.identify(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to get a memoized page view tracking function.\n *\n * @returns A function to track page views\n *\n * @example\n * ```tsx\n * function Page() {\n * const trackPageView = usePageView();\n *\n * useEffect(() => {\n * trackPageView({ path: '/dashboard', title: 'Dashboard' });\n * }, [trackPageView]);\n *\n * return <div>Dashboard</div>;\n * }\n * ```\n */\nexport function usePageView() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options?: PageViewOptions): Promise<TrackResponse | void> => {\n return kitbase.trackPageView(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to automatically track page views when the component mounts\n * or when dependencies change.\n *\n * @param options - Page view options (optional)\n * @param deps - Dependencies that trigger a new page view when changed\n *\n * @example\n * ```tsx\n * function ProductPage({ productId }: { productId: string }) {\n * // Track page view on mount and when productId changes\n * useAutoPageView(\n * { tags: { product_id: productId } },\n * [productId]\n * );\n *\n * return <div>Product {productId}</div>;\n * }\n * ```\n */\nexport function useAutoPageView(\n options?: PageViewOptions,\n deps: React.DependencyList = []\n) {\n const kitbase = useKitbaseAnalytics();\n\n useEffect(() => {\n kitbase.trackPageView(options);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Hook to get a memoized revenue tracking function.\n *\n * @returns A function to track revenue events\n *\n * @example\n * ```tsx\n * function Checkout() {\n * const trackRevenue = useRevenue();\n *\n * const handlePurchase = async (amount: number) => {\n * await trackRevenue({\n * amount,\n * currency: 'USD',\n * tags: { product: 'premium' },\n * });\n * };\n *\n * return <button onClick={() => handlePurchase(1999)}>Buy</button>;\n * }\n * ```\n */\nexport function useRevenue() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(\n (options: RevenueOptions): Promise<TrackResponse | void> => {\n return kitbase.trackRevenue(options);\n },\n [kitbase]\n );\n}\n\n/**\n * Hook to track event duration.\n *\n * @param eventName - The name of the event to time\n * @returns Object with start and stop functions\n *\n * @example\n * ```tsx\n * function VideoPlayer() {\n * const { start, stop } = useTimeEvent('Video Watched');\n * const track = useTrack();\n *\n * const handlePlay = () => start();\n * const handleEnd = async () => {\n * await track({\n * channel: 'engagement',\n * event: 'Video Watched',\n * tags: { video_id: '123' },\n * });\n * // $duration is automatically included\n * };\n *\n * return (\n * <video onPlay={handlePlay} onEnded={handleEnd}>\n * ...\n * </video>\n * );\n * }\n * ```\n */\nexport function useTimeEvent(eventName: string) {\n const kitbase = useKitbaseAnalytics();\n\n return useMemo(\n () => ({\n start: () => kitbase.timeEvent(eventName),\n stop: () => kitbase.cancelTimeEvent(eventName),\n getDuration: () => kitbase.getEventDuration(eventName),\n }),\n [kitbase, eventName]\n );\n}\n\n/**\n * Hook to register super properties.\n *\n * @param properties - Properties to register\n * @param deps - Dependencies that trigger re-registration when changed\n *\n * @example\n * ```tsx\n * function App({ user }: { user: User }) {\n * // Register user properties that will be included in all events\n * useSuperProperties(\n * { user_type: user.type, plan: user.plan },\n * [user.type, user.plan]\n * );\n *\n * return <MainContent />;\n * }\n * ```\n */\nexport function useSuperProperties(\n properties: Tags,\n deps: React.DependencyList = []\n) {\n const kitbase = useKitbaseAnalytics();\n\n useEffect(() => {\n kitbase.register(properties);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Hook to get the current user ID (set via identify).\n *\n * @returns The user ID or null\n *\n * @example\n * ```tsx\n * function UserBadge() {\n * const userId = useUserId();\n * if (!userId) return null;\n * return <div>Logged in as: {userId}</div>;\n * }\n * ```\n */\nexport function useUserId(): string | null {\n const kitbase = useKitbaseAnalytics();\n return kitbase.getUserId();\n}\n\n/**\n * Hook to reset the user identity.\n *\n * @returns A function to reset the user\n *\n * @example\n * ```tsx\n * function LogoutButton() {\n * const reset = useReset();\n *\n * const handleLogout = () => {\n * // Clear server session...\n * reset();\n * };\n *\n * return <button onClick={handleLogout}>Logout</button>;\n * }\n * ```\n */\nexport function useReset() {\n const kitbase = useKitbaseAnalytics();\n\n return useCallback(() => {\n kitbase.reset();\n }, [kitbase]);\n}\n\n"],"mappings":";AAgCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAQK;AAGP,cAAc;AA8DV;AAxDJ,IAAM,0BAA0B,cAAuC,IAAI;AAwCpE,SAAS,yBAAyB,EAAE,QAAQ,SAAS,GAAkC;AAC5F,QAAM,aAAa,OAAgC,IAAI;AAGvD,MAAI,CAAC,WAAW,SAAS;AACvB,eAAW,UAAU,IAAI,iBAAiB,MAAM;AAAA,EAClD;AAGA,YAAU,MAAM;AACd,WAAO,MAAM;AACX,iBAAW,SAAS,SAAS;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SACE,oBAAC,wBAAwB,UAAxB,EAAiC,OAAO,WAAW,SACjD,UACH;AAEJ;AAyBO,SAAS,sBAAwC;AACtD,QAAM,UAAU,WAAW,uBAAuB;AAElD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,oEAAoE;AAAA,EACtF;AAEA,SAAO;AACT;AAwBO,SAAS,WAAW;AACzB,QAAM,UAAU,oBAAoB;AAEpC,SAAO;AAAA,IACL,CAAC,YAAyD;AACxD,aAAO,QAAQ,MAAM,OAAO;AAAA,IAC9B;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAuBO,SAAS,cAAc;AAC5B,QAAM,UAAU,oBAAoB;AAEpC,SAAO;AAAA,IACL,CAAC,YAA4C;AAC3C,aAAO,QAAQ,SAAS,OAAO;AAAA,IACjC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAoBO,SAAS,cAAc;AAC5B,QAAM,UAAU,oBAAoB;AAEpC,SAAO;AAAA,IACL,CAAC,YAA6D;AAC5D,aAAO,QAAQ,cAAc,OAAO;AAAA,IACtC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAsBO,SAAS,gBACd,SACA,OAA6B,CAAC,GAC9B;AACA,QAAM,UAAU,oBAAoB;AAEpC,YAAU,MAAM;AACd,YAAQ,cAAc,OAAO;AAAA,EAE/B,GAAG,IAAI;AACT;AAwBO,SAAS,aAAa;AAC3B,QAAM,UAAU,oBAAoB;AAEpC,SAAO;AAAA,IACL,CAAC,YAA2D;AAC1D,aAAO,QAAQ,aAAa,OAAO;AAAA,IACrC;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AACF;AAgCO,SAAS,aAAa,WAAmB;AAC9C,QAAM,UAAU,oBAAoB;AAEpC,SAAO;AAAA,IACL,OAAO;AAAA,MACL,OAAO,MAAM,QAAQ,UAAU,SAAS;AAAA,MACxC,MAAM,MAAM,QAAQ,gBAAgB,SAAS;AAAA,MAC7C,aAAa,MAAM,QAAQ,iBAAiB,SAAS;AAAA,IACvD;AAAA,IACA,CAAC,SAAS,SAAS;AAAA,EACrB;AACF;AAqBO,SAAS,mBACd,YACA,OAA6B,CAAC,GAC9B;AACA,QAAM,UAAU,oBAAoB;AAEpC,YAAU,MAAM;AACd,YAAQ,SAAS,UAAU;AAAA,EAE7B,GAAG,IAAI;AACT;AAgBO,SAAS,YAA2B;AACzC,QAAM,UAAU,oBAAoB;AACpC,SAAO,QAAQ,UAAU;AAC3B;AAqBO,SAAS,WAAW;AACzB,QAAM,UAAU,oBAAoB;AAEpC,SAAO,YAAY,MAAM;AACvB,YAAQ,MAAM;AAAA,EAChB,GAAG,CAAC,OAAO,CAAC;AACd;","names":[]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@kitbase/analytics-react",
3
+ "version": "0.1.6",
4
+ "description": "React integration for Kitbase Analytics SDK",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "sideEffects": false,
25
+ "keywords": [
26
+ "kitbase",
27
+ "analytics",
28
+ "tracking",
29
+ "react",
30
+ "hooks"
31
+ ],
32
+ "author": "",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/scr2em/kitbase-sdk.git",
37
+ "directory": "customEvents/typescript/packages/react"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=17.0.0"
41
+ },
42
+ "dependencies": {
43
+ "@kitbase/analytics": "0.1.6"
44
+ },
45
+ "devDependencies": {
46
+ "@testing-library/jest-dom": "^6.9.1",
47
+ "@testing-library/react": "^16.3.2",
48
+ "@types/react": "^18.2.0",
49
+ "jsdom": "^28.1.0",
50
+ "react": "^18.2.0",
51
+ "react-dom": "18",
52
+ "tsup": "^8.0.1",
53
+ "typescript": "^5.3.3",
54
+ "vitest": "^1.2.0"
55
+ },
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "dev": "tsup --watch",
59
+ "test": "vitest run",
60
+ "test:watch": "vitest",
61
+ "lint": "eslint src",
62
+ "clean": "rm -rf dist"
63
+ }
64
+ }