@veridia/node-sdk 1.0.3 → 1.0.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 CHANGED
@@ -1,7 +1,9 @@
1
1
  # Veridia Node SDK
2
2
 
3
- Official Node.js SDK for integrating with [Veridia Platform](https://veridia.io).
4
- It provides an easy way to send user identification and tracking data, retrieve user segments, and integrate Veridia into your backend systems.
3
+ [![npm version](https://img.shields.io/npm/v/@veridia/node-sdk.svg)](https://www.npmjs.com/package/@veridia/node-sdk)
4
+
5
+ Official Node.js SDK for integrating with the [Veridia Platform](https://veridia.io).
6
+ It provides an easy way to identify users, send tracking events, retrieve user segments, and manage batching with retries and timeouts — all from your backend.
5
7
 
6
8
  ---
7
9
 
@@ -55,7 +57,8 @@ const client = new VeridiaClient({
55
57
 
56
58
  ### `identify(identifierType, identifierId, attributes)`
57
59
 
58
- Identify a user and update their profile attributes. Provided attributes must match the Profile Attributes schema defined in the Veridia dashboard.
60
+ Identify a user and update their profile attributes.
61
+ Provided attributes must match the Profile Attributes schema defined in your Veridia dashboard.
59
62
 
60
63
  ```ts
61
64
  await client.identify('userId', '123', {
@@ -65,17 +68,18 @@ await client.identify('userId', '123', {
65
68
  });
66
69
  ```
67
70
 
68
- | Parameter | Type | Description |
69
- | ---------------- | ----------------------- | ---------------------------- |
70
- | `identifierType` | `"userId"` \| `"email"` | How the user is identified. |
71
- | `identifierId` | `string` | The unique identifier value. |
72
- | `attributes` | `Record<string, any>` | Arbitrary user attributes. |
71
+ | Parameter | Type | Description |
72
+ | ---------------- | ----------------------- | --------------------------- |
73
+ | `identifierType` | `"userId"` \| `"email"` | How the user is identified. |
74
+ | `identifierId` | `string` | Unique identifier value. |
75
+ | `attributes` | `Record<string, any>` | Arbitrary user attributes. |
73
76
 
74
77
  ---
75
78
 
76
79
  ### `track(identifierType, identifierId, eventType, eventId, eventTime, properties)`
77
80
 
78
- Track an event performed by a user. Provided attributes must match the event attributes schema defined in the Veridia dashboard.
81
+ Track an event performed by a user.
82
+ Provided attributes must match the event attributes schema defined in your Veridia dashboard.
79
83
 
80
84
  ```ts
81
85
  await client.track('userId', '123', 'purchase', 'evt-001', new Date().toISOString(), {
@@ -84,26 +88,34 @@ await client.track('userId', '123', 'purchase', 'evt-001', new Date().toISOStrin
84
88
  });
85
89
  ```
86
90
 
87
- | Parameter | Type | Description |
88
- | ---------------- | ----------------------- | ----------------------------------- |
89
- | `identifierType` | `"userId"` \| `"email"` | How the user is identified. |
90
- | `identifierId` | `string` | Unique identifier for the user. |
91
- | `eventType` | `string` | Event type as in Veridia dashboard. |
92
- | `eventId` | `string` | Unique event ID for idempotency. |
93
- | `eventTime` | `string` | ISO timestamp string. |
94
- | `properties` | `Record<string, any>` | Optional event properties. |
91
+ | Parameter | Type | Description |
92
+ | ---------------- | ----------------------- | -------------------------------- |
93
+ | `identifierType` | `"userId"` \| `"email"` | How the user is identified. |
94
+ | `identifierId` | `string` | Unique user identifier. |
95
+ | `eventType` | `string` | Logical name of the event. |
96
+ | `eventId` | `string` | Unique event ID for idempotency. |
97
+ | `eventTime` | `string` | ISO timestamp string. |
98
+ | `properties` | `Record<string, any>` | Optional event properties. |
95
99
 
96
100
  ---
97
101
 
98
- ### `getUserSegments(identifierType, identifierId)`
102
+ ### `getUserSegments(identifierType, identifierId, [noSegmentsOnError=true])`
99
103
 
100
104
  Fetches the list of segments the specified user currently belongs to.
105
+ If the API call fails and `noSegmentsOnError` is set to `false`, it will throw an error.
106
+ Otherwise, it will return an empty array.
101
107
 
102
108
  ```ts
103
109
  const segments = await client.getUserSegments('userId', '123');
104
110
  console.log(segments); // ['617090ac-a1f6-4c70-a79e-40830a367324', '67f2c139-850f-469f-9ca4-a1c58e6d84ea']
105
111
  ```
106
112
 
113
+ | Parameter | Type | Default | Description |
114
+ | ------------------- | ---------- | --------- | --------------------------------------------------- | ------------------------ |
115
+ | `identifierType` | `"userId"` | `"email"` | — | Type of user identifier. |
116
+ | `identifierId` | `string` | — | Unique user ID or email. |
117
+ | `noSegmentsOnError` | `boolean` | `true` | If true, returns `[]` instead of throwing an error. |
118
+
107
119
  Returns:
108
120
  `Promise<string[]>` — Array of segment identifiers.
109
121
 
@@ -112,6 +124,7 @@ Returns:
112
124
  ### `flush()`
113
125
 
114
126
  Immediately sends all queued identify and track data.
127
+ Automatically called when buffers reach their configured limits or after the flush interval.
115
128
 
116
129
  ```ts
117
130
  await client.flush();
@@ -119,8 +132,8 @@ await client.flush();
119
132
 
120
133
  ### `close()`
121
134
 
122
- Flushes all pending data and prepares the client for shutdown.
123
- Call this before process exit in background workers or serverless functions.
135
+ Flushes any remaining buffered data and closes the client gracefully.
136
+ Call this before application exit in workers or serverless environments.
124
137
 
125
138
  ```ts
126
139
  await client.close();
@@ -130,31 +143,39 @@ await client.close();
130
143
 
131
144
  ## ⚙️ Configuration Options
132
145
 
133
- | Option | Type | Default | Description |
134
- | -------------------------- | --------------- | --------------------------- | -------------------------------------- |
135
- | `accessKeyId` | `string` | — | Veridia API access key ID |
136
- | `secretAccessKey` | `string` | — | Veridia API secret |
137
- | `endpoint` | `string` | `https://api.veridia.io/v1` | API base URL |
138
- | `region` | `string` | `"default"` | API region |
139
- | `maxBufferSize` | `number` | `500` | Max number of items before auto-flush |
140
- | `maxBufferTimeMs` | `number` | `5000` | Max time before auto-flush |
141
- | `retries` | `number` | `3` | Retry attempts on transient errors |
142
- | `timeoutMsGetUserSegments` | `number` | `5000` | Timeout for `getUserSegments` requests |
143
- | `timeoutMsFlush` | `number` | `30000` | Timeout for batch flush |
144
- | `logger` | `VeridiaLogger` | | Custom logger implementation |
146
+ | Option | Type | Default | Description |
147
+ | -------------------------- | --------------- | --------------------------- | --------------------------------------------- |
148
+ | `accessKeyId` | `string` | — | Veridia API access key ID. |
149
+ | `secretAccessKey` | `string` | — | Veridia API secret. |
150
+ | `endpoint` | `string` | `https://api.veridia.io/v1` | API base URL. |
151
+ | `region` | `string` | `"default"` | API region. |
152
+ | `autoFlush` | `boolean` | `true` | Whether to automatically flush buffered data. |
153
+ | `maxBufferSize` | `number` | `500` | Max number of items before auto-flush. |
154
+ | `maxBufferTimeMs` | `number` | `5000` | Max time (ms) before auto-flush. |
155
+ | `retries` | `number` | `3` | Retry attempts on transient network errors. |
156
+ | `retryBaseDelayMs` | `number` | `500` | Base delay (ms) for exponential backoff. |
157
+ | `timeoutMsGetUserSegments` | `number` | `5000` | Timeout (ms) for `getUserSegments` calls. |
158
+ | `timeoutMsFlush` | `number` | `30000` | Timeout (ms) for batch flush requests. |
159
+ | `logger` | `VeridiaLogger` | — | Custom logger implementation. |
145
160
 
146
161
  ---
147
162
 
148
163
  ## 🧾 Logger Interface
149
164
 
150
- The SDK supports pluggable logging.
151
165
  You can integrate your own logger (e.g. Pino, Winston, Bunyan) by providing the following interface:
152
166
 
153
167
  ```ts
154
168
  interface VeridiaLogger {
155
- info(service: string, message: string, context?: unknown): void;
156
- warn(service: string, message: string, context?: unknown): void;
157
- error(service: string, message: string, context?: unknown): void;
169
+ info?(service: string, message: string, context?: VeridiaLogContext): void;
170
+ warn?(service: string, message: string, context?: VeridiaLogContext): void;
171
+ error(service: string, message: string, context?: VeridiaLogContext): void;
172
+ }
173
+
174
+ interface VeridiaLogContext {
175
+ status?: number;
176
+ error?: unknown;
177
+ data?: unknown;
178
+ [key: string]: unknown;
158
179
  }
159
180
  ```
160
181
 
@@ -179,8 +200,8 @@ const client = new VeridiaClient({
179
200
 
180
201
  ## 🧩 TypeScript Support
181
202
 
182
- The SDK ships with full `.d.ts` declarations and JSDoc for IntelliSense.
183
- Hover over any method in VS Code to see inline documentation and parameter hints.
203
+ The SDK ships with full `.d.ts` declarations and JSDoc documentation.
204
+ Hover over any method in VS Code to see inline descriptions and parameter hints.
184
205
 
185
206
  ---
186
207
 
@@ -198,6 +219,9 @@ const client = new VeridiaClient({
198
219
  await client.identify('userId', '123', { plan: 'gold' });
199
220
  await client.track('userId', '123', 'purchase', 'evt-123', new Date().toISOString());
200
221
  await client.flush();
222
+
223
+ const segments = await client.getUserSegments('userId', '123');
224
+ console.log('Segments:', segments);
201
225
  ```
202
226
 
203
227
  ---
@@ -7,6 +7,7 @@ export declare class VeridiaClient {
7
7
  private readonly logger;
8
8
  private readonly baseUrl;
9
9
  private readonly region;
10
+ private readonly autoFlush;
10
11
  private readonly maxBufferSize;
11
12
  private readonly maxBufferTimeMs;
12
13
  private readonly retries;
@@ -38,9 +39,10 @@ export declare class VeridiaClient {
38
39
  *
39
40
  * @param identifierType - The type of user identifier ("userId" | "email").
40
41
  * @param identifierId - The unique ID or email.
42
+ * @param [noSegmentsOnError=true] - Whether to throw an error or to return empty array of segments. Defaults to true.
41
43
  * @returns A list of segment identifiers the user currently belongs to.
42
44
  */
43
- getUserSegments(identifierType: IdentifierPayload['type'], identifierId: string): Promise<string[]>;
45
+ getUserSegments(identifierType: IdentifierPayload['type'], identifierId: string, noSegmentsOnError?: boolean): Promise<string[]>;
44
46
  /**
45
47
  * Sends all queued identify and track data to the Veridia API immediately.
46
48
  * Automatically called when buffers reach their limit or after the configured time interval.
@@ -44,6 +44,7 @@ class VeridiaClient {
44
44
  this.identifyBuffer = [];
45
45
  this.baseUrl = options.endpoint ?? 'https://api.veridia.io/v1';
46
46
  this.region = options.region ?? 'default';
47
+ this.autoFlush = options.autoFlush ?? true;
47
48
  this.maxBufferSize = options.maxBufferSize ?? 500;
48
49
  this.maxBufferTimeMs = options.maxBufferTimeMs ?? 5000;
49
50
  this.retries = options.retries ?? 3;
@@ -67,7 +68,8 @@ class VeridiaClient {
67
68
  },
68
69
  attributes,
69
70
  });
70
- this.scheduleFlushIfNeeded(this.identifyBuffer);
71
+ if (this.autoFlush)
72
+ this.scheduleFlushIfNeeded('profiles', this.identifyBuffer);
71
73
  }
72
74
  /**
73
75
  * Sends a tracking event for the given user.
@@ -87,16 +89,18 @@ class VeridiaClient {
87
89
  eventTime,
88
90
  properties,
89
91
  });
90
- this.scheduleFlushIfNeeded(this.trackBuffer);
92
+ if (this.autoFlush)
93
+ this.scheduleFlushIfNeeded('events', this.trackBuffer);
91
94
  }
92
95
  /**
93
96
  * Retrieves the current segments for the given user.
94
97
  *
95
98
  * @param identifierType - The type of user identifier ("userId" | "email").
96
99
  * @param identifierId - The unique ID or email.
100
+ * @param [noSegmentsOnError=true] - Whether to throw an error or to return empty array of segments. Defaults to true.
97
101
  * @returns A list of segment identifiers the user currently belongs to.
98
102
  */
99
- async getUserSegments(identifierType, identifierId) {
103
+ async getUserSegments(identifierType, identifierId, noSegmentsOnError = true) {
100
104
  try {
101
105
  const path = `/segments/${identifierType}/${encodeURIComponent(identifierId)}`;
102
106
  const url = `${this.baseUrl}${path}`;
@@ -118,7 +122,10 @@ class VeridiaClient {
118
122
  }).finally(() => clearTimeout(timeout));
119
123
  if (!res.ok) {
120
124
  this.logger?.error('segments', 'getUserSegments API call failed', { status: res.status });
121
- return [];
125
+ if (noSegmentsOnError)
126
+ return [];
127
+ else
128
+ throw new Error(`getUserSegments API call failed: ${res.status}`);
122
129
  }
123
130
  const data = (await res.json());
124
131
  if (data.status === 'success' && Array.isArray(data.data)) {
@@ -127,13 +134,19 @@ class VeridiaClient {
127
134
  this.logger?.error('segments', 'getUserSegments API returned invalid response', {
128
135
  data: data,
129
136
  });
130
- return [];
137
+ if (noSegmentsOnError)
138
+ return [];
139
+ else
140
+ throw new Error(`getUserSegments API returned invalid response: ${JSON.stringify(data)}`);
131
141
  }
132
142
  catch (err) {
133
143
  this.logger?.error('segments', 'getUserSegments encountered an error', {
134
144
  error: err,
135
145
  });
136
- return [];
146
+ if (noSegmentsOnError)
147
+ return [];
148
+ else
149
+ throw err;
137
150
  }
138
151
  }
139
152
  /**
@@ -157,12 +170,18 @@ class VeridiaClient {
157
170
  async close() {
158
171
  await this.flush();
159
172
  }
160
- scheduleFlushIfNeeded(buffer) {
173
+ scheduleFlushIfNeeded(service, buffer) {
161
174
  if (buffer.length >= this.maxBufferSize) {
162
- void this.flush();
175
+ this.flush().catch((error) => {
176
+ this.logger?.error(service, 'automatic flush failed', { error });
177
+ });
163
178
  }
164
179
  else if (!this.flushTimer) {
165
- this.flushTimer = setTimeout(() => this.flush(), this.maxBufferTimeMs);
180
+ this.flushTimer = setTimeout(() => {
181
+ this.flush().catch((error) => {
182
+ this.logger?.error(service, 'automatic flush failed', { error });
183
+ });
184
+ }, this.maxBufferTimeMs);
166
185
  }
167
186
  }
168
187
  async flushBatch(service, buffer) {
@@ -32,6 +32,7 @@ export type VeridiaClientOptions = {
32
32
  secretAccessKey: string;
33
33
  endpoint?: string;
34
34
  region?: string;
35
+ autoFlush?: boolean;
35
36
  maxBufferSize?: number;
36
37
  maxBufferTimeMs?: number;
37
38
  retries?: number;
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "1.0.3";
1
+ export declare const SDK_VERSION = "1.0.6";
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
- exports.SDK_VERSION = '1.0.3';
4
+ exports.SDK_VERSION = '1.0.6';
5
5
  //# sourceMappingURL=version.js.map
@@ -7,6 +7,7 @@ export declare class VeridiaClient {
7
7
  private readonly logger;
8
8
  private readonly baseUrl;
9
9
  private readonly region;
10
+ private readonly autoFlush;
10
11
  private readonly maxBufferSize;
11
12
  private readonly maxBufferTimeMs;
12
13
  private readonly retries;
@@ -38,9 +39,10 @@ export declare class VeridiaClient {
38
39
  *
39
40
  * @param identifierType - The type of user identifier ("userId" | "email").
40
41
  * @param identifierId - The unique ID or email.
42
+ * @param [noSegmentsOnError=true] - Whether to throw an error or to return empty array of segments. Defaults to true.
41
43
  * @returns A list of segment identifiers the user currently belongs to.
42
44
  */
43
- getUserSegments(identifierType: IdentifierPayload['type'], identifierId: string): Promise<string[]>;
45
+ getUserSegments(identifierType: IdentifierPayload['type'], identifierId: string, noSegmentsOnError?: boolean): Promise<string[]>;
44
46
  /**
45
47
  * Sends all queued identify and track data to the Veridia API immediately.
46
48
  * Automatically called when buffers reach their limit or after the configured time interval.
@@ -44,6 +44,7 @@ class VeridiaClient {
44
44
  this.identifyBuffer = [];
45
45
  this.baseUrl = options.endpoint ?? 'https://api.veridia.io/v1';
46
46
  this.region = options.region ?? 'default';
47
+ this.autoFlush = options.autoFlush ?? true;
47
48
  this.maxBufferSize = options.maxBufferSize ?? 500;
48
49
  this.maxBufferTimeMs = options.maxBufferTimeMs ?? 5000;
49
50
  this.retries = options.retries ?? 3;
@@ -67,7 +68,8 @@ class VeridiaClient {
67
68
  },
68
69
  attributes,
69
70
  });
70
- this.scheduleFlushIfNeeded(this.identifyBuffer);
71
+ if (this.autoFlush)
72
+ this.scheduleFlushIfNeeded('profiles', this.identifyBuffer);
71
73
  }
72
74
  /**
73
75
  * Sends a tracking event for the given user.
@@ -87,16 +89,18 @@ class VeridiaClient {
87
89
  eventTime,
88
90
  properties,
89
91
  });
90
- this.scheduleFlushIfNeeded(this.trackBuffer);
92
+ if (this.autoFlush)
93
+ this.scheduleFlushIfNeeded('events', this.trackBuffer);
91
94
  }
92
95
  /**
93
96
  * Retrieves the current segments for the given user.
94
97
  *
95
98
  * @param identifierType - The type of user identifier ("userId" | "email").
96
99
  * @param identifierId - The unique ID or email.
100
+ * @param [noSegmentsOnError=true] - Whether to throw an error or to return empty array of segments. Defaults to true.
97
101
  * @returns A list of segment identifiers the user currently belongs to.
98
102
  */
99
- async getUserSegments(identifierType, identifierId) {
103
+ async getUserSegments(identifierType, identifierId, noSegmentsOnError = true) {
100
104
  try {
101
105
  const path = `/segments/${identifierType}/${encodeURIComponent(identifierId)}`;
102
106
  const url = `${this.baseUrl}${path}`;
@@ -118,7 +122,10 @@ class VeridiaClient {
118
122
  }).finally(() => clearTimeout(timeout));
119
123
  if (!res.ok) {
120
124
  this.logger?.error('segments', 'getUserSegments API call failed', { status: res.status });
121
- return [];
125
+ if (noSegmentsOnError)
126
+ return [];
127
+ else
128
+ throw new Error(`getUserSegments API call failed: ${res.status}`);
122
129
  }
123
130
  const data = (await res.json());
124
131
  if (data.status === 'success' && Array.isArray(data.data)) {
@@ -127,13 +134,19 @@ class VeridiaClient {
127
134
  this.logger?.error('segments', 'getUserSegments API returned invalid response', {
128
135
  data: data,
129
136
  });
130
- return [];
137
+ if (noSegmentsOnError)
138
+ return [];
139
+ else
140
+ throw new Error(`getUserSegments API returned invalid response: ${JSON.stringify(data)}`);
131
141
  }
132
142
  catch (err) {
133
143
  this.logger?.error('segments', 'getUserSegments encountered an error', {
134
144
  error: err,
135
145
  });
136
- return [];
146
+ if (noSegmentsOnError)
147
+ return [];
148
+ else
149
+ throw err;
137
150
  }
138
151
  }
139
152
  /**
@@ -157,12 +170,18 @@ class VeridiaClient {
157
170
  async close() {
158
171
  await this.flush();
159
172
  }
160
- scheduleFlushIfNeeded(buffer) {
173
+ scheduleFlushIfNeeded(service, buffer) {
161
174
  if (buffer.length >= this.maxBufferSize) {
162
- void this.flush();
175
+ this.flush().catch((error) => {
176
+ this.logger?.error(service, 'automatic flush failed', { error });
177
+ });
163
178
  }
164
179
  else if (!this.flushTimer) {
165
- this.flushTimer = setTimeout(() => this.flush(), this.maxBufferTimeMs);
180
+ this.flushTimer = setTimeout(() => {
181
+ this.flush().catch((error) => {
182
+ this.logger?.error(service, 'automatic flush failed', { error });
183
+ });
184
+ }, this.maxBufferTimeMs);
166
185
  }
167
186
  }
168
187
  async flushBatch(service, buffer) {
@@ -32,6 +32,7 @@ export type VeridiaClientOptions = {
32
32
  secretAccessKey: string;
33
33
  endpoint?: string;
34
34
  region?: string;
35
+ autoFlush?: boolean;
35
36
  maxBufferSize?: number;
36
37
  maxBufferTimeMs?: number;
37
38
  retries?: number;
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "1.0.3";
1
+ export declare const SDK_VERSION = "1.0.6";
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
- exports.SDK_VERSION = '1.0.3';
4
+ exports.SDK_VERSION = '1.0.6';
5
5
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veridia/node-sdk",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "description": "",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",