vesant-sdk 1.2.0 → 1.3.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.
Files changed (71) hide show
  1. package/dist/{client-BWp5FI3x.d.ts → client-B6fUFAUM.d.mts} +2 -1
  2. package/dist/{client-BIfLMfuC.d.mts → client-DoczGA6L.d.ts} +2 -1
  3. package/dist/client-DzElM7u-.d.mts +238 -0
  4. package/dist/client-DzElM7u-.d.ts +238 -0
  5. package/dist/compliance/index.d.mts +5 -4
  6. package/dist/compliance/index.d.ts +5 -4
  7. package/dist/compliance/index.js +306 -98
  8. package/dist/compliance/index.js.map +1 -1
  9. package/dist/compliance/index.mjs +306 -98
  10. package/dist/compliance/index.mjs.map +1 -1
  11. package/dist/decisions/index.d.mts +100 -0
  12. package/dist/decisions/index.d.ts +100 -0
  13. package/dist/decisions/index.js +607 -0
  14. package/dist/decisions/index.js.map +1 -0
  15. package/dist/decisions/index.mjs +605 -0
  16. package/dist/decisions/index.mjs.map +1 -0
  17. package/dist/geolocation/index.d.mts +4 -3
  18. package/dist/geolocation/index.d.ts +4 -3
  19. package/dist/geolocation/index.js +306 -98
  20. package/dist/geolocation/index.js.map +1 -1
  21. package/dist/geolocation/index.mjs +306 -98
  22. package/dist/geolocation/index.mjs.map +1 -1
  23. package/dist/index.d.mts +15 -7
  24. package/dist/index.d.ts +15 -7
  25. package/dist/index.js +676 -90
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +667 -91
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/kyc/core.d.mts +4 -3
  30. package/dist/kyc/core.d.ts +4 -3
  31. package/dist/kyc/core.js +284 -29
  32. package/dist/kyc/core.js.map +1 -1
  33. package/dist/kyc/core.mjs +284 -29
  34. package/dist/kyc/core.mjs.map +1 -1
  35. package/dist/kyc/index.d.mts +46 -3
  36. package/dist/kyc/index.d.ts +46 -3
  37. package/dist/kyc/index.js +284 -29
  38. package/dist/kyc/index.js.map +1 -1
  39. package/dist/kyc/index.mjs +284 -29
  40. package/dist/kyc/index.mjs.map +1 -1
  41. package/dist/react.d.mts +9 -5
  42. package/dist/react.d.ts +9 -5
  43. package/dist/react.js +422 -99
  44. package/dist/react.js.map +1 -1
  45. package/dist/react.mjs +322 -4
  46. package/dist/react.mjs.map +1 -1
  47. package/dist/risk-profile/index.d.mts +4 -4
  48. package/dist/risk-profile/index.d.ts +4 -4
  49. package/dist/risk-profile/index.js +249 -29
  50. package/dist/risk-profile/index.js.map +1 -1
  51. package/dist/risk-profile/index.mjs +249 -29
  52. package/dist/risk-profile/index.mjs.map +1 -1
  53. package/dist/scores/index.d.mts +96 -0
  54. package/dist/scores/index.d.ts +96 -0
  55. package/dist/scores/index.js +594 -0
  56. package/dist/scores/index.js.map +1 -0
  57. package/dist/scores/index.mjs +591 -0
  58. package/dist/scores/index.mjs.map +1 -0
  59. package/dist/{types-DfHLp_tz.d.ts → types-DLC7Sfy5.d.ts} +1 -1
  60. package/dist/types-DZHongaK.d.mts +61 -0
  61. package/dist/types-DZHongaK.d.ts +61 -0
  62. package/dist/{types-DKCQN4C5.d.mts → types-jaLuzruy.d.mts} +1 -1
  63. package/dist/webhooks/index.d.mts +176 -0
  64. package/dist/webhooks/index.d.ts +176 -0
  65. package/dist/webhooks/index.js +193 -0
  66. package/dist/webhooks/index.js.map +1 -0
  67. package/dist/webhooks/index.mjs +188 -0
  68. package/dist/webhooks/index.mjs.map +1 -0
  69. package/package.json +25 -2
  70. package/dist/types-BpKxSXGF.d.mts +0 -177
  71. package/dist/types-BpKxSXGF.d.ts +0 -177
@@ -0,0 +1,96 @@
1
+ import { B as BaseClient, R as RequestOptions } from '../client-DzElM7u-.js';
2
+ import { c as RiskLevel, T as Timestamp, U as UUID } from '../types-DZHongaK.js';
3
+
4
+ /**
5
+ * Score and Workflow type definitions.
6
+ */
7
+
8
+ interface CustomerScore {
9
+ customer_id: string;
10
+ overall_score: number;
11
+ risk_level: RiskLevel;
12
+ risk_category: string;
13
+ last_calculated: Timestamp;
14
+ }
15
+ interface ScoreFactor {
16
+ name: string;
17
+ value: number;
18
+ weight: number;
19
+ description?: string;
20
+ }
21
+ interface ScoreHistoryEntry {
22
+ score: number;
23
+ risk_level: RiskLevel;
24
+ calculated_at: Timestamp;
25
+ }
26
+ interface ScoreBreakdown extends CustomerScore {
27
+ factors: ScoreFactor[];
28
+ history: ScoreHistoryEntry[];
29
+ weights: Record<string, number>;
30
+ thresholds: Record<RiskLevel, number>;
31
+ }
32
+ type WorkflowStatus = 'pending' | 'in_progress' | 'awaiting_review' | 'completed' | 'failed' | 'cancelled';
33
+ type WorkflowStepType = 'geolocation_verification' | 'kyc_submission' | 'risk_assessment' | 'decision' | 'manual_review' | 'edd_review';
34
+ interface WorkflowStep {
35
+ id: UUID;
36
+ type: WorkflowStepType;
37
+ status: WorkflowStatus;
38
+ result?: Record<string, unknown>;
39
+ started_at?: Timestamp;
40
+ completed_at?: Timestamp;
41
+ }
42
+ interface Workflow {
43
+ id: UUID;
44
+ customer_id: string;
45
+ status: WorkflowStatus;
46
+ steps: WorkflowStep[];
47
+ metadata?: Record<string, unknown>;
48
+ created_at: Timestamp;
49
+ updated_at: Timestamp;
50
+ }
51
+ interface WorkflowFilters {
52
+ status?: WorkflowStatus;
53
+ customer_id?: string;
54
+ from_date?: string;
55
+ to_date?: string;
56
+ page?: number;
57
+ page_size?: number;
58
+ }
59
+ interface WorkflowListResponse {
60
+ data: Workflow[];
61
+ total: number;
62
+ page: number;
63
+ page_size: number;
64
+ total_pages: number;
65
+ }
66
+
67
+ /**
68
+ * Scores and Workflow API clients.
69
+ */
70
+
71
+ declare class ScoresClient extends BaseClient {
72
+ /**
73
+ * Get the current risk score for a customer.
74
+ */
75
+ getScore(customerId: string, requestOptions?: RequestOptions): Promise<CustomerScore>;
76
+ /**
77
+ * Get a detailed score breakdown for a customer.
78
+ */
79
+ getScoreBreakdown(customerId: string, requestOptions?: RequestOptions): Promise<ScoreBreakdown>;
80
+ }
81
+ declare class WorkflowClient extends BaseClient {
82
+ /**
83
+ * Get the current workflow status for a customer.
84
+ */
85
+ getWorkflowStatus(customerId: string, requestOptions?: RequestOptions): Promise<Workflow>;
86
+ /**
87
+ * List workflows with optional filters.
88
+ */
89
+ listWorkflows(filters?: WorkflowFilters, requestOptions?: RequestOptions): Promise<WorkflowListResponse>;
90
+ /**
91
+ * Get a specific workflow by ID.
92
+ */
93
+ getWorkflow(workflowId: string, requestOptions?: RequestOptions): Promise<Workflow>;
94
+ }
95
+
96
+ export { type CustomerScore, type ScoreBreakdown, type ScoreFactor, type ScoreHistoryEntry, ScoresClient, type Workflow, WorkflowClient, type WorkflowFilters, type WorkflowListResponse, type WorkflowStatus, type WorkflowStep, type WorkflowStepType };
@@ -0,0 +1,594 @@
1
+ 'use strict';
2
+
3
+ // src/core/errors.ts
4
+ var CGSError = class _CGSError extends Error {
5
+ constructor(message, code, statusCode, details) {
6
+ super(message);
7
+ this.code = code;
8
+ this.statusCode = statusCode;
9
+ this.details = details;
10
+ this.name = "CGSError";
11
+ Object.setPrototypeOf(this, _CGSError.prototype);
12
+ }
13
+ };
14
+ var NetworkError = class _NetworkError extends CGSError {
15
+ constructor(message, originalError) {
16
+ super(message, "NETWORK_ERROR", void 0, { originalError });
17
+ this.originalError = originalError;
18
+ this.name = "NetworkError";
19
+ Object.setPrototypeOf(this, _NetworkError.prototype);
20
+ }
21
+ };
22
+ var ValidationError = class _ValidationError extends CGSError {
23
+ constructor(message, fields) {
24
+ super(message, "VALIDATION_ERROR", 400, { fields });
25
+ this.name = "ValidationError";
26
+ Object.setPrototypeOf(this, _ValidationError.prototype);
27
+ }
28
+ };
29
+ var ServiceUnavailableError = class _ServiceUnavailableError extends CGSError {
30
+ constructor(message) {
31
+ super(`${message} is unavailable`, "SERVICE_UNAVAILABLE", 503, { service: message });
32
+ this.name = "ServiceUnavailableError";
33
+ Object.setPrototypeOf(this, _ServiceUnavailableError.prototype);
34
+ }
35
+ };
36
+ var AuthenticationError = class _AuthenticationError extends CGSError {
37
+ constructor(message = "Authentication failed") {
38
+ super(message, "AUTHENTICATION_ERROR", 401);
39
+ this.name = "AuthenticationError";
40
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
41
+ }
42
+ };
43
+ var RateLimitError = class _RateLimitError extends CGSError {
44
+ constructor(retryAfter) {
45
+ super("Rate limit exceeded", "RATE_LIMIT_EXCEEDED", 429, { retryAfter });
46
+ this.retryAfter = retryAfter;
47
+ this.name = "RateLimitError";
48
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
49
+ }
50
+ };
51
+ var TimeoutError = class _TimeoutError extends CGSError {
52
+ constructor(timeout) {
53
+ super(`Request timeout after ${timeout}ms`, "TIMEOUT", 408, { timeout });
54
+ this.timeout = timeout;
55
+ this.name = "TimeoutError";
56
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
57
+ }
58
+ };
59
+ var CircuitBreakerOpenError = class _CircuitBreakerOpenError extends CGSError {
60
+ constructor() {
61
+ super("Circuit breaker is open \u2014 requests are temporarily blocked", "CIRCUIT_BREAKER_OPEN", 503);
62
+ this.name = "CircuitBreakerOpenError";
63
+ Object.setPrototypeOf(this, _CircuitBreakerOpenError.prototype);
64
+ }
65
+ };
66
+
67
+ // src/core/circuit-breaker.ts
68
+ var CircuitBreaker = class {
69
+ constructor(config = {}) {
70
+ this.state = "closed";
71
+ this.failures = 0;
72
+ this.successes = 0;
73
+ this.lastFailureTime = null;
74
+ this.failureThreshold = config.failureThreshold ?? 5;
75
+ this.resetTimeout = config.resetTimeout ?? 3e4;
76
+ this.successThreshold = config.successThreshold ?? 1;
77
+ }
78
+ /**
79
+ * Check if a request can proceed through the circuit breaker.
80
+ */
81
+ canExecute() {
82
+ if (this.state === "closed") {
83
+ return true;
84
+ }
85
+ if (this.state === "open") {
86
+ const now = Date.now();
87
+ if (this.lastFailureTime && now - this.lastFailureTime >= this.resetTimeout) {
88
+ this.state = "half-open";
89
+ this.successes = 0;
90
+ return true;
91
+ }
92
+ return false;
93
+ }
94
+ return true;
95
+ }
96
+ /**
97
+ * Record a successful request.
98
+ */
99
+ onSuccess() {
100
+ if (this.state === "half-open") {
101
+ this.successes++;
102
+ if (this.successes >= this.successThreshold) {
103
+ this.state = "closed";
104
+ this.failures = 0;
105
+ this.successes = 0;
106
+ this.lastFailureTime = null;
107
+ }
108
+ } else if (this.state === "closed") {
109
+ this.failures = 0;
110
+ }
111
+ }
112
+ /**
113
+ * Record a failed request.
114
+ */
115
+ onFailure() {
116
+ this.failures++;
117
+ this.lastFailureTime = Date.now();
118
+ if (this.state === "half-open") {
119
+ this.state = "open";
120
+ this.successes = 0;
121
+ } else if (this.state === "closed" && this.failures >= this.failureThreshold) {
122
+ this.state = "open";
123
+ }
124
+ }
125
+ /**
126
+ * Get current circuit breaker status.
127
+ */
128
+ getStatus() {
129
+ return {
130
+ state: this.state,
131
+ failures: this.failures,
132
+ successes: this.successes,
133
+ lastFailureTime: this.lastFailureTime,
134
+ nextRetryTime: this.state === "open" && this.lastFailureTime ? this.lastFailureTime + this.resetTimeout : null
135
+ };
136
+ }
137
+ /**
138
+ * Reset the circuit breaker to its initial closed state.
139
+ */
140
+ reset() {
141
+ this.state = "closed";
142
+ this.failures = 0;
143
+ this.successes = 0;
144
+ this.lastFailureTime = null;
145
+ }
146
+ };
147
+
148
+ // src/core/rate-limiter.ts
149
+ var RateLimitTracker = class {
150
+ constructor() {
151
+ this.limit = null;
152
+ this.remaining = null;
153
+ this.reset = null;
154
+ this.retryAfter = null;
155
+ }
156
+ /**
157
+ * Extract rate limit information from response headers.
158
+ */
159
+ updateFromHeaders(headers) {
160
+ const limit = headers.get("x-ratelimit-limit");
161
+ const remaining = headers.get("x-ratelimit-remaining");
162
+ const reset = headers.get("x-ratelimit-reset");
163
+ const retryAfter = headers.get("retry-after");
164
+ if (limit !== null) this.limit = parseInt(limit, 10);
165
+ if (remaining !== null) this.remaining = parseInt(remaining, 10);
166
+ if (reset !== null) this.reset = parseInt(reset, 10);
167
+ if (retryAfter !== null) this.retryAfter = parseInt(retryAfter, 10);
168
+ }
169
+ /**
170
+ * Check if the rate limit has been exceeded based on tracked headers.
171
+ */
172
+ isLimitExceeded() {
173
+ if (this.remaining !== null && this.remaining <= 0) {
174
+ if (this.reset !== null) {
175
+ const now = Math.floor(Date.now() / 1e3);
176
+ if (now >= this.reset) {
177
+ this.remaining = null;
178
+ this.reset = null;
179
+ this.retryAfter = null;
180
+ return false;
181
+ }
182
+ }
183
+ return true;
184
+ }
185
+ return false;
186
+ }
187
+ /**
188
+ * Get current rate limit status.
189
+ */
190
+ getStatus() {
191
+ return {
192
+ limit: this.limit,
193
+ remaining: this.remaining,
194
+ reset: this.reset,
195
+ retryAfter: this.retryAfter
196
+ };
197
+ }
198
+ };
199
+
200
+ // src/core/logger.ts
201
+ function createConsoleLogger() {
202
+ return {
203
+ debug(message, meta) {
204
+ console.log(`[CGS SDK] ${message}`, meta !== void 0 ? meta : "");
205
+ },
206
+ info(message, meta) {
207
+ console.info(`[CGS SDK] ${message}`, meta !== void 0 ? meta : "");
208
+ },
209
+ warn(message, meta) {
210
+ console.warn(`[CGS SDK] ${message}`, meta !== void 0 ? meta : "");
211
+ },
212
+ error(message, meta) {
213
+ console.error(`[CGS SDK] ${message}`, meta !== void 0 ? meta : "");
214
+ }
215
+ };
216
+ }
217
+
218
+ // src/core/version.ts
219
+ var SDK_VERSION = "1.3.0";
220
+
221
+ // src/shared/browser-utils.ts
222
+ function generateUUID() {
223
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
224
+ return crypto.randomUUID();
225
+ }
226
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
227
+ const r = Math.random() * 16 | 0;
228
+ const v = c === "x" ? r : r & 3 | 8;
229
+ return v.toString(16);
230
+ });
231
+ }
232
+
233
+ // src/core/client.ts
234
+ var BaseClient = class {
235
+ constructor(config) {
236
+ this.circuitBreaker = null;
237
+ this.rateLimitTracker = null;
238
+ if (!config.baseURL?.trim()) {
239
+ throw new ValidationError("baseURL is required and must be a non-empty string", ["baseURL"]);
240
+ }
241
+ if (!config.tenantId?.trim()) {
242
+ throw new ValidationError("tenantId is required and must be a non-empty string", ["tenantId"]);
243
+ }
244
+ this.interceptors = config.interceptors || [];
245
+ this.logger = config.logger || createConsoleLogger();
246
+ this.config = {
247
+ ...config,
248
+ apiKey: config.apiKey || "",
249
+ headers: config.headers || {},
250
+ timeout: config.timeout || 1e4,
251
+ retries: config.retries || 3,
252
+ debug: config.debug || false,
253
+ interceptors: this.interceptors,
254
+ logger: this.logger
255
+ };
256
+ if (config.circuitBreaker) {
257
+ this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
258
+ }
259
+ if (config.enableRateLimitTracking) {
260
+ this.rateLimitTracker = new RateLimitTracker();
261
+ }
262
+ }
263
+ /**
264
+ * Make an HTTP request with timeout and error handling
265
+ */
266
+ async request(endpoint, options = {}, serviceURL, requestOptions) {
267
+ const requestId = generateUUID();
268
+ if (this.circuitBreaker && !this.circuitBreaker.canExecute()) {
269
+ const error = new CircuitBreakerOpenError();
270
+ error.requestId = requestId;
271
+ throw error;
272
+ }
273
+ if (this.rateLimitTracker && this.rateLimitTracker.isLimitExceeded()) {
274
+ const status = this.rateLimitTracker.getStatus();
275
+ const error = new RateLimitError(status.retryAfter ?? void 0);
276
+ error.requestId = requestId;
277
+ throw error;
278
+ }
279
+ const baseURL = this.config.environment === "sandbox" && this.config.sandboxBaseURL ? this.config.sandboxBaseURL : serviceURL || this.config.baseURL;
280
+ const url = `${serviceURL || baseURL}${endpoint}`;
281
+ const headers = {
282
+ "Content-Type": "application/json",
283
+ "X-Tenant-ID": this.config.tenantId,
284
+ "X-SDK-Version": `vesant-sdk-ts/${SDK_VERSION}`,
285
+ "X-Request-ID": requestId,
286
+ ...this.config.headers,
287
+ ...options.headers || {}
288
+ };
289
+ if (this.config.apiKey) {
290
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
291
+ }
292
+ if (this.config.environment === "sandbox") {
293
+ headers["X-Sandbox"] = "true";
294
+ }
295
+ const method = (options.method || "GET").toUpperCase();
296
+ if (["POST", "PUT", "PATCH"].includes(method)) {
297
+ headers["Idempotency-Key"] = requestOptions?.idempotencyKey || generateUUID();
298
+ }
299
+ const controller = new AbortController();
300
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
301
+ if (requestOptions?.signal) {
302
+ if (requestOptions.signal.aborted) {
303
+ controller.abort();
304
+ } else {
305
+ requestOptions.signal.addEventListener("abort", () => controller.abort(), { once: true });
306
+ }
307
+ }
308
+ try {
309
+ let finalOptions = { ...options, headers };
310
+ for (const interceptor of this.interceptors) {
311
+ if (interceptor.onRequest) {
312
+ finalOptions = await interceptor.onRequest(url, finalOptions);
313
+ }
314
+ }
315
+ if (this.config.debug) {
316
+ this.logger.debug(`${finalOptions.method || "GET"} ${url}`, {
317
+ headers: finalOptions.headers,
318
+ body: finalOptions.body
319
+ });
320
+ }
321
+ const response = await fetch(url, {
322
+ ...finalOptions,
323
+ signal: controller.signal
324
+ });
325
+ clearTimeout(timeoutId);
326
+ if (this.rateLimitTracker) {
327
+ this.rateLimitTracker.updateFromHeaders(response.headers);
328
+ }
329
+ let data;
330
+ try {
331
+ data = await response.json();
332
+ } catch {
333
+ if (!response.ok) {
334
+ this.handleErrorResponse(response.status, {
335
+ error: `HTTP ${response.status}`,
336
+ message: response.statusText
337
+ }, requestId);
338
+ }
339
+ this.circuitBreaker?.onSuccess();
340
+ return void 0;
341
+ }
342
+ if (!response.ok) {
343
+ this.handleErrorResponse(response.status, data || {}, requestId);
344
+ }
345
+ this.circuitBreaker?.onSuccess();
346
+ let result = data;
347
+ for (const interceptor of this.interceptors) {
348
+ if (interceptor.onResponse) {
349
+ result = await interceptor.onResponse(url, result);
350
+ }
351
+ }
352
+ if (this.config.debug) {
353
+ this.logger.debug("Response:", { data: result });
354
+ }
355
+ return result;
356
+ } catch (error) {
357
+ clearTimeout(timeoutId);
358
+ if (error instanceof CGSError && error.statusCode && error.statusCode >= 500) {
359
+ this.circuitBreaker?.onFailure();
360
+ } else if (error instanceof NetworkError || error instanceof TimeoutError) {
361
+ this.circuitBreaker?.onFailure();
362
+ }
363
+ if (error instanceof CGSError && !error.requestId) {
364
+ error.requestId = requestId;
365
+ }
366
+ if (error instanceof Error) {
367
+ for (const interceptor of this.interceptors) {
368
+ if (interceptor.onError) {
369
+ await interceptor.onError(url, error);
370
+ }
371
+ }
372
+ }
373
+ if (error instanceof Error) {
374
+ if (error.name === "AbortError") {
375
+ if (requestOptions?.signal?.aborted) {
376
+ const abortError = new CGSError("Request aborted", "REQUEST_ABORTED");
377
+ abortError.requestId = requestId;
378
+ throw abortError;
379
+ }
380
+ this.circuitBreaker?.onFailure();
381
+ const timeoutError = new TimeoutError(this.config.timeout);
382
+ timeoutError.requestId = requestId;
383
+ throw timeoutError;
384
+ }
385
+ if (error instanceof CGSError) {
386
+ throw error;
387
+ }
388
+ }
389
+ const networkError = new NetworkError("Network request failed", error);
390
+ networkError.requestId = requestId;
391
+ this.circuitBreaker?.onFailure();
392
+ throw networkError;
393
+ }
394
+ }
395
+ /**
396
+ * Make an HTTP request with retry logic
397
+ */
398
+ async requestWithRetry(endpoint, options = {}, serviceURL, retries = this.config.retries, requestOptions) {
399
+ let lastError;
400
+ for (let attempt = 0; attempt <= retries; attempt++) {
401
+ try {
402
+ return await this.request(endpoint, options, serviceURL, requestOptions);
403
+ } catch (error) {
404
+ lastError = error instanceof Error ? error : new Error("Unknown error");
405
+ if (requestOptions?.signal?.aborted) {
406
+ throw lastError;
407
+ }
408
+ if (lastError instanceof CGSError && lastError.statusCode && lastError.statusCode >= 400 && lastError.statusCode < 500 && lastError.statusCode !== 429) {
409
+ throw lastError;
410
+ }
411
+ if (attempt === retries) {
412
+ break;
413
+ }
414
+ let delay;
415
+ if (lastError instanceof RateLimitError && lastError.retryAfter) {
416
+ delay = lastError.retryAfter * 1e3;
417
+ } else {
418
+ delay = Math.min(1e3 * Math.pow(2, attempt) + Math.random() * 1e3, 1e4);
419
+ }
420
+ await new Promise((resolve) => setTimeout(resolve, delay));
421
+ if (this.config.debug) {
422
+ this.logger.debug(`Retry attempt ${attempt + 1}/${retries} after ${delay.toFixed(0)}ms`);
423
+ }
424
+ }
425
+ }
426
+ throw new NetworkError(`Request failed after ${retries} retries`, lastError);
427
+ }
428
+ /**
429
+ * Handle error responses from API
430
+ */
431
+ handleErrorResponse(status, data, requestId) {
432
+ const message = data.error || data.message || `HTTP ${status}`;
433
+ const createError = () => {
434
+ switch (status) {
435
+ case 400:
436
+ return new CGSError(message, "BAD_REQUEST", 400, data);
437
+ case 401:
438
+ return new AuthenticationError(message);
439
+ case 403:
440
+ return new CGSError(message, "FORBIDDEN", 403, data);
441
+ case 404:
442
+ return new CGSError(message, "NOT_FOUND", 404, data);
443
+ case 429: {
444
+ const retryAfter = data.retry_after || data.retryAfter;
445
+ return new RateLimitError(retryAfter);
446
+ }
447
+ case 500:
448
+ case 502:
449
+ case 503:
450
+ case 504:
451
+ return new ServiceUnavailableError(message);
452
+ default:
453
+ return new CGSError(message, "UNKNOWN_ERROR", status, data);
454
+ }
455
+ };
456
+ const error = createError();
457
+ if (requestId) {
458
+ error.requestId = requestId;
459
+ }
460
+ throw error;
461
+ }
462
+ /**
463
+ * Build query string from parameters
464
+ */
465
+ buildQueryString(params) {
466
+ const query = new URLSearchParams();
467
+ Object.entries(params).forEach(([key, value]) => {
468
+ if (value !== void 0 && value !== null) {
469
+ if (Array.isArray(value)) {
470
+ value.forEach((item) => query.append(key, String(item)));
471
+ } else {
472
+ query.append(key, String(value));
473
+ }
474
+ }
475
+ });
476
+ const queryString = query.toString();
477
+ return queryString ? `?${queryString}` : "";
478
+ }
479
+ /**
480
+ * Update client configuration
481
+ */
482
+ updateConfig(config) {
483
+ this.config = {
484
+ ...this.config,
485
+ ...config,
486
+ headers: {
487
+ ...this.config.headers,
488
+ ...config.headers || {}
489
+ }
490
+ };
491
+ if (config.logger) {
492
+ this.logger = config.logger;
493
+ }
494
+ if (config.interceptors) {
495
+ this.interceptors = config.interceptors;
496
+ }
497
+ }
498
+ /**
499
+ * Get current configuration (readonly)
500
+ */
501
+ getConfig() {
502
+ return { ...this.config };
503
+ }
504
+ /**
505
+ * Get rate limit status from tracked response headers.
506
+ */
507
+ getRateLimitStatus() {
508
+ return this.rateLimitTracker?.getStatus() ?? null;
509
+ }
510
+ /**
511
+ * Get circuit breaker status.
512
+ */
513
+ getCircuitBreakerStatus() {
514
+ return this.circuitBreaker?.getStatus() ?? null;
515
+ }
516
+ /**
517
+ * Health check endpoint
518
+ */
519
+ async healthCheck() {
520
+ return this.request("/api/v1/health");
521
+ }
522
+ };
523
+
524
+ // src/scores/client.ts
525
+ var ScoresClient = class extends BaseClient {
526
+ /**
527
+ * Get the current risk score for a customer.
528
+ */
529
+ async getScore(customerId, requestOptions) {
530
+ return this.requestWithRetry(
531
+ `/api/v1/scores/${encodeURIComponent(customerId)}`,
532
+ { method: "GET" },
533
+ void 0,
534
+ void 0,
535
+ requestOptions
536
+ );
537
+ }
538
+ /**
539
+ * Get a detailed score breakdown for a customer.
540
+ */
541
+ async getScoreBreakdown(customerId, requestOptions) {
542
+ return this.requestWithRetry(
543
+ `/api/v1/scores/${encodeURIComponent(customerId)}/breakdown`,
544
+ { method: "GET" },
545
+ void 0,
546
+ void 0,
547
+ requestOptions
548
+ );
549
+ }
550
+ };
551
+ var WorkflowClient = class extends BaseClient {
552
+ /**
553
+ * Get the current workflow status for a customer.
554
+ */
555
+ async getWorkflowStatus(customerId, requestOptions) {
556
+ return this.requestWithRetry(
557
+ `/api/v1/workflows/${encodeURIComponent(customerId)}/status`,
558
+ { method: "GET" },
559
+ void 0,
560
+ void 0,
561
+ requestOptions
562
+ );
563
+ }
564
+ /**
565
+ * List workflows with optional filters.
566
+ */
567
+ async listWorkflows(filters, requestOptions) {
568
+ const queryString = this.buildQueryString(filters || {});
569
+ return this.requestWithRetry(
570
+ `/api/v1/workflows${queryString}`,
571
+ { method: "GET" },
572
+ void 0,
573
+ void 0,
574
+ requestOptions
575
+ );
576
+ }
577
+ /**
578
+ * Get a specific workflow by ID.
579
+ */
580
+ async getWorkflow(workflowId, requestOptions) {
581
+ return this.requestWithRetry(
582
+ `/api/v1/workflows/${encodeURIComponent(workflowId)}`,
583
+ { method: "GET" },
584
+ void 0,
585
+ void 0,
586
+ requestOptions
587
+ );
588
+ }
589
+ };
590
+
591
+ exports.ScoresClient = ScoresClient;
592
+ exports.WorkflowClient = WorkflowClient;
593
+ //# sourceMappingURL=index.js.map
594
+ //# sourceMappingURL=index.js.map