cap-hydra-web-sdk 1.0.2 → 1.0.3

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 CHANGED
@@ -1,230 +1,394 @@
1
1
  # WebSDK Integration Guide
2
2
 
3
- A comprehensive guide for integrating the Hydra WebSDK into your web application for event tracking and analytics.
3
+ A comprehensive guide for integrating the Hydra WebSDK into your web application for event tracking, user identification, and analytics.
4
4
 
5
- ## Quick Start
5
+ ---
6
6
 
7
- Here's a minimal example to get you started:
7
+ ## Basic WebSDK Integration
8
8
 
9
- ```javascript
10
- import { WebSDK } from 'cap-hydra-web-sdk';
11
-
12
- // Initialize the SDK
13
- const sdk = new WebSDK({
14
- accountId: 'your-account-id',
15
- baseURL: 'https://api.your-domain.com',
16
- brandId: 'your-brand-id',
17
- applicationId: 'your-app-id',
18
- debugLevel: 'INFO',
19
- });
20
-
21
- // Initialize
22
- sdk.init();
23
-
24
- // Track events
25
- sdk.pushEvent('button_click', {
26
- button_id: 'submit',
27
- page: 'checkout',
28
- });
29
- ```
9
+ ### 1. Installation
30
10
 
31
- ## Installation
32
-
33
- ### NPM Installation
11
+ **NPM (recommended):**
34
12
 
35
13
  ```bash
36
14
  npm install cap-hydra-web-sdk
37
15
  ```
38
16
 
39
- ### CDN Installation
17
+ **CDN / Script tag:**
40
18
 
41
19
  ```html
42
20
  <script src="https://cdn.jsdelivr.net/npm/cap-hydra-web-sdk@latest/dist/index.umd.min.js"></script>
43
21
  ```
44
22
 
45
- ### ES6 Modules
23
+ ### 2. Importing the SDK
24
+
25
+ **ES6 Modules (TypeScript / JavaScript):**
46
26
 
47
27
  ```javascript
48
28
  import { WebSDK } from 'cap-hydra-web-sdk';
49
29
  ```
50
30
 
51
- ### CommonJS
31
+ **CommonJS:**
52
32
 
53
33
  ```javascript
54
34
  const { WebSDK } = require('cap-hydra-web-sdk');
55
35
  ```
56
36
 
57
- ## Basic Configuration
37
+ When using the CDN script tag, `WebSDK` is available as a global on the `window` object.
58
38
 
59
- ### Required Configuration
39
+ ### 3. SDK Initialization
40
+
41
+ Call `WebSDK.initialize()` once at application startup. The SDK uses Firebase Remote Config to fetch backend configuration (`accountId`, `baseURL`, `debugLevel`, etc.) automatically — you only need to provide Firebase credentials and the Remote Config key.
60
42
 
61
43
  ```javascript
62
- const config = {
63
- accountId: 'your-account-id', // Your Hydra account ID
64
- baseURL: 'https://api.hydra.com', // API endpoint
65
- };
44
+ import { WebSDK } from 'cap-hydra-web-sdk';
45
+
46
+ WebSDK.initialize({
47
+ firebaseConfig: {
48
+ apiKey: 'YOUR_FIREBASE_API_KEY',
49
+ authDomain: 'your-app.firebaseapp.com',
50
+ databaseURL: 'https://your-app.firebaseio.com',
51
+ projectId: 'your-project-id',
52
+ storageBucket: 'your-app.appspot.com',
53
+ messagingSenderId: '123456789',
54
+ appId: 'your-firebase-app-id',
55
+ },
56
+ remoteConfigKey: 'your_app_config_key',
57
+ appVersion: '1.0.0',
58
+ });
66
59
  ```
67
60
 
68
- ### Optional Configuration
61
+ > **Important:** Initialize the SDK at **module load time** — not inside React `useEffect`, Angular `ngOnInit`, or similar async lifecycle hooks. This ensures the SDK instance exists before any component attempts to use it.
62
+
63
+ ### 4. Basic Event Tracking
69
64
 
70
65
  ```javascript
71
- const config = {
72
- // Required
73
- accountId: 'your-account-id',
74
- baseURL: 'https://api.hydra.com',
66
+ // Track a page view (auto-captures URL and title)
67
+ WebSDK.pageView();
75
68
 
76
- // Optional
77
- brandId: 'your-brand-id',
78
- applicationId: 'your-app-id',
79
- debugLevel: 'INFO', // 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'NONE'
80
- country: 'US', // Default country
81
- city: 'New York', // Default city
82
- countryCode: 'US', // Default country code
83
- retryDelays: [60000, 120000, 240000, 480000, 900000], // Custom retry delays in milliseconds
84
- };
69
+ // Track a custom event
70
+ WebSDK.track('page_view', {
71
+ page: 'homepage',
72
+ });
73
+
74
+ // Track with detailed properties
75
+ WebSDK.track('add_to_cart', {
76
+ product_id: 'shoe-123',
77
+ product_name: 'Nike Air Max',
78
+ quantity: 1,
79
+ price: 129.99,
80
+ currency: 'USD',
81
+ });
85
82
  ```
86
83
 
87
- ## Initialization
84
+ ### 5. User Identification
88
85
 
89
- ### React Integration
86
+ When a user logs in, call `identify()` to link their activity to a known identity:
90
87
 
91
- ```jsx
92
- import React, { useEffect } from 'react';
88
+ ```javascript
89
+ WebSDK.identify({
90
+ identifier: { type: 'email', cuid: 'user@example.com' },
91
+ actionType: 'USER_REGISTER',
92
+ traits: {
93
+ firstName: 'John',
94
+ lastName: 'Doe',
95
+ },
96
+ });
97
+ ```
98
+
99
+ Supported identifier types: `'email'`, `'mobile'`, `'externalId'`.
100
+
101
+ When the user logs out, call `reset()` to return to anonymous tracking:
102
+
103
+ ```javascript
104
+ WebSDK.reset();
105
+ ```
106
+
107
+ ---
108
+
109
+ ## React Integration Example
110
+
111
+ For React applications, wrap the SDK in a service and initialize at module load time:
112
+
113
+ ```typescript
114
+ // services/sdkService.ts
93
115
  import { WebSDK } from 'cap-hydra-web-sdk';
94
116
 
95
- function App() {
96
- useEffect(() => {
97
- // Initialize SDK
98
- const webSDK = new WebSDK(config);
99
- webSDK.init();
117
+ class SDKService {
118
+ initialize() {
119
+ WebSDK.initialize({
120
+ firebaseConfig: {
121
+ /* ... */
122
+ },
123
+ remoteConfigKey: 'your_app_config_key',
124
+ appVersion: '1.0.0',
125
+ notifications: {
126
+ enableNotifications: true,
127
+ vapidKey: 'YOUR_VAPID_KEY',
128
+ },
129
+ });
130
+ }
100
131
 
101
- // Store SDK instance for use throughout the app
102
- window.hydraSDK = webSDK;
132
+ trackEvent(name: string, properties?: Record<string, unknown>) {
133
+ WebSDK.track(name, properties);
134
+ }
103
135
 
104
- // Start tracking immediately
105
- webSDK.pushEvent('app_mounted', { timestamp: Date.now() });
106
- }, []);
136
+ trackPageView() {
137
+ WebSDK.pageView();
138
+ }
107
139
 
108
- return (
109
- <div>
110
- <Dashboard />
111
- </div>
112
- );
140
+ identifyUser(type: 'email' | 'mobile' | 'externalId', cuid: string, traits?: object) {
141
+ WebSDK.identify({
142
+ identifier: { type, cuid },
143
+ actionType: 'USER_REGISTER',
144
+ traits,
145
+ });
146
+ }
147
+
148
+ reset() {
149
+ WebSDK.reset();
150
+ }
113
151
  }
114
152
 
115
- // In other components, use the global SDK instance
116
- function Dashboard() {
117
- const handleButtonClick = () => {
118
- window.hydraSDK.pushEvent('button_click', {
119
- button_id: 'dashboard_action',
120
- timestamp: Date.now(),
121
- });
122
- };
153
+ export const sdkService = new SDKService();
154
+
155
+ // Initialize immediately at module load
156
+ sdkService.initialize();
157
+ ```
158
+
159
+ ```jsx
160
+ // App.tsx
161
+ import { useEffect } from 'react';
162
+ import { sdkService } from './services/sdkService';
123
163
 
124
- return <button onClick={handleButtonClick}>Click Me</button>;
164
+ function App() {
165
+ useEffect(() => {
166
+ sdkService.trackPageView();
167
+ }, []);
168
+
169
+ return <Dashboard />;
125
170
  }
126
171
  ```
127
172
 
128
- ## User Management
173
+ ---
174
+
175
+ ## Configuration
176
+
177
+ SDK configuration values like `accountId`, `baseURL`, `debugLevel`, etc. are automatically fetched from Firebase Remote Config. The host application only needs to provide Firebase credentials and the Remote Config key.
178
+
179
+ ### Required Fields
180
+
181
+ | Field | Type | Description |
182
+ | ----------------- | ---------------- | ------------------------------------------ |
183
+ | `firebaseConfig` | `FirebaseConfig` | Firebase project configuration |
184
+ | `remoteConfigKey` | `string` | Key to fetch SDK config from Remote Config |
185
+
186
+ ### Optional Fields
187
+
188
+ | Field | Type | Default | Description |
189
+ | --------------- | -------------------- | ----------------------------------------- | ------------------------------------------------------------ |
190
+ | `appVersion` | `string` | — | Host application version (populates `app_version` in events) |
191
+ | `retryDelays` | `number[]` | `[60000, 120000, 240000, 480000, 900000]` | Custom retry delays in milliseconds |
192
+ | `notifications` | `NotificationConfig` | — | Push notification configuration |
129
193
 
130
- ### User Lifecycle Events
194
+ ### Auto-populated Fields (from Remote Config)
131
195
 
132
- #### User Sign In
196
+ The following fields are fetched from Firebase Remote Config. **Do not set them manually:**
197
+
198
+ `accountId`, `baseURL`, `orgId`, `vapId`, `brandId`, `applicationId`, `source`, `channelType`, `sessionTimeoutMinutes`, `batchSize`, `debugLevel`
199
+
200
+ ---
201
+
202
+ ## Public API Reference
203
+
204
+ All 7 public methods are static and accessed via `WebSDK.*`. All methods (except `initialize`) internally wait for SDK initialization to complete before executing.
205
+
206
+ ### 1. `initialize(config)`
207
+
208
+ Creates and initializes the SDK singleton. Must be called once before any other method. Safe to call multiple times — subsequent calls return the existing instance.
133
209
 
134
210
  ```javascript
135
- sdk.pushUserSignin(
136
- 'user-12345', // cuid (required)
137
- 'John', // firstName (optional)
138
- 'Doe', // lastName (optional)
139
- 'user@example.com', // email (optional)
140
- '+1234567890', // phone (optional)
141
- {
142
- // customData (optional)
143
- method: 'email',
144
- provider: 'google',
145
- preferences: ['tech', 'sports'],
146
- }
147
- );
211
+ const sdk = WebSDK.initialize({
212
+ firebaseConfig: {
213
+ /* ... */
214
+ },
215
+ remoteConfigKey: 'your_app_config_key',
216
+ appVersion: '1.0.0',
217
+ });
148
218
  ```
149
219
 
150
- #### User Sign Up
220
+ | Parameter | Type | Required | Description |
221
+ | --------- | -------------- | -------- | ------------------------ |
222
+ | `config` | `WebSDKConfig` | Yes | SDK configuration object |
223
+
224
+ ---
225
+
226
+ ### 2. `track(eventName, properties?)`
227
+
228
+ Tracks a custom behavioral event.
151
229
 
152
230
  ```javascript
153
- sdk.pushUserSignup(
154
- 'user-12345', // cuid (required)
155
- 'John', // firstName (required)
156
- 'Doe', // lastName (required)
157
- 'user@example.com', // email (required)
158
- '+1234567890', // phone (required)
159
- {
160
- // customData (optional)
161
- method: 'email',
162
- age: 30,
163
- interests: ['technology', 'travel'],
164
- }
165
- );
231
+ WebSDK.track('button_click', {
232
+ button_id: 'checkout',
233
+ page: 'cart',
234
+ value: 99.99,
235
+ });
166
236
  ```
167
237
 
168
- #### User Profile Update
238
+ | Parameter | Type | Required | Description |
239
+ | ------------ | ------------------------- | -------- | ----------------------- |
240
+ | `eventName` | `string` | Yes | Name of the event |
241
+ | `properties` | `Record<string, unknown>` | No | Custom event properties |
242
+
243
+ ---
244
+
245
+ ### 3. `pageView(options?)`
246
+
247
+ Tracks a page view event. If called with no arguments, automatically captures the current URL and page title.
169
248
 
170
249
  ```javascript
171
- sdk.pushUserUpdate(
172
- 'user-12345', // cuid (required)
173
- 'John', // firstName (optional)
174
- 'Smith', // lastName (optional)
175
- 'john.smith@example.com', // email (optional)
176
- '+1234567890', // phone (optional)
177
- {
178
- // customData (optional)
179
- age: 31,
180
- preferences: ['tech', 'music', 'travel'],
181
- }
182
- );
250
+ // Automatic capture
251
+ WebSDK.pageView();
252
+
253
+ // With custom options
254
+ WebSDK.pageView({
255
+ url: 'https://example.com/products/123',
256
+ title: 'Product Detail',
257
+ category: 'product',
258
+ properties: { productId: 'SKU-123' },
259
+ });
183
260
  ```
184
261
 
185
- #### User Sign Out
262
+ | Parameter | Type | Required | Description |
263
+ | --------- | ----------------- | -------- | ------------------ |
264
+ | `options` | `PageViewOptions` | No | Page view metadata |
265
+
266
+ **`PageViewOptions` fields:**
267
+
268
+ | Field | Type | Description |
269
+ | ------------ | ------------------------- | --------------------------------------------------------- |
270
+ | `url` | `string` | Override the current page URL |
271
+ | `title` | `string` | Override the current page title |
272
+ | `category` | `string` | Page category (e.g., `'blog'`, `'product'`, `'checkout'`) |
273
+ | `properties` | `Record<string, unknown>` | Custom properties |
274
+
275
+ ---
276
+
277
+ ### 4. `identify(params)`
278
+
279
+ Identifies a user (login/signup) or updates user profile attributes. This is the primary method for user identity management.
186
280
 
187
281
  ```javascript
188
- sdk.pushUserSignOut('user-12345'); // cuid (required)
282
+ // User login / signup
283
+ WebSDK.identify({
284
+ identifier: { type: 'email', cuid: 'user@example.com' },
285
+ actionType: 'USER_REGISTER',
286
+ traits: {
287
+ firstName: 'John',
288
+ lastName: 'Doe',
289
+ gender: 'male',
290
+ custom: { plan: 'premium' },
291
+ },
292
+ });
293
+
294
+ // User profile update
295
+ WebSDK.identify({
296
+ identifier: { type: 'mobile', cuid: '+1234567890' },
297
+ actionType: 'USER_UPDATE',
298
+ traits: {
299
+ firstName: 'John',
300
+ lastName: 'Smith',
301
+ },
302
+ });
189
303
  ```
190
304
 
191
- ## Event Tracking
305
+ | Parameter | Type | Required | Description |
306
+ | --------- | ---------------- | -------- | ------------------- |
307
+ | `params` | `IdentifyParams` | Yes | Identity parameters |
308
+
309
+ **`IdentifyParams` fields:**
310
+
311
+ | Field | Type | Required | Description |
312
+ | ------------ | -------------------- | -------- | ------------------------------------ |
313
+ | `identifier` | `Identifier` | Yes | User identifier (`type` + `cuid`) |
314
+ | `actionType` | `IdentifyActionType` | Yes | `'USER_REGISTER'` or `'USER_UPDATE'` |
315
+ | `traits` | `IdentifyTraits` | No | User profile attributes |
316
+
317
+ **`Identifier.type` values:** `'email'`, `'mobile'`, `'externalId'`
192
318
 
193
- ### Behavioral Events
319
+ ---
194
320
 
195
- **Push Event:**
321
+ ### 5. `enableSDK()`
322
+
323
+ Re-enables event tracking after it was disabled. Pending events in the queue are processed.
196
324
 
197
325
  ```javascript
198
- sdk.pushEvent(eventName, attributes);
199
- // eventName (required)
200
- // attributes (optional)
326
+ WebSDK.enableSDK();
201
327
  ```
202
328
 
203
- **Common Behavioral Events:**
329
+ ---
330
+
331
+ ### 6. `disableSDK()`
332
+
333
+ Disables event tracking. New events are dropped. Existing queued events are preserved in IndexedDB and will be sent when the SDK is re-enabled.
204
334
 
205
335
  ```javascript
206
- // Button clicks
207
- sdk.pushEvent('button_click', {
208
- button_id: 'checkout',
209
- button_text: 'Complete Purchase',
210
- page: 'cart',
211
- section: 'payment',
212
- });
336
+ WebSDK.disableSDK();
337
+ ```
213
338
 
214
- // E-commerce events
215
- sdk.pushEvent('add_to_cart', {
216
- product_id: 'shoe-123',
217
- product_name: 'Nike Air Max',
218
- quantity: 1,
219
- price: 129.99,
220
- currency: 'USD',
221
- cart_total: 259.98,
222
- });
339
+ ---
340
+
341
+ ### 7. `reset()`
342
+
343
+ Signs out the current user and returns the SDK to anonymous tracking mode.
223
344
 
224
- // Page navigation
225
- sdk.pushEvent('page_view', {
226
- page: '/dashboard',
227
- referrer: '/home',
228
- timestamp: Date.now(),
345
+ ```javascript
346
+ WebSDK.reset();
347
+ ```
348
+
349
+ ---
350
+
351
+ ## Push Notifications
352
+
353
+ To enable push notifications, add the `notifications` config to `initialize()`:
354
+
355
+ ```javascript
356
+ WebSDK.initialize({
357
+ firebaseConfig: {
358
+ /* ... */
359
+ },
360
+ remoteConfigKey: 'your_app_config_key',
361
+ notifications: {
362
+ enableNotifications: true,
363
+ vapidKey: 'YOUR_VAPID_KEY',
364
+ serviceWorkerPath: '/firebase-messaging-sw.js',
365
+ },
229
366
  });
230
367
  ```
368
+
369
+ **Service Worker Setup:**
370
+
371
+ 1. Copy `firebase-messaging-sw.js` from `node_modules/cap-hydra-web-sdk/public/` into your `public/` directory.
372
+ 2. Update the Firebase config inside the copied file with your credentials.
373
+ 3. Set `serviceWorkerPath` to the URL path where the file is accessible from the browser.
374
+
375
+ **`serviceWorkerPath` depends on where your app is served from:**
376
+
377
+ | Scenario | `serviceWorkerPath` value |
378
+ | ---------------------------------------------- | ------------------------------------- |
379
+ | App at root (`https://example.com/`) | `/firebase-messaging-sw.js` (default) |
380
+ | App at subpath (`https://example.com/my-app/`) | `/my-app/firebase-messaging-sw.js` |
381
+
382
+ If not provided, it defaults to `/firebase-messaging-sw.js`.
383
+
384
+ ---
385
+
386
+ ## Minimum Browser Requirements
387
+
388
+ | Browser | Minimum Version | Notes |
389
+ | ------- | --------------- | ----------------------------------------------------- |
390
+ | Chrome | 49+ | Full support |
391
+ | Firefox | 52+ (ESR) | Full support |
392
+ | Safari | 10+ | Service Worker requires 11.1+ |
393
+ | Edge | 79+ (Chromium) | Full support |
394
+ | IE | 11 | Limited: no Service Worker, no Push API, no Web Locks |
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { WebSDK as default } from '@/core/init';
2
+ export { DebugLevel, FirebaseConfig, Identifier, IdentifierType, IdentifyActionType, IdentifyParams, IdentifyTraits, NotificationConfig, NotificationPayload, NotificationState, PageViewOptions, UserAttributes, WebSDKConfig } from '@/shared/types';