@reevit/core 0.8.1 → 0.9.0
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 +28 -1
- package/dist/index.d.mts +35 -6
- package/dist/index.d.ts +35 -6
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +48 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -42,6 +42,33 @@ if (data) {
|
|
|
42
42
|
}
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
+
### Loading a checkout session
|
|
46
|
+
|
|
47
|
+
Browser SDKs should prefer server-created checkout sessions. Use the session secret returned by your backend to load the payment intent without exposing private API credentials.
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
const { data, error } = await client.getCheckoutSession('cs_session_secret');
|
|
51
|
+
|
|
52
|
+
if (data) {
|
|
53
|
+
console.log('Ready to render:', data.payment_intent.id);
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Error handling
|
|
58
|
+
|
|
59
|
+
Core returns a consistent `{ data, error }` result. Errors include `code`, `message`, `recoverable`, and `details.httpStatus` when the API returns a status code.
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
const result = await client.getCheckoutSession('cs_session_secret');
|
|
63
|
+
|
|
64
|
+
if (result.error) {
|
|
65
|
+
if (result.error.recoverable) {
|
|
66
|
+
// show retry UI
|
|
67
|
+
}
|
|
68
|
+
console.error(result.error.code, result.error.message);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
45
72
|
### Using Utilities
|
|
46
73
|
|
|
47
74
|
```typescript
|
|
@@ -72,7 +99,7 @@ const { idempotencyKey, reference } = resolveIntentIdentity({
|
|
|
72
99
|
|
|
73
100
|
## Release Notes
|
|
74
101
|
|
|
75
|
-
### v0.
|
|
102
|
+
### v0.9.0
|
|
76
103
|
|
|
77
104
|
- Version alignment across all Reevit SDKs
|
|
78
105
|
- Updated shared CSS with redesigned checkout visual system
|
package/dist/index.d.mts
CHANGED
|
@@ -10,10 +10,12 @@ type PaymentSource = 'payment_link' | 'api' | 'subscription';
|
|
|
10
10
|
interface ReevitCheckoutConfig {
|
|
11
11
|
/** Your Reevit public key (required for API-created intents; omit for payment links) */
|
|
12
12
|
publicKey?: string;
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
|
|
13
|
+
/** Server-created checkout session secret. Prefer this for browser checkouts. */
|
|
14
|
+
sessionSecret?: string;
|
|
15
|
+
/** Amount in the smallest currency unit (e.g., pesewas for GHS). Required unless sessionSecret or initialPaymentIntent is provided. */
|
|
16
|
+
amount?: number;
|
|
17
|
+
/** Currency code (e.g., 'GHS', 'NGN', 'USD'). Required unless sessionSecret or initialPaymentIntent is provided. */
|
|
18
|
+
currency?: string;
|
|
17
19
|
/** Customer email address */
|
|
18
20
|
email?: string;
|
|
19
21
|
/** Customer phone number (required for mobile money) */
|
|
@@ -247,6 +249,7 @@ interface PaymentIntentResponse {
|
|
|
247
249
|
provider_ref_id?: string;
|
|
248
250
|
status: string;
|
|
249
251
|
client_secret: string;
|
|
252
|
+
session_secret?: string;
|
|
250
253
|
psp_public_key: string;
|
|
251
254
|
psp_credentials?: {
|
|
252
255
|
merchantAccount?: string | number;
|
|
@@ -267,6 +270,13 @@ interface PaymentIntentResponse {
|
|
|
267
270
|
}>;
|
|
268
271
|
branding?: Record<string, unknown>;
|
|
269
272
|
}
|
|
273
|
+
interface CheckoutSessionResponse {
|
|
274
|
+
id: string;
|
|
275
|
+
client_secret: string;
|
|
276
|
+
session_secret: string;
|
|
277
|
+
payment_intent: PaymentIntentResponse;
|
|
278
|
+
expires_at?: string;
|
|
279
|
+
}
|
|
270
280
|
interface ConfirmPaymentRequest {
|
|
271
281
|
provider_ref_id: string;
|
|
272
282
|
provider_data?: Record<string, unknown>;
|
|
@@ -298,8 +308,15 @@ interface PaymentDetailResponse {
|
|
|
298
308
|
interface APIErrorResponse {
|
|
299
309
|
code: string;
|
|
300
310
|
message: string;
|
|
301
|
-
details?: Record<string,
|
|
311
|
+
details?: Record<string, unknown>;
|
|
302
312
|
}
|
|
313
|
+
type ReevitAPIResult<T> = {
|
|
314
|
+
data: T;
|
|
315
|
+
error?: never;
|
|
316
|
+
} | {
|
|
317
|
+
data?: never;
|
|
318
|
+
error: PaymentError;
|
|
319
|
+
};
|
|
303
320
|
interface ReevitAPIClientConfig {
|
|
304
321
|
/** Your Reevit public key */
|
|
305
322
|
publicKey?: string;
|
|
@@ -308,6 +325,11 @@ interface ReevitAPIClientConfig {
|
|
|
308
325
|
/** Request timeout in milliseconds */
|
|
309
326
|
timeout?: number;
|
|
310
327
|
}
|
|
328
|
+
/**
|
|
329
|
+
* Creates a PaymentError from an API error response
|
|
330
|
+
*/
|
|
331
|
+
declare function createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError;
|
|
332
|
+
declare function isPaymentError(error: unknown): error is PaymentError;
|
|
311
333
|
/**
|
|
312
334
|
* Generates a deterministic idempotency key based on input parameters
|
|
313
335
|
* Uses a simple hash function suitable for browser environments
|
|
@@ -344,6 +366,13 @@ declare class ReevitAPIClient {
|
|
|
344
366
|
data?: PaymentDetailResponse;
|
|
345
367
|
error?: PaymentError;
|
|
346
368
|
}>;
|
|
369
|
+
/**
|
|
370
|
+
* Retrieves a server-created checkout session using its public session secret.
|
|
371
|
+
*/
|
|
372
|
+
getCheckoutSession(sessionSecret: string): Promise<{
|
|
373
|
+
data?: CheckoutSessionResponse;
|
|
374
|
+
error?: PaymentError;
|
|
375
|
+
}>;
|
|
347
376
|
/**
|
|
348
377
|
* Confirms a payment after PSP callback
|
|
349
378
|
*/
|
|
@@ -494,4 +523,4 @@ declare function createInitialState(): ReevitState;
|
|
|
494
523
|
*/
|
|
495
524
|
declare function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState;
|
|
496
525
|
|
|
497
|
-
export { type APIErrorResponse, type CardFormData, type CheckoutProviderOption, type CheckoutState, type ConfirmPaymentRequest, type CreatePaymentIntentRequest, type HubtelSessionResponse, type IntentCacheEntry, type MobileMoneyFormData, type MobileMoneyNetwork, type PSPConfig, type PSPType, type PaymentDetailResponse, type PaymentError, type PaymentIntent, type PaymentIntentResponse, type PaymentMethod, type PaymentResult, type PaymentSource, ReevitAPIClient, type ReevitAPIClientConfig, type ReevitAction, type ReevitCheckoutCallbacks, type ReevitCheckoutConfig, type ReevitState, type ReevitTheme, cacheIntentPromise, cacheIntentResponse, clearIntentCacheEntry, cn, createInitialState, createReevitClient, createThemeVariables, detectCountryFromCurrency, detectNetwork, formatAmount, formatPhone, generateIdempotencyKey, generateReference, getIntentCacheEntry, reevitReducer, resolveIntentIdentity, validatePhone };
|
|
526
|
+
export { type APIErrorResponse, type CardFormData, type CheckoutProviderOption, type CheckoutSessionResponse, type CheckoutState, type ConfirmPaymentRequest, type CreatePaymentIntentRequest, type HubtelSessionResponse, type IntentCacheEntry, type MobileMoneyFormData, type MobileMoneyNetwork, type PSPConfig, type PSPType, type PaymentDetailResponse, type PaymentError, type PaymentIntent, type PaymentIntentResponse, type PaymentMethod, type PaymentResult, type PaymentSource, ReevitAPIClient, type ReevitAPIClientConfig, type ReevitAPIResult, type ReevitAction, type ReevitCheckoutCallbacks, type ReevitCheckoutConfig, type ReevitState, type ReevitTheme, cacheIntentPromise, cacheIntentResponse, clearIntentCacheEntry, cn, createInitialState, createPaymentError, createReevitClient, createThemeVariables, detectCountryFromCurrency, detectNetwork, formatAmount, formatPhone, generateIdempotencyKey, generateReference, getIntentCacheEntry, isPaymentError, reevitReducer, resolveIntentIdentity, validatePhone };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,10 +10,12 @@ type PaymentSource = 'payment_link' | 'api' | 'subscription';
|
|
|
10
10
|
interface ReevitCheckoutConfig {
|
|
11
11
|
/** Your Reevit public key (required for API-created intents; omit for payment links) */
|
|
12
12
|
publicKey?: string;
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
|
|
13
|
+
/** Server-created checkout session secret. Prefer this for browser checkouts. */
|
|
14
|
+
sessionSecret?: string;
|
|
15
|
+
/** Amount in the smallest currency unit (e.g., pesewas for GHS). Required unless sessionSecret or initialPaymentIntent is provided. */
|
|
16
|
+
amount?: number;
|
|
17
|
+
/** Currency code (e.g., 'GHS', 'NGN', 'USD'). Required unless sessionSecret or initialPaymentIntent is provided. */
|
|
18
|
+
currency?: string;
|
|
17
19
|
/** Customer email address */
|
|
18
20
|
email?: string;
|
|
19
21
|
/** Customer phone number (required for mobile money) */
|
|
@@ -247,6 +249,7 @@ interface PaymentIntentResponse {
|
|
|
247
249
|
provider_ref_id?: string;
|
|
248
250
|
status: string;
|
|
249
251
|
client_secret: string;
|
|
252
|
+
session_secret?: string;
|
|
250
253
|
psp_public_key: string;
|
|
251
254
|
psp_credentials?: {
|
|
252
255
|
merchantAccount?: string | number;
|
|
@@ -267,6 +270,13 @@ interface PaymentIntentResponse {
|
|
|
267
270
|
}>;
|
|
268
271
|
branding?: Record<string, unknown>;
|
|
269
272
|
}
|
|
273
|
+
interface CheckoutSessionResponse {
|
|
274
|
+
id: string;
|
|
275
|
+
client_secret: string;
|
|
276
|
+
session_secret: string;
|
|
277
|
+
payment_intent: PaymentIntentResponse;
|
|
278
|
+
expires_at?: string;
|
|
279
|
+
}
|
|
270
280
|
interface ConfirmPaymentRequest {
|
|
271
281
|
provider_ref_id: string;
|
|
272
282
|
provider_data?: Record<string, unknown>;
|
|
@@ -298,8 +308,15 @@ interface PaymentDetailResponse {
|
|
|
298
308
|
interface APIErrorResponse {
|
|
299
309
|
code: string;
|
|
300
310
|
message: string;
|
|
301
|
-
details?: Record<string,
|
|
311
|
+
details?: Record<string, unknown>;
|
|
302
312
|
}
|
|
313
|
+
type ReevitAPIResult<T> = {
|
|
314
|
+
data: T;
|
|
315
|
+
error?: never;
|
|
316
|
+
} | {
|
|
317
|
+
data?: never;
|
|
318
|
+
error: PaymentError;
|
|
319
|
+
};
|
|
303
320
|
interface ReevitAPIClientConfig {
|
|
304
321
|
/** Your Reevit public key */
|
|
305
322
|
publicKey?: string;
|
|
@@ -308,6 +325,11 @@ interface ReevitAPIClientConfig {
|
|
|
308
325
|
/** Request timeout in milliseconds */
|
|
309
326
|
timeout?: number;
|
|
310
327
|
}
|
|
328
|
+
/**
|
|
329
|
+
* Creates a PaymentError from an API error response
|
|
330
|
+
*/
|
|
331
|
+
declare function createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError;
|
|
332
|
+
declare function isPaymentError(error: unknown): error is PaymentError;
|
|
311
333
|
/**
|
|
312
334
|
* Generates a deterministic idempotency key based on input parameters
|
|
313
335
|
* Uses a simple hash function suitable for browser environments
|
|
@@ -344,6 +366,13 @@ declare class ReevitAPIClient {
|
|
|
344
366
|
data?: PaymentDetailResponse;
|
|
345
367
|
error?: PaymentError;
|
|
346
368
|
}>;
|
|
369
|
+
/**
|
|
370
|
+
* Retrieves a server-created checkout session using its public session secret.
|
|
371
|
+
*/
|
|
372
|
+
getCheckoutSession(sessionSecret: string): Promise<{
|
|
373
|
+
data?: CheckoutSessionResponse;
|
|
374
|
+
error?: PaymentError;
|
|
375
|
+
}>;
|
|
347
376
|
/**
|
|
348
377
|
* Confirms a payment after PSP callback
|
|
349
378
|
*/
|
|
@@ -494,4 +523,4 @@ declare function createInitialState(): ReevitState;
|
|
|
494
523
|
*/
|
|
495
524
|
declare function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState;
|
|
496
525
|
|
|
497
|
-
export { type APIErrorResponse, type CardFormData, type CheckoutProviderOption, type CheckoutState, type ConfirmPaymentRequest, type CreatePaymentIntentRequest, type HubtelSessionResponse, type IntentCacheEntry, type MobileMoneyFormData, type MobileMoneyNetwork, type PSPConfig, type PSPType, type PaymentDetailResponse, type PaymentError, type PaymentIntent, type PaymentIntentResponse, type PaymentMethod, type PaymentResult, type PaymentSource, ReevitAPIClient, type ReevitAPIClientConfig, type ReevitAction, type ReevitCheckoutCallbacks, type ReevitCheckoutConfig, type ReevitState, type ReevitTheme, cacheIntentPromise, cacheIntentResponse, clearIntentCacheEntry, cn, createInitialState, createReevitClient, createThemeVariables, detectCountryFromCurrency, detectNetwork, formatAmount, formatPhone, generateIdempotencyKey, generateReference, getIntentCacheEntry, reevitReducer, resolveIntentIdentity, validatePhone };
|
|
526
|
+
export { type APIErrorResponse, type CardFormData, type CheckoutProviderOption, type CheckoutSessionResponse, type CheckoutState, type ConfirmPaymentRequest, type CreatePaymentIntentRequest, type HubtelSessionResponse, type IntentCacheEntry, type MobileMoneyFormData, type MobileMoneyNetwork, type PSPConfig, type PSPType, type PaymentDetailResponse, type PaymentError, type PaymentIntent, type PaymentIntentResponse, type PaymentMethod, type PaymentResult, type PaymentSource, ReevitAPIClient, type ReevitAPIClientConfig, type ReevitAPIResult, type ReevitAction, type ReevitCheckoutCallbacks, type ReevitCheckoutConfig, type ReevitState, type ReevitTheme, cacheIntentPromise, cacheIntentResponse, clearIntentCacheEntry, cn, createInitialState, createPaymentError, createReevitClient, createThemeVariables, detectCountryFromCurrency, detectNetwork, formatAmount, formatPhone, generateIdempotencyKey, generateReference, getIntentCacheEntry, isPaymentError, reevitReducer, resolveIntentIdentity, validatePhone };
|
package/dist/index.js
CHANGED
|
@@ -26,6 +26,7 @@ __export(index_exports, {
|
|
|
26
26
|
clearIntentCacheEntry: () => clearIntentCacheEntry,
|
|
27
27
|
cn: () => cn,
|
|
28
28
|
createInitialState: () => createInitialState,
|
|
29
|
+
createPaymentError: () => createPaymentError,
|
|
29
30
|
createReevitClient: () => createReevitClient,
|
|
30
31
|
createThemeVariables: () => createThemeVariables,
|
|
31
32
|
detectCountryFromCurrency: () => detectCountryFromCurrency,
|
|
@@ -35,6 +36,7 @@ __export(index_exports, {
|
|
|
35
36
|
generateIdempotencyKey: () => generateIdempotencyKey,
|
|
36
37
|
generateReference: () => generateReference,
|
|
37
38
|
getIntentCacheEntry: () => getIntentCacheEntry,
|
|
39
|
+
isPaymentError: () => isPaymentError,
|
|
38
40
|
reevitReducer: () => reevitReducer,
|
|
39
41
|
resolveIntentIdentity: () => resolveIntentIdentity,
|
|
40
42
|
validatePhone: () => validatePhone
|
|
@@ -44,16 +46,25 @@ module.exports = __toCommonJS(index_exports);
|
|
|
44
46
|
// src/api/client.ts
|
|
45
47
|
var API_BASE_URL_PRODUCTION = "https://api.reevit.io";
|
|
46
48
|
var DEFAULT_TIMEOUT = 3e4;
|
|
49
|
+
var hasWarnedAboutLiveBrowserIntents = false;
|
|
47
50
|
function createPaymentError(response, errorData) {
|
|
48
51
|
return {
|
|
49
52
|
code: errorData.code || "api_error",
|
|
50
53
|
message: errorData.message || "An unexpected error occurred",
|
|
54
|
+
recoverable: isRecoverableStatus(response.status),
|
|
51
55
|
details: {
|
|
52
56
|
httpStatus: response.status,
|
|
57
|
+
requestId: response.headers.get("x-request-id") || response.headers.get("x-reevit-request-id") || void 0,
|
|
53
58
|
...errorData.details
|
|
54
59
|
}
|
|
55
60
|
};
|
|
56
61
|
}
|
|
62
|
+
function isPaymentError(error) {
|
|
63
|
+
return typeof error === "object" && error !== null && "code" in error && "message" in error;
|
|
64
|
+
}
|
|
65
|
+
function isRecoverableStatus(status) {
|
|
66
|
+
return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
|
|
67
|
+
}
|
|
57
68
|
function generateIdempotencyKey(params) {
|
|
58
69
|
const sortedKeys = Object.keys(params).sort();
|
|
59
70
|
const stableString = sortedKeys.map((key) => `${key}:${JSON.stringify(params[key])}`).join("|");
|
|
@@ -82,7 +93,7 @@ var ReevitAPIClient = class {
|
|
|
82
93
|
const headers = {
|
|
83
94
|
"Content-Type": "application/json",
|
|
84
95
|
"X-Reevit-Client": "@reevit/core",
|
|
85
|
-
"X-Reevit-Client-Version": "0.
|
|
96
|
+
"X-Reevit-Client-Version": "0.9.0"
|
|
86
97
|
};
|
|
87
98
|
if (this.publicKey) {
|
|
88
99
|
headers["X-Reevit-Key"] = this.publicKey;
|
|
@@ -112,7 +123,8 @@ var ReevitAPIClient = class {
|
|
|
112
123
|
return {
|
|
113
124
|
error: {
|
|
114
125
|
code: "request_timeout",
|
|
115
|
-
message: "The request timed out. Please try again."
|
|
126
|
+
message: "The request timed out. Please try again.",
|
|
127
|
+
recoverable: true
|
|
116
128
|
}
|
|
117
129
|
};
|
|
118
130
|
}
|
|
@@ -120,7 +132,8 @@ var ReevitAPIClient = class {
|
|
|
120
132
|
return {
|
|
121
133
|
error: {
|
|
122
134
|
code: "network_error",
|
|
123
|
-
message: "Unable to connect to Reevit. Please check your internet connection."
|
|
135
|
+
message: "Unable to connect to Reevit. Please check your internet connection.",
|
|
136
|
+
recoverable: true
|
|
124
137
|
}
|
|
125
138
|
};
|
|
126
139
|
}
|
|
@@ -128,7 +141,8 @@ var ReevitAPIClient = class {
|
|
|
128
141
|
return {
|
|
129
142
|
error: {
|
|
130
143
|
code: "unknown_error",
|
|
131
|
-
message: "An unexpected error occurred. Please try again."
|
|
144
|
+
message: "An unexpected error occurred. Please try again.",
|
|
145
|
+
recoverable: true
|
|
132
146
|
}
|
|
133
147
|
};
|
|
134
148
|
}
|
|
@@ -137,6 +151,21 @@ var ReevitAPIClient = class {
|
|
|
137
151
|
* Creates a payment intent
|
|
138
152
|
*/
|
|
139
153
|
async createPaymentIntent(config, method, country = "GH", options) {
|
|
154
|
+
if (this.publicKey.startsWith("pfk_live_") && !hasWarnedAboutLiveBrowserIntents && typeof console !== "undefined") {
|
|
155
|
+
hasWarnedAboutLiveBrowserIntents = true;
|
|
156
|
+
console.warn(
|
|
157
|
+
"Creating live payment intents from the browser is deprecated. Create a checkout session on your server and pass sessionSecret to the browser SDK instead."
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
if (typeof config.amount !== "number" || !config.currency) {
|
|
161
|
+
return {
|
|
162
|
+
error: {
|
|
163
|
+
code: "invalid_checkout_config",
|
|
164
|
+
message: "amount and currency are required when creating a payment intent in the browser.",
|
|
165
|
+
recoverable: false
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
140
169
|
const metadata = { ...config.metadata };
|
|
141
170
|
if (config.email) {
|
|
142
171
|
metadata.customer_email = config.email;
|
|
@@ -177,6 +206,15 @@ var ReevitAPIClient = class {
|
|
|
177
206
|
async getPaymentIntent(paymentId) {
|
|
178
207
|
return this.request("GET", `/v1/payments/${paymentId}`);
|
|
179
208
|
}
|
|
209
|
+
/**
|
|
210
|
+
* Retrieves a server-created checkout session using its public session secret.
|
|
211
|
+
*/
|
|
212
|
+
async getCheckoutSession(sessionSecret) {
|
|
213
|
+
return this.request(
|
|
214
|
+
"GET",
|
|
215
|
+
`/v1/checkout/sessions/${encodeURIComponent(sessionSecret)}`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
180
218
|
/**
|
|
181
219
|
* Confirms a payment after PSP callback
|
|
182
220
|
*/
|
|
@@ -395,6 +433,12 @@ function setIntentCacheEntryInternal(key, update) {
|
|
|
395
433
|
}
|
|
396
434
|
function buildIdempotencyPayload(options) {
|
|
397
435
|
const { config, method, preferredProvider, allowedProviders, publicKey } = options;
|
|
436
|
+
if (config.sessionSecret) {
|
|
437
|
+
return {
|
|
438
|
+
sessionSecret: config.sessionSecret,
|
|
439
|
+
publicKey: publicKey || config.publicKey || ""
|
|
440
|
+
};
|
|
441
|
+
}
|
|
398
442
|
const payload = {
|
|
399
443
|
amount: config.amount,
|
|
400
444
|
currency: config.currency,
|
|
@@ -484,6 +528,7 @@ function reevitReducer(state, action) {
|
|
|
484
528
|
clearIntentCacheEntry,
|
|
485
529
|
cn,
|
|
486
530
|
createInitialState,
|
|
531
|
+
createPaymentError,
|
|
487
532
|
createReevitClient,
|
|
488
533
|
createThemeVariables,
|
|
489
534
|
detectCountryFromCurrency,
|
|
@@ -493,6 +538,7 @@ function reevitReducer(state, action) {
|
|
|
493
538
|
generateIdempotencyKey,
|
|
494
539
|
generateReference,
|
|
495
540
|
getIntentCacheEntry,
|
|
541
|
+
isPaymentError,
|
|
496
542
|
reevitReducer,
|
|
497
543
|
resolveIntentIdentity,
|
|
498
544
|
validatePhone
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/api/client.ts","../src/utils.ts","../src/intent.ts","../src/state.ts"],"sourcesContent":["/**\n * @reevit/core\n * Shared utilities and API client for Reevit payment SDKs\n */\n\n// API Client\nexport {\n ReevitAPIClient,\n createReevitClient,\n generateIdempotencyKey,\n type ReevitAPIClientConfig,\n type CreatePaymentIntentRequest,\n type PaymentIntentResponse,\n type PaymentDetailResponse,\n type ConfirmPaymentRequest,\n type APIErrorResponse,\n} from './api/client';\n\n// Types\nexport type {\n PaymentMethod,\n MobileMoneyNetwork,\n ReevitCheckoutConfig,\n ReevitCheckoutCallbacks,\n CheckoutState,\n PaymentResult,\n PaymentError,\n ReevitTheme,\n CheckoutProviderOption,\n MobileMoneyFormData,\n CardFormData,\n PaymentIntent,\n PSPConfig,\n PSPType,\n PaymentSource,\n HubtelSessionResponse,\n} from './types';\n\n// Utilities\nexport {\n formatAmount,\n generateReference,\n validatePhone,\n formatPhone,\n detectNetwork,\n detectCountryFromCurrency,\n createThemeVariables,\n cn,\n} from './utils';\n\n// Intent identity + cache helpers\nexport {\n resolveIntentIdentity,\n getIntentCacheEntry,\n cacheIntentPromise,\n cacheIntentResponse,\n clearIntentCacheEntry,\n type IntentCacheEntry,\n} from './intent';\n\n// State machine helpers\nexport {\n createInitialState,\n reevitReducer,\n type ReevitState,\n type ReevitAction,\n} from './state';\n","/**\n * Reevit API Client\n * \n * Handles communication with the Reevit backend for payment operations.\n */\n\nimport type { PaymentMethod, ReevitCheckoutConfig, PaymentError, HubtelSessionResponse } from '../types';\n\n// API Response Types (matching backend handlers_payments.go)\nexport interface CreatePaymentIntentRequest {\n amount: number;\n currency: string;\n method?: string;\n country: string;\n customer_id?: string;\n metadata?: Record<string, unknown>;\n description?: string;\n policy?: {\n prefer?: string[];\n allowed_providers?: string[];\n max_amount?: number;\n blocked_bins?: string[];\n allowed_bins?: string[];\n velocity_max_per_minute?: number;\n };\n}\n\nexport interface PaymentIntentResponse {\n id: string;\n org_id?: string;\n connection_id: string;\n provider: string;\n provider_ref_id?: string;\n status: string;\n client_secret: string;\n psp_public_key: string;\n psp_credentials?: {\n merchantAccount?: string | number;\n basicAuth?: string;\n [key: string]: unknown;\n };\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n reference?: string;\n available_psps?: Array<{\n provider: string;\n name: string;\n methods: string[];\n countries?: string[];\n }>;\n branding?: Record<string, unknown>;\n}\n\nexport interface ConfirmPaymentRequest {\n provider_ref_id: string;\n provider_data?: Record<string, unknown>;\n}\n\nexport interface PaymentDetailResponse {\n id: string;\n connection_id: string;\n provider: string;\n method: string;\n status: string;\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n customer_id?: string;\n client_secret: string;\n provider_ref_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n /** Payment source type (payment_link, api, subscription) */\n source?: 'payment_link' | 'api' | 'subscription';\n /** ID of the source (payment link ID, subscription ID, etc.) */\n source_id?: string;\n /** Human-readable description of the source (e.g., payment link name) */\n source_description?: string;\n}\n\nexport interface APIErrorResponse {\n code: string;\n message: string;\n details?: Record<string, string>;\n}\n\n// API Client configuration\nexport interface ReevitAPIClientConfig {\n /** Your Reevit public key */\n publicKey?: string;\n /** Base URL for the Reevit API (defaults to production) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n// Default API base URLs\nconst API_BASE_URL_PRODUCTION = 'https://api.reevit.io';\nconst DEFAULT_TIMEOUT = 30000; // 30 seconds\n\n/**\n * Determines if a public key is for sandbox mode\n */\nexport function isSandboxKey(publicKey: string): boolean {\n return publicKey.startsWith('pfk_test_');\n}\n\n/**\n * Creates a PaymentError from an API error response\n */\nfunction createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError {\n return {\n code: errorData.code || 'api_error',\n message: errorData.message || 'An unexpected error occurred',\n details: {\n httpStatus: response.status,\n ...errorData.details,\n },\n };\n}\n\n/**\n * Generates a deterministic idempotency key based on input parameters\n * Uses a simple hash function suitable for browser environments\n * Exported for use by SDK hooks (e.g., payment link flows)\n */\nexport function generateIdempotencyKey(params: Record<string, unknown>): string {\n // Create a stable string representation of the parameters\n const sortedKeys = Object.keys(params).sort();\n const stableString = sortedKeys\n .map(key => `${key}:${JSON.stringify(params[key])}`)\n .join('|');\n\n // Simple hash function (djb2 algorithm)\n let hash = 5381;\n for (let i = 0; i < stableString.length; i++) {\n hash = ((hash << 5) + hash) + stableString.charCodeAt(i);\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n // Convert to positive hex string\n const hashHex = (hash >>> 0).toString(16);\n\n // Add a time bucket (5-minute windows) to allow retries within a reasonable window\n // but prevent keys from being reused across completely different sessions\n const timeBucket = Math.floor(Date.now() / (5 * 60 * 1000));\n\n return `reevit_${timeBucket}_${hashHex}`;\n}\n\n/**\n * Reevit API Client\n */\nexport class ReevitAPIClient {\n private readonly publicKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(config: ReevitAPIClientConfig) {\n this.publicKey = config.publicKey || '';\n this.baseUrl = config.baseUrl || API_BASE_URL_PRODUCTION;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Makes an authenticated API request\n * @param idempotencyKey Optional deterministic idempotency key for the request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: unknown,\n idempotencyKey?: string\n ): Promise<{ data?: T; error?: PaymentError }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Generate headers with idempotency key for mutating requests\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Reevit-Client': '@reevit/core',\n 'X-Reevit-Client-Version': '0.8.1',\n };\n if (this.publicKey) {\n headers['X-Reevit-Key'] = this.publicKey;\n }\n\n if (method === 'POST' || method === 'PATCH' || method === 'PUT') {\n // Use provided deterministic key, or generate one based on request body\n headers['Idempotency-Key'] = idempotencyKey ||\n (body ? generateIdempotencyKey(body as Record<string, unknown>) : `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`);\n }\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const responseData = await response.json().catch(() => ({}));\n\n if (!response.ok) {\n return {\n error: createPaymentError(response, responseData as APIErrorResponse),\n };\n }\n\n return { data: responseData as T };\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return {\n error: {\n code: 'request_timeout',\n message: 'The request timed out. Please try again.',\n },\n };\n }\n\n if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {\n return {\n error: {\n code: 'network_error',\n message: 'Unable to connect to Reevit. Please check your internet connection.',\n },\n };\n }\n }\n\n return {\n error: {\n code: 'unknown_error',\n message: 'An unexpected error occurred. Please try again.',\n },\n };\n }\n }\n\n /**\n * Creates a payment intent\n */\n async createPaymentIntent(\n config: ReevitCheckoutConfig,\n method?: PaymentMethod,\n country: string = 'GH',\n options?: { preferredProviders?: string[]; allowedProviders?: string[] }\n ): Promise<{ data?: PaymentIntentResponse; error?: PaymentError }> {\n // Build metadata with customer_email for PSP providers that require it\n const metadata: Record<string, unknown> = { ...config.metadata };\n if (config.email) {\n metadata.customer_email = config.email;\n }\n if (config.phone) {\n metadata.customer_phone = config.phone;\n }\n\n const request: CreatePaymentIntentRequest = {\n amount: config.amount,\n currency: config.currency,\n country,\n customer_id: config.email || (config.metadata?.customerId as string | undefined),\n metadata,\n };\n\n if (method) {\n request.method = this.mapPaymentMethod(method);\n }\n\n if (options?.preferredProviders?.length || options?.allowedProviders?.length) {\n request.policy = {\n prefer: options?.preferredProviders,\n allowed_providers: options?.allowedProviders,\n };\n }\n\n // Generate a deterministic idempotency key based on payment parameters\n // This ensures that duplicate requests for the same payment return the same intent\n const idempotencyKey = config.idempotencyKey || generateIdempotencyKey({\n amount: config.amount,\n currency: config.currency,\n customer: config.email || config.metadata?.customerId || '',\n reference: config.reference || '',\n method: method || '',\n provider: options?.preferredProviders?.[0] || options?.allowedProviders?.[0] || '',\n publicKey: this.publicKey,\n });\n\n return this.request<PaymentIntentResponse>('POST', '/v1/payments/intents', request, idempotencyKey);\n }\n\n /**\n * Retrieves a payment intent by ID\n */\n async getPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('GET', `/v1/payments/${paymentId}`);\n }\n\n /**\n * Confirms a payment after PSP callback\n */\n async confirmPayment(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/confirm`);\n }\n\n /**\n * Confirms a payment intent using client secret (public endpoint)\n */\n async confirmPaymentIntent(paymentId: string, clientSecret: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>(\n 'POST',\n `/v1/payments/${paymentId}/confirm-intent?client_secret=${encodeURIComponent(clientSecret)}`\n );\n }\n\n /**\n * Cancels a payment intent\n */\n async cancelPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/cancel`);\n }\n\n /**\n * Creates a Hubtel session token for secure checkout\n * Returns a short-lived token that contains Hubtel credentials\n * Credentials are never exposed to the client directly\n */\n async createHubtelSession(\n paymentId: string,\n clientSecret?: string\n ): Promise<{ data?: HubtelSessionResponse; error?: PaymentError }> {\n const query = clientSecret ? `?client_secret=${encodeURIComponent(clientSecret)}` : '';\n return this.request<HubtelSessionResponse>('POST', `/v1/payments/hubtel/sessions/${paymentId}${query}`);\n }\n\n /**\n * Maps SDK payment method to backend format\n */\n private mapPaymentMethod(method: PaymentMethod): string {\n switch (method) {\n case 'card':\n return 'card';\n case 'mobile_money':\n return 'mobile_money';\n case 'bank_transfer':\n return 'bank_transfer';\n default:\n return method;\n }\n }\n}\n\n/**\n * Creates a new Reevit API client instance\n */\nexport function createReevitClient(config: ReevitAPIClientConfig): ReevitAPIClient {\n return new ReevitAPIClient(config);\n}\n","/**\n * Utility Functions\n * Shared utilities for Reevit SDKs\n */\n\nimport type { MobileMoneyNetwork, ReevitTheme } from './types';\n\n/**\n * Formats an amount from smallest currency unit to display format\n */\nexport function formatAmount(amount: number, currency: string): string {\n const majorUnit = amount / 100;\n\n const currencyFormats: Record<string, { locale: string; minimumFractionDigits: number }> = {\n GHS: { locale: 'en-GH', minimumFractionDigits: 2 },\n NGN: { locale: 'en-NG', minimumFractionDigits: 2 },\n KES: { locale: 'en-KE', minimumFractionDigits: 2 },\n USD: { locale: 'en-US', minimumFractionDigits: 2 },\n EUR: { locale: 'de-DE', minimumFractionDigits: 2 },\n GBP: { locale: 'en-GB', minimumFractionDigits: 2 },\n };\n\n const format = currencyFormats[currency.toUpperCase()] || { locale: 'en-US', minimumFractionDigits: 2 };\n\n try {\n return new Intl.NumberFormat(format.locale, {\n style: 'currency',\n currency: currency.toUpperCase(),\n minimumFractionDigits: format.minimumFractionDigits,\n }).format(majorUnit);\n } catch {\n // Fallback for unsupported currencies\n return `${currency} ${majorUnit.toFixed(2)}`;\n }\n}\n\n/**\n * Generates a unique payment reference\n */\nexport function generateReference(prefix: string = 'reevit'): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${prefix}_${timestamp}_${random}`;\n}\n\n/**\n * Validates a phone number for mobile money\n */\nexport function validatePhone(phone: string, country: string = 'GH'): boolean {\n // Remove non-digit characters\n const digits = phone.replace(/\\D/g, '');\n\n const patterns: Record<string, RegExp> = {\n GH: /^(?:233|0)?[235][0-9]{8}$/, // Ghana\n NG: /^(?:234|0)?[789][01][0-9]{8}$/, // Nigeria\n KE: /^(?:254|0)?[17][0-9]{8}$/, // Kenya\n };\n\n const pattern = patterns[country.toUpperCase()];\n if (!pattern) return digits.length >= 10;\n\n return pattern.test(digits);\n}\n\n/**\n * Formats a phone number for display\n */\nexport function formatPhone(phone: string, country: string = 'GH'): string {\n const digits = phone.replace(/\\D/g, '');\n\n if (country === 'GH') {\n // Format as 0XX XXX XXXX\n if (digits.startsWith('233') && digits.length === 12) {\n const local = '0' + digits.slice(3);\n return `${local.slice(0, 3)} ${local.slice(3, 6)} ${local.slice(6)}`;\n }\n if (digits.length === 10 && digits.startsWith('0')) {\n return `${digits.slice(0, 3)} ${digits.slice(3, 6)} ${digits.slice(6)}`;\n }\n }\n\n return phone;\n}\n\n/**\n * Detects mobile money network from phone number (Ghana)\n */\nexport function detectNetwork(phone: string): MobileMoneyNetwork | null {\n const digits = phone.replace(/\\D/g, '');\n\n // Get the network prefix (first 3 digits after country code or 0)\n let prefix: string;\n if (digits.startsWith('233')) {\n prefix = digits.slice(3, 5);\n } else if (digits.startsWith('0')) {\n prefix = digits.slice(1, 3);\n } else {\n prefix = digits.slice(0, 2);\n }\n\n // Ghana network prefixes\n const mtnPrefixes = ['24', '25', '53', '54', '55', '59'];\n const telecelPrefixes = ['20', '50'];\n const airteltigoPrefixes = ['26', '27', '56', '57'];\n\n if (mtnPrefixes.includes(prefix)) return 'mtn';\n if (telecelPrefixes.includes(prefix)) return 'telecel';\n if (airteltigoPrefixes.includes(prefix)) return 'airteltigo';\n\n return null;\n}\n\n/**\n * Creates CSS custom property variables from theme\n */\nexport function createThemeVariables(theme: ReevitTheme): Record<string, string> {\n const variables: Record<string, string> = {};\n\n // Primary color = main text color\n if (theme.primaryColor) {\n variables['--reevit-text'] = theme.primaryColor;\n }\n\n // Primary foreground = description/secondary text color\n if (theme.primaryForegroundColor) {\n variables['--reevit-text-secondary'] = theme.primaryForegroundColor;\n variables['--reevit-muted'] = theme.primaryForegroundColor;\n }\n\n // Button colors\n if (theme.buttonBackgroundColor) {\n variables['--reevit-primary'] = theme.buttonBackgroundColor;\n variables['--reevit-primary-hover'] = theme.buttonBackgroundColor;\n }\n if (theme.buttonTextColor) {\n variables['--reevit-primary-foreground'] = theme.buttonTextColor;\n }\n\n // Background and surface colors\n if (theme.backgroundColor) {\n variables['--reevit-background'] = theme.backgroundColor;\n variables['--reevit-surface'] = theme.backgroundColor;\n }\n if (theme.surfaceColor) {\n variables['--reevit-surface'] = theme.surfaceColor;\n }\n\n // Border color\n if (theme.borderColor) {\n variables['--reevit-border'] = theme.borderColor;\n }\n\n // Legacy text color support\n if (theme.textColor) {\n variables['--reevit-text'] = theme.textColor;\n }\n if (theme.mutedTextColor) {\n variables['--reevit-text-secondary'] = theme.mutedTextColor;\n }\n\n // Border radius\n if (theme.borderRadius) {\n variables['--reevit-radius'] = theme.borderRadius;\n variables['--reevit-radius-sm'] = theme.borderRadius;\n variables['--reevit-radius-lg'] = theme.borderRadius;\n }\n\n // Font family\n if (theme.fontFamily) {\n variables['--reevit-font'] = theme.fontFamily;\n }\n\n return variables;\n}\n\nfunction getContrastingColor(color: string): string | null {\n const hex = color.trim();\n if (!hex.startsWith('#')) {\n return null;\n }\n\n const normalized = hex.length === 4\n ? `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`\n : hex;\n\n if (normalized.length !== 7) {\n return null;\n }\n\n const r = parseInt(normalized.slice(1, 3), 16);\n const g = parseInt(normalized.slice(3, 5), 16);\n const b = parseInt(normalized.slice(5, 7), 16);\n\n if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n return null;\n }\n\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 140 ? '#0b1120' : '#ffffff';\n}\n\n/**\n * Simple class name concatenation utility\n */\nexport function cn(...classes: (string | boolean | undefined | null)[]): string {\n return classes.filter(Boolean).join(' ');\n}\n\n/**\n * Detects country code from currency\n */\nexport function detectCountryFromCurrency(currency: string): string {\n const currencyToCountry: Record<string, string> = {\n GHS: 'GH',\n NGN: 'NG',\n KES: 'KE',\n UGX: 'UG',\n TZS: 'TZ',\n ZAR: 'ZA',\n XOF: 'CI',\n XAF: 'CM',\n USD: 'US',\n EUR: 'DE',\n GBP: 'GB',\n };\n\n return currencyToCountry[currency.toUpperCase()] || 'GH';\n}\n","/**\n * Intent identity + cache helpers\n */\n\nimport type { PaymentIntentResponse } from './api/client';\nimport { generateIdempotencyKey } from './api/client';\nimport type { PaymentMethod, ReevitCheckoutConfig } from './types';\nimport { generateReference } from './utils';\n\nconst INTENT_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface IntentIdentityOptions {\n config: ReevitCheckoutConfig;\n method?: PaymentMethod;\n preferredProvider?: string;\n allowedProviders?: string[];\n publicKey?: string;\n}\n\nexport interface IntentCacheEntry {\n promise?: Promise<PaymentIntentResponse>;\n response?: PaymentIntentResponse;\n expiresAt: number;\n reference?: string;\n}\n\nconst intentCache = new Map<string, IntentCacheEntry>();\n\nfunction pruneIntentCache(now: number = Date.now()): void {\n for (const [key, entry] of intentCache) {\n if (entry.expiresAt <= now) {\n intentCache.delete(key);\n }\n }\n}\n\nfunction getIntentCacheEntryInternal(key: string): IntentCacheEntry | undefined {\n const entry = intentCache.get(key);\n if (!entry) {\n return undefined;\n }\n if (entry.expiresAt <= Date.now()) {\n intentCache.delete(key);\n return undefined;\n }\n return entry;\n}\n\nfunction setIntentCacheEntryInternal(key: string, update: Partial<IntentCacheEntry>): IntentCacheEntry {\n const now = Date.now();\n const existing = getIntentCacheEntryInternal(key);\n const next: IntentCacheEntry = {\n ...existing,\n ...update,\n expiresAt: now + INTENT_CACHE_TTL_MS,\n };\n intentCache.set(key, next);\n return next;\n}\n\nfunction buildIdempotencyPayload(options: IntentIdentityOptions): Record<string, unknown> {\n const { config, method, preferredProvider, allowedProviders, publicKey } = options;\n const payload: Record<string, unknown> = {\n amount: config.amount,\n currency: config.currency,\n email: config.email || '',\n phone: config.phone || '',\n customerName: config.customerName || '',\n paymentLinkCode: config.paymentLinkCode || '',\n paymentMethods: config.paymentMethods || [],\n metadata: config.metadata || {},\n customFields: config.customFields || {},\n method: method || '',\n preferredProvider: preferredProvider || '',\n allowedProviders: allowedProviders || [],\n publicKey: publicKey || config.publicKey || '',\n };\n\n if (config.reference) {\n payload.reference = config.reference;\n }\n\n return payload;\n}\n\nexport function resolveIntentIdentity(options: IntentIdentityOptions): {\n idempotencyKey: string;\n reference: string;\n cacheEntry?: IntentCacheEntry;\n} {\n pruneIntentCache();\n\n const idempotencyKey =\n options.config.idempotencyKey || generateIdempotencyKey(buildIdempotencyPayload(options));\n const existing = getIntentCacheEntryInternal(idempotencyKey);\n const reference = options.config.reference || existing?.reference || generateReference();\n\n const cacheEntry = setIntentCacheEntryInternal(idempotencyKey, { reference });\n\n return { idempotencyKey, reference, cacheEntry };\n}\n\nexport function getIntentCacheEntry(idempotencyKey: string): IntentCacheEntry | undefined {\n pruneIntentCache();\n return getIntentCacheEntryInternal(idempotencyKey);\n}\n\nexport function cacheIntentPromise(\n idempotencyKey: string,\n promise: Promise<PaymentIntentResponse>\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { promise });\n}\n\nexport function cacheIntentResponse(\n idempotencyKey: string,\n response: PaymentIntentResponse\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { response, promise: undefined });\n}\n\nexport function clearIntentCacheEntry(idempotencyKey: string): void {\n intentCache.delete(idempotencyKey);\n}\n","/**\n * Reevit State Machine\n * Shared state management logic for all SDKs\n */\n\nimport type { CheckoutState, PaymentIntent, PaymentMethod, PaymentResult, PaymentError } from './types';\n\n// State shape\nexport interface ReevitState {\n status: CheckoutState;\n paymentIntent: PaymentIntent | null;\n selectedMethod: PaymentMethod | null;\n error: PaymentError | null;\n result: PaymentResult | null;\n}\n\n// Actions\nexport type ReevitAction =\n | { type: 'INIT_START' }\n | { type: 'INIT_SUCCESS'; payload: PaymentIntent }\n | { type: 'INIT_ERROR'; payload: PaymentError }\n | { type: 'SELECT_METHOD'; payload: PaymentMethod }\n | { type: 'PROCESS_START' }\n | { type: 'PROCESS_SUCCESS'; payload: PaymentResult }\n | { type: 'PROCESS_ERROR'; payload: PaymentError }\n | { type: 'RESET' }\n | { type: 'CLOSE' };\n\n/**\n * Creates the initial state for the checkout\n */\nexport function createInitialState(): ReevitState {\n return {\n status: 'idle',\n paymentIntent: null,\n selectedMethod: null,\n error: null,\n result: null,\n };\n}\n\n/**\n * State reducer for checkout flow\n */\nexport function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState {\n switch (action.type) {\n case 'INIT_START':\n return { ...state, status: 'loading', error: null };\n case 'INIT_SUCCESS':\n return {\n ...state,\n status: 'ready',\n paymentIntent: action.payload,\n selectedMethod:\n action.payload.availableMethods?.length === 1 ? action.payload.availableMethods[0] : null,\n };\n case 'INIT_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'SELECT_METHOD':\n return { ...state, status: 'method_selected', selectedMethod: action.payload };\n case 'PROCESS_START':\n return { ...state, status: 'processing', error: null };\n case 'PROCESS_SUCCESS':\n return { ...state, status: 'success', result: action.payload };\n case 'PROCESS_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'RESET':\n return { ...createInitialState(), status: 'ready', paymentIntent: state.paymentIntent };\n case 'CLOSE':\n return { ...state, status: 'closed' };\n default:\n return state;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuGA,IAAM,0BAA0B;AAChC,IAAM,kBAAkB;AAYxB,SAAS,mBAAmB,UAAoB,WAA2C;AACzF,SAAO;AAAA,IACL,MAAM,UAAU,QAAQ;AAAA,IACxB,SAAS,UAAU,WAAW;AAAA,IAC9B,SAAS;AAAA,MACP,YAAY,SAAS;AAAA,MACrB,GAAG,UAAU;AAAA,IACf;AAAA,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ACf,gBAAgB;AAAA,IAChB,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAKO,SAAS,cAAc,OAAoB,QAAmC;AACnF,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,WAAW,OAAO,KAAK;AAAA,IACpD,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,QAAQ;AAAA,QACR,eAAe,OAAO;AAAA,QACtB,gBACE,OAAO,QAAQ,kBAAkB,WAAW,IAAI,OAAO,QAAQ,iBAAiB,CAAC,IAAI;AAAA,MACzF;AAAA,IACF,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,UAAU,OAAO,OAAO,QAAQ;AAAA,IAC7D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,mBAAmB,gBAAgB,OAAO,QAAQ;AAAA,IAC/E,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,cAAc,OAAO,KAAK;AAAA,IACvD,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,WAAW,QAAQ,OAAO,QAAQ;AAAA,IAC/D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,UAAU,OAAO,OAAO,QAAQ;AAAA,IAC7D,KAAK;AACH,aAAO,EAAE,GAAG,mBAAmB,GAAG,QAAQ,SAAS,eAAe,MAAM,cAAc;AAAA,IACxF,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,SAAS;AAAA,IACtC;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/api/client.ts","../src/utils.ts","../src/intent.ts","../src/state.ts"],"sourcesContent":["/**\n * @reevit/core\n * Shared utilities and API client for Reevit payment SDKs\n */\n\n// API Client\nexport {\n ReevitAPIClient,\n createReevitClient,\n createPaymentError,\n generateIdempotencyKey,\n isPaymentError,\n type ReevitAPIClientConfig,\n type CreatePaymentIntentRequest,\n type PaymentIntentResponse,\n type CheckoutSessionResponse,\n type PaymentDetailResponse,\n type ConfirmPaymentRequest,\n type APIErrorResponse,\n type ReevitAPIResult,\n} from './api/client';\n\n// Types\nexport type {\n PaymentMethod,\n MobileMoneyNetwork,\n ReevitCheckoutConfig,\n ReevitCheckoutCallbacks,\n CheckoutState,\n PaymentResult,\n PaymentError,\n ReevitTheme,\n CheckoutProviderOption,\n MobileMoneyFormData,\n CardFormData,\n PaymentIntent,\n PSPConfig,\n PSPType,\n PaymentSource,\n HubtelSessionResponse,\n} from './types';\n\n// Utilities\nexport {\n formatAmount,\n generateReference,\n validatePhone,\n formatPhone,\n detectNetwork,\n detectCountryFromCurrency,\n createThemeVariables,\n cn,\n} from './utils';\n\n// Intent identity + cache helpers\nexport {\n resolveIntentIdentity,\n getIntentCacheEntry,\n cacheIntentPromise,\n cacheIntentResponse,\n clearIntentCacheEntry,\n type IntentCacheEntry,\n} from './intent';\n\n// State machine helpers\nexport {\n createInitialState,\n reevitReducer,\n type ReevitState,\n type ReevitAction,\n} from './state';\n","/**\n * Reevit API Client\n * \n * Handles communication with the Reevit backend for payment operations.\n */\n\nimport type { PaymentMethod, ReevitCheckoutConfig, PaymentError, HubtelSessionResponse } from '../types';\n\n// API Response Types (matching backend handlers_payments.go)\nexport interface CreatePaymentIntentRequest {\n amount: number;\n currency: string;\n method?: string;\n country: string;\n customer_id?: string;\n metadata?: Record<string, unknown>;\n description?: string;\n policy?: {\n prefer?: string[];\n allowed_providers?: string[];\n max_amount?: number;\n blocked_bins?: string[];\n allowed_bins?: string[];\n velocity_max_per_minute?: number;\n };\n}\n\nexport interface PaymentIntentResponse {\n id: string;\n org_id?: string;\n connection_id: string;\n provider: string;\n provider_ref_id?: string;\n status: string;\n client_secret: string;\n session_secret?: string;\n psp_public_key: string;\n psp_credentials?: {\n merchantAccount?: string | number;\n basicAuth?: string;\n [key: string]: unknown;\n };\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n reference?: string;\n available_psps?: Array<{\n provider: string;\n name: string;\n methods: string[];\n countries?: string[];\n }>;\n branding?: Record<string, unknown>;\n}\n\nexport interface CheckoutSessionResponse {\n id: string;\n client_secret: string;\n session_secret: string;\n payment_intent: PaymentIntentResponse;\n expires_at?: string;\n}\n\nexport interface ConfirmPaymentRequest {\n provider_ref_id: string;\n provider_data?: Record<string, unknown>;\n}\n\nexport interface PaymentDetailResponse {\n id: string;\n connection_id: string;\n provider: string;\n method: string;\n status: string;\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n customer_id?: string;\n client_secret: string;\n provider_ref_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n /** Payment source type (payment_link, api, subscription) */\n source?: 'payment_link' | 'api' | 'subscription';\n /** ID of the source (payment link ID, subscription ID, etc.) */\n source_id?: string;\n /** Human-readable description of the source (e.g., payment link name) */\n source_description?: string;\n}\n\nexport interface APIErrorResponse {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\nexport type ReevitAPIResult<T> = { data: T; error?: never } | { data?: never; error: PaymentError };\n\n// API Client configuration\nexport interface ReevitAPIClientConfig {\n /** Your Reevit public key */\n publicKey?: string;\n /** Base URL for the Reevit API (defaults to production) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n// Default API base URLs\nconst API_BASE_URL_PRODUCTION = 'https://api.reevit.io';\nconst DEFAULT_TIMEOUT = 30000; // 30 seconds\nlet hasWarnedAboutLiveBrowserIntents = false;\n\n/**\n * Determines if a public key is for sandbox mode\n */\nexport function isSandboxKey(publicKey: string): boolean {\n return publicKey.startsWith('pfk_test_');\n}\n\n/**\n * Creates a PaymentError from an API error response\n */\nexport function createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError {\n return {\n code: errorData.code || 'api_error',\n message: errorData.message || 'An unexpected error occurred',\n recoverable: isRecoverableStatus(response.status),\n details: {\n httpStatus: response.status,\n requestId: response.headers.get('x-request-id') || response.headers.get('x-reevit-request-id') || undefined,\n ...errorData.details,\n },\n };\n}\n\nexport function isPaymentError(error: unknown): error is PaymentError {\n return typeof error === 'object' && error !== null && 'code' in error && 'message' in error;\n}\n\nfunction isRecoverableStatus(status: number): boolean {\n return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;\n}\n\n/**\n * Generates a deterministic idempotency key based on input parameters\n * Uses a simple hash function suitable for browser environments\n * Exported for use by SDK hooks (e.g., payment link flows)\n */\nexport function generateIdempotencyKey(params: Record<string, unknown>): string {\n // Create a stable string representation of the parameters\n const sortedKeys = Object.keys(params).sort();\n const stableString = sortedKeys\n .map(key => `${key}:${JSON.stringify(params[key])}`)\n .join('|');\n\n // Simple hash function (djb2 algorithm)\n let hash = 5381;\n for (let i = 0; i < stableString.length; i++) {\n hash = ((hash << 5) + hash) + stableString.charCodeAt(i);\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n // Convert to positive hex string\n const hashHex = (hash >>> 0).toString(16);\n\n // Add a time bucket (5-minute windows) to allow retries within a reasonable window\n // but prevent keys from being reused across completely different sessions\n const timeBucket = Math.floor(Date.now() / (5 * 60 * 1000));\n\n return `reevit_${timeBucket}_${hashHex}`;\n}\n\n/**\n * Reevit API Client\n */\nexport class ReevitAPIClient {\n private readonly publicKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(config: ReevitAPIClientConfig) {\n this.publicKey = config.publicKey || '';\n this.baseUrl = config.baseUrl || API_BASE_URL_PRODUCTION;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Makes an authenticated API request\n * @param idempotencyKey Optional deterministic idempotency key for the request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: unknown,\n idempotencyKey?: string\n ): Promise<ReevitAPIResult<T>> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Generate headers with idempotency key for mutating requests\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Reevit-Client': '@reevit/core',\n 'X-Reevit-Client-Version': '0.9.0',\n };\n if (this.publicKey) {\n headers['X-Reevit-Key'] = this.publicKey;\n }\n\n if (method === 'POST' || method === 'PATCH' || method === 'PUT') {\n // Use provided deterministic key, or generate one based on request body\n headers['Idempotency-Key'] = idempotencyKey ||\n (body ? generateIdempotencyKey(body as Record<string, unknown>) : `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`);\n }\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const responseData = await response.json().catch(() => ({}));\n\n if (!response.ok) {\n return {\n error: createPaymentError(response, responseData as APIErrorResponse),\n };\n }\n\n return { data: responseData as T };\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return {\n error: {\n code: 'request_timeout',\n message: 'The request timed out. Please try again.',\n recoverable: true,\n },\n };\n }\n\n if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {\n return {\n error: {\n code: 'network_error',\n message: 'Unable to connect to Reevit. Please check your internet connection.',\n recoverable: true,\n },\n };\n }\n }\n\n return {\n error: {\n code: 'unknown_error',\n message: 'An unexpected error occurred. Please try again.',\n recoverable: true,\n },\n };\n }\n }\n\n /**\n * Creates a payment intent\n */\n async createPaymentIntent(\n config: ReevitCheckoutConfig,\n method?: PaymentMethod,\n country: string = 'GH',\n options?: { preferredProviders?: string[]; allowedProviders?: string[] }\n ): Promise<{ data?: PaymentIntentResponse; error?: PaymentError }> {\n if (\n this.publicKey.startsWith('pfk_live_') &&\n !hasWarnedAboutLiveBrowserIntents &&\n typeof console !== 'undefined'\n ) {\n hasWarnedAboutLiveBrowserIntents = true;\n console.warn(\n 'Creating live payment intents from the browser is deprecated. Create a checkout session on your server and pass sessionSecret to the browser SDK instead.'\n );\n }\n\n if (typeof config.amount !== 'number' || !config.currency) {\n return {\n error: {\n code: 'invalid_checkout_config',\n message: 'amount and currency are required when creating a payment intent in the browser.',\n recoverable: false,\n },\n };\n }\n\n // Build metadata with customer_email for PSP providers that require it\n const metadata: Record<string, unknown> = { ...config.metadata };\n if (config.email) {\n metadata.customer_email = config.email;\n }\n if (config.phone) {\n metadata.customer_phone = config.phone;\n }\n\n const request: CreatePaymentIntentRequest = {\n amount: config.amount,\n currency: config.currency,\n country,\n customer_id: config.email || (config.metadata?.customerId as string | undefined),\n metadata,\n };\n\n if (method) {\n request.method = this.mapPaymentMethod(method);\n }\n\n if (options?.preferredProviders?.length || options?.allowedProviders?.length) {\n request.policy = {\n prefer: options?.preferredProviders,\n allowed_providers: options?.allowedProviders,\n };\n }\n\n // Generate a deterministic idempotency key based on payment parameters\n // This ensures that duplicate requests for the same payment return the same intent\n const idempotencyKey = config.idempotencyKey || generateIdempotencyKey({\n amount: config.amount,\n currency: config.currency,\n customer: config.email || config.metadata?.customerId || '',\n reference: config.reference || '',\n method: method || '',\n provider: options?.preferredProviders?.[0] || options?.allowedProviders?.[0] || '',\n publicKey: this.publicKey,\n });\n\n return this.request<PaymentIntentResponse>('POST', '/v1/payments/intents', request, idempotencyKey);\n }\n\n /**\n * Retrieves a payment intent by ID\n */\n async getPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('GET', `/v1/payments/${paymentId}`);\n }\n\n /**\n * Retrieves a server-created checkout session using its public session secret.\n */\n async getCheckoutSession(sessionSecret: string): Promise<{ data?: CheckoutSessionResponse; error?: PaymentError }> {\n return this.request<CheckoutSessionResponse>(\n 'GET',\n `/v1/checkout/sessions/${encodeURIComponent(sessionSecret)}`\n );\n }\n\n /**\n * Confirms a payment after PSP callback\n */\n async confirmPayment(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/confirm`);\n }\n\n /**\n * Confirms a payment intent using client secret (public endpoint)\n */\n async confirmPaymentIntent(paymentId: string, clientSecret: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>(\n 'POST',\n `/v1/payments/${paymentId}/confirm-intent?client_secret=${encodeURIComponent(clientSecret)}`\n );\n }\n\n /**\n * Cancels a payment intent\n */\n async cancelPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/cancel`);\n }\n\n /**\n * Creates a Hubtel session token for secure checkout\n * Returns a short-lived token that contains Hubtel credentials\n * Credentials are never exposed to the client directly\n */\n async createHubtelSession(\n paymentId: string,\n clientSecret?: string\n ): Promise<{ data?: HubtelSessionResponse; error?: PaymentError }> {\n const query = clientSecret ? `?client_secret=${encodeURIComponent(clientSecret)}` : '';\n return this.request<HubtelSessionResponse>('POST', `/v1/payments/hubtel/sessions/${paymentId}${query}`);\n }\n\n /**\n * Maps SDK payment method to backend format\n */\n private mapPaymentMethod(method: PaymentMethod): string {\n switch (method) {\n case 'card':\n return 'card';\n case 'mobile_money':\n return 'mobile_money';\n case 'bank_transfer':\n return 'bank_transfer';\n default:\n return method;\n }\n }\n}\n\n/**\n * Creates a new Reevit API client instance\n */\nexport function createReevitClient(config: ReevitAPIClientConfig): ReevitAPIClient {\n return new ReevitAPIClient(config);\n}\n","/**\n * Utility Functions\n * Shared utilities for Reevit SDKs\n */\n\nimport type { MobileMoneyNetwork, ReevitTheme } from './types';\n\n/**\n * Formats an amount from smallest currency unit to display format\n */\nexport function formatAmount(amount: number, currency: string): string {\n const majorUnit = amount / 100;\n\n const currencyFormats: Record<string, { locale: string; minimumFractionDigits: number }> = {\n GHS: { locale: 'en-GH', minimumFractionDigits: 2 },\n NGN: { locale: 'en-NG', minimumFractionDigits: 2 },\n KES: { locale: 'en-KE', minimumFractionDigits: 2 },\n USD: { locale: 'en-US', minimumFractionDigits: 2 },\n EUR: { locale: 'de-DE', minimumFractionDigits: 2 },\n GBP: { locale: 'en-GB', minimumFractionDigits: 2 },\n };\n\n const format = currencyFormats[currency.toUpperCase()] || { locale: 'en-US', minimumFractionDigits: 2 };\n\n try {\n return new Intl.NumberFormat(format.locale, {\n style: 'currency',\n currency: currency.toUpperCase(),\n minimumFractionDigits: format.minimumFractionDigits,\n }).format(majorUnit);\n } catch {\n // Fallback for unsupported currencies\n return `${currency} ${majorUnit.toFixed(2)}`;\n }\n}\n\n/**\n * Generates a unique payment reference\n */\nexport function generateReference(prefix: string = 'reevit'): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${prefix}_${timestamp}_${random}`;\n}\n\n/**\n * Validates a phone number for mobile money\n */\nexport function validatePhone(phone: string, country: string = 'GH'): boolean {\n // Remove non-digit characters\n const digits = phone.replace(/\\D/g, '');\n\n const patterns: Record<string, RegExp> = {\n GH: /^(?:233|0)?[235][0-9]{8}$/, // Ghana\n NG: /^(?:234|0)?[789][01][0-9]{8}$/, // Nigeria\n KE: /^(?:254|0)?[17][0-9]{8}$/, // Kenya\n };\n\n const pattern = patterns[country.toUpperCase()];\n if (!pattern) return digits.length >= 10;\n\n return pattern.test(digits);\n}\n\n/**\n * Formats a phone number for display\n */\nexport function formatPhone(phone: string, country: string = 'GH'): string {\n const digits = phone.replace(/\\D/g, '');\n\n if (country === 'GH') {\n // Format as 0XX XXX XXXX\n if (digits.startsWith('233') && digits.length === 12) {\n const local = '0' + digits.slice(3);\n return `${local.slice(0, 3)} ${local.slice(3, 6)} ${local.slice(6)}`;\n }\n if (digits.length === 10 && digits.startsWith('0')) {\n return `${digits.slice(0, 3)} ${digits.slice(3, 6)} ${digits.slice(6)}`;\n }\n }\n\n return phone;\n}\n\n/**\n * Detects mobile money network from phone number (Ghana)\n */\nexport function detectNetwork(phone: string): MobileMoneyNetwork | null {\n const digits = phone.replace(/\\D/g, '');\n\n // Get the network prefix (first 3 digits after country code or 0)\n let prefix: string;\n if (digits.startsWith('233')) {\n prefix = digits.slice(3, 5);\n } else if (digits.startsWith('0')) {\n prefix = digits.slice(1, 3);\n } else {\n prefix = digits.slice(0, 2);\n }\n\n // Ghana network prefixes\n const mtnPrefixes = ['24', '25', '53', '54', '55', '59'];\n const telecelPrefixes = ['20', '50'];\n const airteltigoPrefixes = ['26', '27', '56', '57'];\n\n if (mtnPrefixes.includes(prefix)) return 'mtn';\n if (telecelPrefixes.includes(prefix)) return 'telecel';\n if (airteltigoPrefixes.includes(prefix)) return 'airteltigo';\n\n return null;\n}\n\n/**\n * Creates CSS custom property variables from theme\n */\nexport function createThemeVariables(theme: ReevitTheme): Record<string, string> {\n const variables: Record<string, string> = {};\n\n // Primary color = main text color\n if (theme.primaryColor) {\n variables['--reevit-text'] = theme.primaryColor;\n }\n\n // Primary foreground = description/secondary text color\n if (theme.primaryForegroundColor) {\n variables['--reevit-text-secondary'] = theme.primaryForegroundColor;\n variables['--reevit-muted'] = theme.primaryForegroundColor;\n }\n\n // Button colors\n if (theme.buttonBackgroundColor) {\n variables['--reevit-primary'] = theme.buttonBackgroundColor;\n variables['--reevit-primary-hover'] = theme.buttonBackgroundColor;\n }\n if (theme.buttonTextColor) {\n variables['--reevit-primary-foreground'] = theme.buttonTextColor;\n }\n\n // Background and surface colors\n if (theme.backgroundColor) {\n variables['--reevit-background'] = theme.backgroundColor;\n variables['--reevit-surface'] = theme.backgroundColor;\n }\n if (theme.surfaceColor) {\n variables['--reevit-surface'] = theme.surfaceColor;\n }\n\n // Border color\n if (theme.borderColor) {\n variables['--reevit-border'] = theme.borderColor;\n }\n\n // Legacy text color support\n if (theme.textColor) {\n variables['--reevit-text'] = theme.textColor;\n }\n if (theme.mutedTextColor) {\n variables['--reevit-text-secondary'] = theme.mutedTextColor;\n }\n\n // Border radius\n if (theme.borderRadius) {\n variables['--reevit-radius'] = theme.borderRadius;\n variables['--reevit-radius-sm'] = theme.borderRadius;\n variables['--reevit-radius-lg'] = theme.borderRadius;\n }\n\n // Font family\n if (theme.fontFamily) {\n variables['--reevit-font'] = theme.fontFamily;\n }\n\n return variables;\n}\n\nfunction getContrastingColor(color: string): string | null {\n const hex = color.trim();\n if (!hex.startsWith('#')) {\n return null;\n }\n\n const normalized = hex.length === 4\n ? `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`\n : hex;\n\n if (normalized.length !== 7) {\n return null;\n }\n\n const r = parseInt(normalized.slice(1, 3), 16);\n const g = parseInt(normalized.slice(3, 5), 16);\n const b = parseInt(normalized.slice(5, 7), 16);\n\n if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n return null;\n }\n\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 140 ? '#0b1120' : '#ffffff';\n}\n\n/**\n * Simple class name concatenation utility\n */\nexport function cn(...classes: (string | boolean | undefined | null)[]): string {\n return classes.filter(Boolean).join(' ');\n}\n\n/**\n * Detects country code from currency\n */\nexport function detectCountryFromCurrency(currency: string): string {\n const currencyToCountry: Record<string, string> = {\n GHS: 'GH',\n NGN: 'NG',\n KES: 'KE',\n UGX: 'UG',\n TZS: 'TZ',\n ZAR: 'ZA',\n XOF: 'CI',\n XAF: 'CM',\n USD: 'US',\n EUR: 'DE',\n GBP: 'GB',\n };\n\n return currencyToCountry[currency.toUpperCase()] || 'GH';\n}\n","/**\n * Intent identity + cache helpers\n */\n\nimport type { PaymentIntentResponse } from './api/client';\nimport { generateIdempotencyKey } from './api/client';\nimport type { PaymentMethod, ReevitCheckoutConfig } from './types';\nimport { generateReference } from './utils';\n\nconst INTENT_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface IntentIdentityOptions {\n config: ReevitCheckoutConfig;\n method?: PaymentMethod;\n preferredProvider?: string;\n allowedProviders?: string[];\n publicKey?: string;\n}\n\nexport interface IntentCacheEntry {\n promise?: Promise<PaymentIntentResponse>;\n response?: PaymentIntentResponse;\n expiresAt: number;\n reference?: string;\n}\n\nconst intentCache = new Map<string, IntentCacheEntry>();\n\nfunction pruneIntentCache(now: number = Date.now()): void {\n for (const [key, entry] of intentCache) {\n if (entry.expiresAt <= now) {\n intentCache.delete(key);\n }\n }\n}\n\nfunction getIntentCacheEntryInternal(key: string): IntentCacheEntry | undefined {\n const entry = intentCache.get(key);\n if (!entry) {\n return undefined;\n }\n if (entry.expiresAt <= Date.now()) {\n intentCache.delete(key);\n return undefined;\n }\n return entry;\n}\n\nfunction setIntentCacheEntryInternal(key: string, update: Partial<IntentCacheEntry>): IntentCacheEntry {\n const now = Date.now();\n const existing = getIntentCacheEntryInternal(key);\n const next: IntentCacheEntry = {\n ...existing,\n ...update,\n expiresAt: now + INTENT_CACHE_TTL_MS,\n };\n intentCache.set(key, next);\n return next;\n}\n\nfunction buildIdempotencyPayload(options: IntentIdentityOptions): Record<string, unknown> {\n const { config, method, preferredProvider, allowedProviders, publicKey } = options;\n if (config.sessionSecret) {\n return {\n sessionSecret: config.sessionSecret,\n publicKey: publicKey || config.publicKey || '',\n };\n }\n\n const payload: Record<string, unknown> = {\n amount: config.amount,\n currency: config.currency,\n email: config.email || '',\n phone: config.phone || '',\n customerName: config.customerName || '',\n paymentLinkCode: config.paymentLinkCode || '',\n paymentMethods: config.paymentMethods || [],\n metadata: config.metadata || {},\n customFields: config.customFields || {},\n method: method || '',\n preferredProvider: preferredProvider || '',\n allowedProviders: allowedProviders || [],\n publicKey: publicKey || config.publicKey || '',\n };\n\n if (config.reference) {\n payload.reference = config.reference;\n }\n\n return payload;\n}\n\nexport function resolveIntentIdentity(options: IntentIdentityOptions): {\n idempotencyKey: string;\n reference: string;\n cacheEntry?: IntentCacheEntry;\n} {\n pruneIntentCache();\n\n const idempotencyKey =\n options.config.idempotencyKey || generateIdempotencyKey(buildIdempotencyPayload(options));\n const existing = getIntentCacheEntryInternal(idempotencyKey);\n const reference = options.config.reference || existing?.reference || generateReference();\n\n const cacheEntry = setIntentCacheEntryInternal(idempotencyKey, { reference });\n\n return { idempotencyKey, reference, cacheEntry };\n}\n\nexport function getIntentCacheEntry(idempotencyKey: string): IntentCacheEntry | undefined {\n pruneIntentCache();\n return getIntentCacheEntryInternal(idempotencyKey);\n}\n\nexport function cacheIntentPromise(\n idempotencyKey: string,\n promise: Promise<PaymentIntentResponse>\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { promise });\n}\n\nexport function cacheIntentResponse(\n idempotencyKey: string,\n response: PaymentIntentResponse\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { response, promise: undefined });\n}\n\nexport function clearIntentCacheEntry(idempotencyKey: string): void {\n intentCache.delete(idempotencyKey);\n}\n","/**\n * Reevit State Machine\n * Shared state management logic for all SDKs\n */\n\nimport type { CheckoutState, PaymentIntent, PaymentMethod, PaymentResult, PaymentError } from './types';\n\n// State shape\nexport interface ReevitState {\n status: CheckoutState;\n paymentIntent: PaymentIntent | null;\n selectedMethod: PaymentMethod | null;\n error: PaymentError | null;\n result: PaymentResult | null;\n}\n\n// Actions\nexport type ReevitAction =\n | { type: 'INIT_START' }\n | { type: 'INIT_SUCCESS'; payload: PaymentIntent }\n | { type: 'INIT_ERROR'; payload: PaymentError }\n | { type: 'SELECT_METHOD'; payload: PaymentMethod }\n | { type: 'PROCESS_START' }\n | { type: 'PROCESS_SUCCESS'; payload: PaymentResult }\n | { type: 'PROCESS_ERROR'; payload: PaymentError }\n | { type: 'RESET' }\n | { type: 'CLOSE' };\n\n/**\n * Creates the initial state for the checkout\n */\nexport function createInitialState(): ReevitState {\n return {\n status: 'idle',\n paymentIntent: null,\n selectedMethod: null,\n error: null,\n result: null,\n };\n}\n\n/**\n * State reducer for checkout flow\n */\nexport function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState {\n switch (action.type) {\n case 'INIT_START':\n return { ...state, status: 'loading', error: null };\n case 'INIT_SUCCESS':\n return {\n ...state,\n status: 'ready',\n paymentIntent: action.payload,\n selectedMethod:\n action.payload.availableMethods?.length === 1 ? action.payload.availableMethods[0] : null,\n };\n case 'INIT_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'SELECT_METHOD':\n return { ...state, status: 'method_selected', selectedMethod: action.payload };\n case 'PROCESS_START':\n return { ...state, status: 'processing', error: null };\n case 'PROCESS_SUCCESS':\n return { ...state, status: 'success', result: action.payload };\n case 'PROCESS_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'RESET':\n return { ...createInitialState(), status: 'ready', paymentIntent: state.paymentIntent };\n case 'CLOSE':\n return { ...state, status: 'closed' };\n default:\n return state;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkHA,IAAM,0BAA0B;AAChC,IAAM,kBAAkB;AACxB,IAAI,mCAAmC;AAYhC,SAAS,mBAAmB,UAAoB,WAA2C;AAChG,SAAO;AAAA,IACL,MAAM,UAAU,QAAQ;AAAA,IACxB,SAAS,UAAU,WAAW;AAAA,IAC9B,aAAa,oBAAoB,SAAS,MAAM;AAAA,IAChD,SAAS;AAAA,MACP,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS,QAAQ,IAAI,cAAc,KAAK,SAAS,QAAQ,IAAI,qBAAqB,KAAK;AAAA,MAClG,GAAG,UAAU;AAAA,IACf;AAAA,EACF;AACF;AAEO,SAAS,eAAe,OAAuC;AACpE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,aAAa;AACxF;AAEA,SAAS,oBAAoB,QAAyB;AACpD,SAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,UAAU;AAC3F;AAOO,SAAS,uBAAuB,QAAyC;AAE9E,QAAM,aAAa,OAAO,KAAK,MAAM,EAAE,KAAK;AAC5C,QAAM,eAAe,WAClB,IAAI,SAAO,GAAG,GAAG,IAAI,KAAK,UAAU,OAAO,GAAG,CAAC,CAAC,EA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AO,EAAE,GAAG,mBAAmB,GAAG,QAAQ,SAAS,eAAe,MAAM,cAAc;AAAA,IACxF,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,QAAQ,SAAS;AAAA,IACtC;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
// src/api/client.ts
|
|
2
2
|
var API_BASE_URL_PRODUCTION = "https://api.reevit.io";
|
|
3
3
|
var DEFAULT_TIMEOUT = 3e4;
|
|
4
|
+
var hasWarnedAboutLiveBrowserIntents = false;
|
|
4
5
|
function createPaymentError(response, errorData) {
|
|
5
6
|
return {
|
|
6
7
|
code: errorData.code || "api_error",
|
|
7
8
|
message: errorData.message || "An unexpected error occurred",
|
|
9
|
+
recoverable: isRecoverableStatus(response.status),
|
|
8
10
|
details: {
|
|
9
11
|
httpStatus: response.status,
|
|
12
|
+
requestId: response.headers.get("x-request-id") || response.headers.get("x-reevit-request-id") || void 0,
|
|
10
13
|
...errorData.details
|
|
11
14
|
}
|
|
12
15
|
};
|
|
13
16
|
}
|
|
17
|
+
function isPaymentError(error) {
|
|
18
|
+
return typeof error === "object" && error !== null && "code" in error && "message" in error;
|
|
19
|
+
}
|
|
20
|
+
function isRecoverableStatus(status) {
|
|
21
|
+
return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
|
|
22
|
+
}
|
|
14
23
|
function generateIdempotencyKey(params) {
|
|
15
24
|
const sortedKeys = Object.keys(params).sort();
|
|
16
25
|
const stableString = sortedKeys.map((key) => `${key}:${JSON.stringify(params[key])}`).join("|");
|
|
@@ -39,7 +48,7 @@ var ReevitAPIClient = class {
|
|
|
39
48
|
const headers = {
|
|
40
49
|
"Content-Type": "application/json",
|
|
41
50
|
"X-Reevit-Client": "@reevit/core",
|
|
42
|
-
"X-Reevit-Client-Version": "0.
|
|
51
|
+
"X-Reevit-Client-Version": "0.9.0"
|
|
43
52
|
};
|
|
44
53
|
if (this.publicKey) {
|
|
45
54
|
headers["X-Reevit-Key"] = this.publicKey;
|
|
@@ -69,7 +78,8 @@ var ReevitAPIClient = class {
|
|
|
69
78
|
return {
|
|
70
79
|
error: {
|
|
71
80
|
code: "request_timeout",
|
|
72
|
-
message: "The request timed out. Please try again."
|
|
81
|
+
message: "The request timed out. Please try again.",
|
|
82
|
+
recoverable: true
|
|
73
83
|
}
|
|
74
84
|
};
|
|
75
85
|
}
|
|
@@ -77,7 +87,8 @@ var ReevitAPIClient = class {
|
|
|
77
87
|
return {
|
|
78
88
|
error: {
|
|
79
89
|
code: "network_error",
|
|
80
|
-
message: "Unable to connect to Reevit. Please check your internet connection."
|
|
90
|
+
message: "Unable to connect to Reevit. Please check your internet connection.",
|
|
91
|
+
recoverable: true
|
|
81
92
|
}
|
|
82
93
|
};
|
|
83
94
|
}
|
|
@@ -85,7 +96,8 @@ var ReevitAPIClient = class {
|
|
|
85
96
|
return {
|
|
86
97
|
error: {
|
|
87
98
|
code: "unknown_error",
|
|
88
|
-
message: "An unexpected error occurred. Please try again."
|
|
99
|
+
message: "An unexpected error occurred. Please try again.",
|
|
100
|
+
recoverable: true
|
|
89
101
|
}
|
|
90
102
|
};
|
|
91
103
|
}
|
|
@@ -94,6 +106,21 @@ var ReevitAPIClient = class {
|
|
|
94
106
|
* Creates a payment intent
|
|
95
107
|
*/
|
|
96
108
|
async createPaymentIntent(config, method, country = "GH", options) {
|
|
109
|
+
if (this.publicKey.startsWith("pfk_live_") && !hasWarnedAboutLiveBrowserIntents && typeof console !== "undefined") {
|
|
110
|
+
hasWarnedAboutLiveBrowserIntents = true;
|
|
111
|
+
console.warn(
|
|
112
|
+
"Creating live payment intents from the browser is deprecated. Create a checkout session on your server and pass sessionSecret to the browser SDK instead."
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (typeof config.amount !== "number" || !config.currency) {
|
|
116
|
+
return {
|
|
117
|
+
error: {
|
|
118
|
+
code: "invalid_checkout_config",
|
|
119
|
+
message: "amount and currency are required when creating a payment intent in the browser.",
|
|
120
|
+
recoverable: false
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
97
124
|
const metadata = { ...config.metadata };
|
|
98
125
|
if (config.email) {
|
|
99
126
|
metadata.customer_email = config.email;
|
|
@@ -134,6 +161,15 @@ var ReevitAPIClient = class {
|
|
|
134
161
|
async getPaymentIntent(paymentId) {
|
|
135
162
|
return this.request("GET", `/v1/payments/${paymentId}`);
|
|
136
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Retrieves a server-created checkout session using its public session secret.
|
|
166
|
+
*/
|
|
167
|
+
async getCheckoutSession(sessionSecret) {
|
|
168
|
+
return this.request(
|
|
169
|
+
"GET",
|
|
170
|
+
`/v1/checkout/sessions/${encodeURIComponent(sessionSecret)}`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
137
173
|
/**
|
|
138
174
|
* Confirms a payment after PSP callback
|
|
139
175
|
*/
|
|
@@ -352,6 +388,12 @@ function setIntentCacheEntryInternal(key, update) {
|
|
|
352
388
|
}
|
|
353
389
|
function buildIdempotencyPayload(options) {
|
|
354
390
|
const { config, method, preferredProvider, allowedProviders, publicKey } = options;
|
|
391
|
+
if (config.sessionSecret) {
|
|
392
|
+
return {
|
|
393
|
+
sessionSecret: config.sessionSecret,
|
|
394
|
+
publicKey: publicKey || config.publicKey || ""
|
|
395
|
+
};
|
|
396
|
+
}
|
|
355
397
|
const payload = {
|
|
356
398
|
amount: config.amount,
|
|
357
399
|
currency: config.currency,
|
|
@@ -440,6 +482,7 @@ export {
|
|
|
440
482
|
clearIntentCacheEntry,
|
|
441
483
|
cn,
|
|
442
484
|
createInitialState,
|
|
485
|
+
createPaymentError,
|
|
443
486
|
createReevitClient,
|
|
444
487
|
createThemeVariables,
|
|
445
488
|
detectCountryFromCurrency,
|
|
@@ -449,6 +492,7 @@ export {
|
|
|
449
492
|
generateIdempotencyKey,
|
|
450
493
|
generateReference,
|
|
451
494
|
getIntentCacheEntry,
|
|
495
|
+
isPaymentError,
|
|
452
496
|
reevitReducer,
|
|
453
497
|
resolveIntentIdentity,
|
|
454
498
|
validatePhone
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/client.ts","../src/utils.ts","../src/intent.ts","../src/state.ts"],"sourcesContent":["/**\n * Reevit API Client\n * \n * Handles communication with the Reevit backend for payment operations.\n */\n\nimport type { PaymentMethod, ReevitCheckoutConfig, PaymentError, HubtelSessionResponse } from '../types';\n\n// API Response Types (matching backend handlers_payments.go)\nexport interface CreatePaymentIntentRequest {\n amount: number;\n currency: string;\n method?: string;\n country: string;\n customer_id?: string;\n metadata?: Record<string, unknown>;\n description?: string;\n policy?: {\n prefer?: string[];\n allowed_providers?: string[];\n max_amount?: number;\n blocked_bins?: string[];\n allowed_bins?: string[];\n velocity_max_per_minute?: number;\n };\n}\n\nexport interface PaymentIntentResponse {\n id: string;\n org_id?: string;\n connection_id: string;\n provider: string;\n provider_ref_id?: string;\n status: string;\n client_secret: string;\n psp_public_key: string;\n psp_credentials?: {\n merchantAccount?: string | number;\n basicAuth?: string;\n [key: string]: unknown;\n };\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n reference?: string;\n available_psps?: Array<{\n provider: string;\n name: string;\n methods: string[];\n countries?: string[];\n }>;\n branding?: Record<string, unknown>;\n}\n\nexport interface ConfirmPaymentRequest {\n provider_ref_id: string;\n provider_data?: Record<string, unknown>;\n}\n\nexport interface PaymentDetailResponse {\n id: string;\n connection_id: string;\n provider: string;\n method: string;\n status: string;\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n customer_id?: string;\n client_secret: string;\n provider_ref_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n /** Payment source type (payment_link, api, subscription) */\n source?: 'payment_link' | 'api' | 'subscription';\n /** ID of the source (payment link ID, subscription ID, etc.) */\n source_id?: string;\n /** Human-readable description of the source (e.g., payment link name) */\n source_description?: string;\n}\n\nexport interface APIErrorResponse {\n code: string;\n message: string;\n details?: Record<string, string>;\n}\n\n// API Client configuration\nexport interface ReevitAPIClientConfig {\n /** Your Reevit public key */\n publicKey?: string;\n /** Base URL for the Reevit API (defaults to production) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n// Default API base URLs\nconst API_BASE_URL_PRODUCTION = 'https://api.reevit.io';\nconst DEFAULT_TIMEOUT = 30000; // 30 seconds\n\n/**\n * Determines if a public key is for sandbox mode\n */\nexport function isSandboxKey(publicKey: string): boolean {\n return publicKey.startsWith('pfk_test_');\n}\n\n/**\n * Creates a PaymentError from an API error response\n */\nfunction createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError {\n return {\n code: errorData.code || 'api_error',\n message: errorData.message || 'An unexpected error occurred',\n details: {\n httpStatus: response.status,\n ...errorData.details,\n },\n };\n}\n\n/**\n * Generates a deterministic idempotency key based on input parameters\n * Uses a simple hash function suitable for browser environments\n * Exported for use by SDK hooks (e.g., payment link flows)\n */\nexport function generateIdempotencyKey(params: Record<string, unknown>): string {\n // Create a stable string representation of the parameters\n const sortedKeys = Object.keys(params).sort();\n const stableString = sortedKeys\n .map(key => `${key}:${JSON.stringify(params[key])}`)\n .join('|');\n\n // Simple hash function (djb2 algorithm)\n let hash = 5381;\n for (let i = 0; i < stableString.length; i++) {\n hash = ((hash << 5) + hash) + stableString.charCodeAt(i);\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n // Convert to positive hex string\n const hashHex = (hash >>> 0).toString(16);\n\n // Add a time bucket (5-minute windows) to allow retries within a reasonable window\n // but prevent keys from being reused across completely different sessions\n const timeBucket = Math.floor(Date.now() / (5 * 60 * 1000));\n\n return `reevit_${timeBucket}_${hashHex}`;\n}\n\n/**\n * Reevit API Client\n */\nexport class ReevitAPIClient {\n private readonly publicKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(config: ReevitAPIClientConfig) {\n this.publicKey = config.publicKey || '';\n this.baseUrl = config.baseUrl || API_BASE_URL_PRODUCTION;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Makes an authenticated API request\n * @param idempotencyKey Optional deterministic idempotency key for the request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: unknown,\n idempotencyKey?: string\n ): Promise<{ data?: T; error?: PaymentError }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Generate headers with idempotency key for mutating requests\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Reevit-Client': '@reevit/core',\n 'X-Reevit-Client-Version': '0.8.1',\n };\n if (this.publicKey) {\n headers['X-Reevit-Key'] = this.publicKey;\n }\n\n if (method === 'POST' || method === 'PATCH' || method === 'PUT') {\n // Use provided deterministic key, or generate one based on request body\n headers['Idempotency-Key'] = idempotencyKey ||\n (body ? generateIdempotencyKey(body as Record<string, unknown>) : `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`);\n }\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const responseData = await response.json().catch(() => ({}));\n\n if (!response.ok) {\n return {\n error: createPaymentError(response, responseData as APIErrorResponse),\n };\n }\n\n return { data: responseData as T };\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return {\n error: {\n code: 'request_timeout',\n message: 'The request timed out. Please try again.',\n },\n };\n }\n\n if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {\n return {\n error: {\n code: 'network_error',\n message: 'Unable to connect to Reevit. Please check your internet connection.',\n },\n };\n }\n }\n\n return {\n error: {\n code: 'unknown_error',\n message: 'An unexpected error occurred. Please try again.',\n },\n };\n }\n }\n\n /**\n * Creates a payment intent\n */\n async createPaymentIntent(\n config: ReevitCheckoutConfig,\n method?: PaymentMethod,\n country: string = 'GH',\n options?: { preferredProviders?: string[]; allowedProviders?: string[] }\n ): Promise<{ data?: PaymentIntentResponse; error?: PaymentError }> {\n // Build metadata with customer_email for PSP providers that require it\n const metadata: Record<string, unknown> = { ...config.metadata };\n if (config.email) {\n metadata.customer_email = config.email;\n }\n if (config.phone) {\n metadata.customer_phone = config.phone;\n }\n\n const request: CreatePaymentIntentRequest = {\n amount: config.amount,\n currency: config.currency,\n country,\n customer_id: config.email || (config.metadata?.customerId as string | undefined),\n metadata,\n };\n\n if (method) {\n request.method = this.mapPaymentMethod(method);\n }\n\n if (options?.preferredProviders?.length || options?.allowedProviders?.length) {\n request.policy = {\n prefer: options?.preferredProviders,\n allowed_providers: options?.allowedProviders,\n };\n }\n\n // Generate a deterministic idempotency key based on payment parameters\n // This ensures that duplicate requests for the same payment return the same intent\n const idempotencyKey = config.idempotencyKey || generateIdempotencyKey({\n amount: config.amount,\n currency: config.currency,\n customer: config.email || config.metadata?.customerId || '',\n reference: config.reference || '',\n method: method || '',\n provider: options?.preferredProviders?.[0] || options?.allowedProviders?.[0] || '',\n publicKey: this.publicKey,\n });\n\n return this.request<PaymentIntentResponse>('POST', '/v1/payments/intents', request, idempotencyKey);\n }\n\n /**\n * Retrieves a payment intent by ID\n */\n async getPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('GET', `/v1/payments/${paymentId}`);\n }\n\n /**\n * Confirms a payment after PSP callback\n */\n async confirmPayment(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/confirm`);\n }\n\n /**\n * Confirms a payment intent using client secret (public endpoint)\n */\n async confirmPaymentIntent(paymentId: string, clientSecret: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>(\n 'POST',\n `/v1/payments/${paymentId}/confirm-intent?client_secret=${encodeURIComponent(clientSecret)}`\n );\n }\n\n /**\n * Cancels a payment intent\n */\n async cancelPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/cancel`);\n }\n\n /**\n * Creates a Hubtel session token for secure checkout\n * Returns a short-lived token that contains Hubtel credentials\n * Credentials are never exposed to the client directly\n */\n async createHubtelSession(\n paymentId: string,\n clientSecret?: string\n ): Promise<{ data?: HubtelSessionResponse; error?: PaymentError }> {\n const query = clientSecret ? `?client_secret=${encodeURIComponent(clientSecret)}` : '';\n return this.request<HubtelSessionResponse>('POST', `/v1/payments/hubtel/sessions/${paymentId}${query}`);\n }\n\n /**\n * Maps SDK payment method to backend format\n */\n private mapPaymentMethod(method: PaymentMethod): string {\n switch (method) {\n case 'card':\n return 'card';\n case 'mobile_money':\n return 'mobile_money';\n case 'bank_transfer':\n return 'bank_transfer';\n default:\n return method;\n }\n }\n}\n\n/**\n * Creates a new Reevit API client instance\n */\nexport function createReevitClient(config: ReevitAPIClientConfig): ReevitAPIClient {\n return new ReevitAPIClient(config);\n}\n","/**\n * Utility Functions\n * Shared utilities for Reevit SDKs\n */\n\nimport type { MobileMoneyNetwork, ReevitTheme } from './types';\n\n/**\n * Formats an amount from smallest currency unit to display format\n */\nexport function formatAmount(amount: number, currency: string): string {\n const majorUnit = amount / 100;\n\n const currencyFormats: Record<string, { locale: string; minimumFractionDigits: number }> = {\n GHS: { locale: 'en-GH', minimumFractionDigits: 2 },\n NGN: { locale: 'en-NG', minimumFractionDigits: 2 },\n KES: { locale: 'en-KE', minimumFractionDigits: 2 },\n USD: { locale: 'en-US', minimumFractionDigits: 2 },\n EUR: { locale: 'de-DE', minimumFractionDigits: 2 },\n GBP: { locale: 'en-GB', minimumFractionDigits: 2 },\n };\n\n const format = currencyFormats[currency.toUpperCase()] || { locale: 'en-US', minimumFractionDigits: 2 };\n\n try {\n return new Intl.NumberFormat(format.locale, {\n style: 'currency',\n currency: currency.toUpperCase(),\n minimumFractionDigits: format.minimumFractionDigits,\n }).format(majorUnit);\n } catch {\n // Fallback for unsupported currencies\n return `${currency} ${majorUnit.toFixed(2)}`;\n }\n}\n\n/**\n * Generates a unique payment reference\n */\nexport function generateReference(prefix: string = 'reevit'): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${prefix}_${timestamp}_${random}`;\n}\n\n/**\n * Validates a phone number for mobile money\n */\nexport function validatePhone(phone: string, country: string = 'GH'): boolean {\n // Remove non-digit characters\n const digits = phone.replace(/\\D/g, '');\n\n const patterns: Record<string, RegExp> = {\n GH: /^(?:233|0)?[235][0-9]{8}$/, // Ghana\n NG: /^(?:234|0)?[789][01][0-9]{8}$/, // Nigeria\n KE: /^(?:254|0)?[17][0-9]{8}$/, // Kenya\n };\n\n const pattern = patterns[country.toUpperCase()];\n if (!pattern) return digits.length >= 10;\n\n return pattern.test(digits);\n}\n\n/**\n * Formats a phone number for display\n */\nexport function formatPhone(phone: string, country: string = 'GH'): string {\n const digits = phone.replace(/\\D/g, '');\n\n if (country === 'GH') {\n // Format as 0XX XXX XXXX\n if (digits.startsWith('233') && digits.length === 12) {\n const local = '0' + digits.slice(3);\n return `${local.slice(0, 3)} ${local.slice(3, 6)} ${local.slice(6)}`;\n }\n if (digits.length === 10 && digits.startsWith('0')) {\n return `${digits.slice(0, 3)} ${digits.slice(3, 6)} ${digits.slice(6)}`;\n }\n }\n\n return phone;\n}\n\n/**\n * Detects mobile money network from phone number (Ghana)\n */\nexport function detectNetwork(phone: string): MobileMoneyNetwork | null {\n const digits = phone.replace(/\\D/g, '');\n\n // Get the network prefix (first 3 digits after country code or 0)\n let prefix: string;\n if (digits.startsWith('233')) {\n prefix = digits.slice(3, 5);\n } else if (digits.startsWith('0')) {\n prefix = digits.slice(1, 3);\n } else {\n prefix = digits.slice(0, 2);\n }\n\n // Ghana network prefixes\n const mtnPrefixes = ['24', '25', '53', '54', '55', '59'];\n const telecelPrefixes = ['20', '50'];\n const airteltigoPrefixes = ['26', '27', '56', '57'];\n\n if (mtnPrefixes.includes(prefix)) return 'mtn';\n if (telecelPrefixes.includes(prefix)) return 'telecel';\n if (airteltigoPrefixes.includes(prefix)) return 'airteltigo';\n\n return null;\n}\n\n/**\n * Creates CSS custom property variables from theme\n */\nexport function createThemeVariables(theme: ReevitTheme): Record<string, string> {\n const variables: Record<string, string> = {};\n\n // Primary color = main text color\n if (theme.primaryColor) {\n variables['--reevit-text'] = theme.primaryColor;\n }\n\n // Primary foreground = description/secondary text color\n if (theme.primaryForegroundColor) {\n variables['--reevit-text-secondary'] = theme.primaryForegroundColor;\n variables['--reevit-muted'] = theme.primaryForegroundColor;\n }\n\n // Button colors\n if (theme.buttonBackgroundColor) {\n variables['--reevit-primary'] = theme.buttonBackgroundColor;\n variables['--reevit-primary-hover'] = theme.buttonBackgroundColor;\n }\n if (theme.buttonTextColor) {\n variables['--reevit-primary-foreground'] = theme.buttonTextColor;\n }\n\n // Background and surface colors\n if (theme.backgroundColor) {\n variables['--reevit-background'] = theme.backgroundColor;\n variables['--reevit-surface'] = theme.backgroundColor;\n }\n if (theme.surfaceColor) {\n variables['--reevit-surface'] = theme.surfaceColor;\n }\n\n // Border color\n if (theme.borderColor) {\n variables['--reevit-border'] = theme.borderColor;\n }\n\n // Legacy text color support\n if (theme.textColor) {\n variables['--reevit-text'] = theme.textColor;\n }\n if (theme.mutedTextColor) {\n variables['--reevit-text-secondary'] = theme.mutedTextColor;\n }\n\n // Border radius\n if (theme.borderRadius) {\n variables['--reevit-radius'] = theme.borderRadius;\n variables['--reevit-radius-sm'] = theme.borderRadius;\n variables['--reevit-radius-lg'] = theme.borderRadius;\n }\n\n // Font family\n if (theme.fontFamily) {\n variables['--reevit-font'] = theme.fontFamily;\n }\n\n return variables;\n}\n\nfunction getContrastingColor(color: string): string | null {\n const hex = color.trim();\n if (!hex.startsWith('#')) {\n return null;\n }\n\n const normalized = hex.length === 4\n ? `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`\n : hex;\n\n if (normalized.length !== 7) {\n return null;\n }\n\n const r = parseInt(normalized.slice(1, 3), 16);\n const g = parseInt(normalized.slice(3, 5), 16);\n const b = parseInt(normalized.slice(5, 7), 16);\n\n if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n return null;\n }\n\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 140 ? '#0b1120' : '#ffffff';\n}\n\n/**\n * Simple class name concatenation utility\n */\nexport function cn(...classes: (string | boolean | undefined | null)[]): string {\n return classes.filter(Boolean).join(' ');\n}\n\n/**\n * Detects country code from currency\n */\nexport function detectCountryFromCurrency(currency: string): string {\n const currencyToCountry: Record<string, string> = {\n GHS: 'GH',\n NGN: 'NG',\n KES: 'KE',\n UGX: 'UG',\n TZS: 'TZ',\n ZAR: 'ZA',\n XOF: 'CI',\n XAF: 'CM',\n USD: 'US',\n EUR: 'DE',\n GBP: 'GB',\n };\n\n return currencyToCountry[currency.toUpperCase()] || 'GH';\n}\n","/**\n * Intent identity + cache helpers\n */\n\nimport type { PaymentIntentResponse } from './api/client';\nimport { generateIdempotencyKey } from './api/client';\nimport type { PaymentMethod, ReevitCheckoutConfig } from './types';\nimport { generateReference } from './utils';\n\nconst INTENT_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface IntentIdentityOptions {\n config: ReevitCheckoutConfig;\n method?: PaymentMethod;\n preferredProvider?: string;\n allowedProviders?: string[];\n publicKey?: string;\n}\n\nexport interface IntentCacheEntry {\n promise?: Promise<PaymentIntentResponse>;\n response?: PaymentIntentResponse;\n expiresAt: number;\n reference?: string;\n}\n\nconst intentCache = new Map<string, IntentCacheEntry>();\n\nfunction pruneIntentCache(now: number = Date.now()): void {\n for (const [key, entry] of intentCache) {\n if (entry.expiresAt <= now) {\n intentCache.delete(key);\n }\n }\n}\n\nfunction getIntentCacheEntryInternal(key: string): IntentCacheEntry | undefined {\n const entry = intentCache.get(key);\n if (!entry) {\n return undefined;\n }\n if (entry.expiresAt <= Date.now()) {\n intentCache.delete(key);\n return undefined;\n }\n return entry;\n}\n\nfunction setIntentCacheEntryInternal(key: string, update: Partial<IntentCacheEntry>): IntentCacheEntry {\n const now = Date.now();\n const existing = getIntentCacheEntryInternal(key);\n const next: IntentCacheEntry = {\n ...existing,\n ...update,\n expiresAt: now + INTENT_CACHE_TTL_MS,\n };\n intentCache.set(key, next);\n return next;\n}\n\nfunction buildIdempotencyPayload(options: IntentIdentityOptions): Record<string, unknown> {\n const { config, method, preferredProvider, allowedProviders, publicKey } = options;\n const payload: Record<string, unknown> = {\n amount: config.amount,\n currency: config.currency,\n email: config.email || '',\n phone: config.phone || '',\n customerName: config.customerName || '',\n paymentLinkCode: config.paymentLinkCode || '',\n paymentMethods: config.paymentMethods || [],\n metadata: config.metadata || {},\n customFields: config.customFields || {},\n method: method || '',\n preferredProvider: preferredProvider || '',\n allowedProviders: allowedProviders || [],\n publicKey: publicKey || config.publicKey || '',\n };\n\n if (config.reference) {\n payload.reference = config.reference;\n }\n\n return payload;\n}\n\nexport function resolveIntentIdentity(options: IntentIdentityOptions): {\n idempotencyKey: string;\n reference: string;\n cacheEntry?: IntentCacheEntry;\n} {\n pruneIntentCache();\n\n const idempotencyKey =\n options.config.idempotencyKey || generateIdempotencyKey(buildIdempotencyPayload(options));\n const existing = getIntentCacheEntryInternal(idempotencyKey);\n const reference = options.config.reference || existing?.reference || generateReference();\n\n const cacheEntry = setIntentCacheEntryInternal(idempotencyKey, { reference });\n\n return { idempotencyKey, reference, cacheEntry };\n}\n\nexport function getIntentCacheEntry(idempotencyKey: string): IntentCacheEntry | undefined {\n pruneIntentCache();\n return getIntentCacheEntryInternal(idempotencyKey);\n}\n\nexport function cacheIntentPromise(\n idempotencyKey: string,\n promise: Promise<PaymentIntentResponse>\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { promise });\n}\n\nexport function cacheIntentResponse(\n idempotencyKey: string,\n response: PaymentIntentResponse\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { response, promise: undefined });\n}\n\nexport function clearIntentCacheEntry(idempotencyKey: string): void {\n intentCache.delete(idempotencyKey);\n}\n","/**\n * Reevit State Machine\n * Shared state management logic for all SDKs\n */\n\nimport type { CheckoutState, PaymentIntent, PaymentMethod, PaymentResult, PaymentError } from './types';\n\n// State shape\nexport interface ReevitState {\n status: CheckoutState;\n paymentIntent: PaymentIntent | null;\n selectedMethod: PaymentMethod | null;\n error: PaymentError | null;\n result: PaymentResult | null;\n}\n\n// Actions\nexport type ReevitAction =\n | { type: 'INIT_START' }\n | { type: 'INIT_SUCCESS'; payload: PaymentIntent }\n | { type: 'INIT_ERROR'; payload: PaymentError }\n | { type: 'SELECT_METHOD'; payload: PaymentMethod }\n | { type: 'PROCESS_START' }\n | { type: 'PROCESS_SUCCESS'; payload: PaymentResult }\n | { type: 'PROCESS_ERROR'; payload: PaymentError }\n | { type: 'RESET' }\n | { type: 'CLOSE' };\n\n/**\n * Creates the initial state for the checkout\n */\nexport function createInitialState(): ReevitState {\n return {\n status: 'idle',\n paymentIntent: null,\n selectedMethod: null,\n error: null,\n result: null,\n };\n}\n\n/**\n * State reducer for checkout flow\n */\nexport function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState {\n switch (action.type) {\n case 'INIT_START':\n return { ...state, status: 'loading', error: null };\n case 'INIT_SUCCESS':\n return {\n ...state,\n status: 'ready',\n paymentIntent: action.payload,\n selectedMethod:\n action.payload.availableMethods?.length === 1 ? action.payload.availableMethods[0] : null,\n };\n case 'INIT_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'SELECT_METHOD':\n return { ...state, status: 'method_selected', selectedMethod: action.payload };\n case 'PROCESS_START':\n return { ...state, status: 'processing', error: null };\n case 'PROCESS_SUCCESS':\n return { ...state, status: 'success', result: action.payload };\n case 'PROCESS_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'RESET':\n return { ...createInitialState(), status: 'ready', paymentIntent: state.paymentIntent };\n case 'CLOSE':\n return { ...state, status: 'closed' };\n default:\n return state;\n }\n}\n"],"mappings":";AAuGA,IAAM,0BAA0B;AAChC,IAAM,kBAAkB;AAYxB,SAAS,mBAAmB,UAAoB,WAA2C;AACzF,SAAO;AAAA,IACL,MAAM,UAAU,QAAQ;AAAA,IACxB,SAAS,UAAU,WAAW;AAAA,IAC9B,SAAS;AAAA,MACP,YAAY,SAAS;AAAA,MACrB,GAAG,UAAU;AAAA,IACf;AAAA,EACF;AACF;AAOO,SAAS,uBAAuB,QAAyC;AAE9E,QAAM,aAAa,OAAO,KAAK,MAAM,EAAE,KAAK;AAC5C,QAAM,eAAe,WAClB,IAAI,SAAO,GAAG,GAAG,IAAI,KAAK,UAAU,OAAO,GAAG,CAAC,CAAC,EAAE,EAClD,KAAK,GAAG;AAGX,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAS,QAAQ,KAAK,OAAQ,aAAa,WAAW,CAAC;AACvD,WAAO,OAAO;AAAA,EAChB;AAGA,QAAM,WAAW,SAAS,GAAG,SAAS,EAAE;AAIxC,QAAM,aAAa,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI,KAAK,IAAK;AAE1D,SAAO,UAAU,UAAU,IAAI,OAAO;AACxC;AAKO,IAAM,kBAAN,MAAsB;AAAA,EAK3B,YAAY,QAA+B;AACzC,SAAK,YAAY,OAAO,aAAa;AACrC,SAAK,UAAU,OAAO,WAAW;AACjC,SAAK,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,QACZ,QACA,MACA,MACA,gBAC6C;AAC7C,UAAM,aAAa,IAAI,gBAAgB;AACvC,UAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO;AAGnE,UAAM,UAAkC;AAAA,MACtC,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,MACnB,2BAA2B;AAAA,I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AAQ,SAAS;AAAA,IACtC;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/api/client.ts","../src/utils.ts","../src/intent.ts","../src/state.ts"],"sourcesContent":["/**\n * Reevit API Client\n * \n * Handles communication with the Reevit backend for payment operations.\n */\n\nimport type { PaymentMethod, ReevitCheckoutConfig, PaymentError, HubtelSessionResponse } from '../types';\n\n// API Response Types (matching backend handlers_payments.go)\nexport interface CreatePaymentIntentRequest {\n amount: number;\n currency: string;\n method?: string;\n country: string;\n customer_id?: string;\n metadata?: Record<string, unknown>;\n description?: string;\n policy?: {\n prefer?: string[];\n allowed_providers?: string[];\n max_amount?: number;\n blocked_bins?: string[];\n allowed_bins?: string[];\n velocity_max_per_minute?: number;\n };\n}\n\nexport interface PaymentIntentResponse {\n id: string;\n org_id?: string;\n connection_id: string;\n provider: string;\n provider_ref_id?: string;\n status: string;\n client_secret: string;\n session_secret?: string;\n psp_public_key: string;\n psp_credentials?: {\n merchantAccount?: string | number;\n basicAuth?: string;\n [key: string]: unknown;\n };\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n reference?: string;\n available_psps?: Array<{\n provider: string;\n name: string;\n methods: string[];\n countries?: string[];\n }>;\n branding?: Record<string, unknown>;\n}\n\nexport interface CheckoutSessionResponse {\n id: string;\n client_secret: string;\n session_secret: string;\n payment_intent: PaymentIntentResponse;\n expires_at?: string;\n}\n\nexport interface ConfirmPaymentRequest {\n provider_ref_id: string;\n provider_data?: Record<string, unknown>;\n}\n\nexport interface PaymentDetailResponse {\n id: string;\n connection_id: string;\n provider: string;\n method: string;\n status: string;\n amount: number;\n currency: string;\n fee_amount: number;\n fee_currency: string;\n net_amount: number;\n customer_id?: string;\n client_secret: string;\n provider_ref_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n /** Payment source type (payment_link, api, subscription) */\n source?: 'payment_link' | 'api' | 'subscription';\n /** ID of the source (payment link ID, subscription ID, etc.) */\n source_id?: string;\n /** Human-readable description of the source (e.g., payment link name) */\n source_description?: string;\n}\n\nexport interface APIErrorResponse {\n code: string;\n message: string;\n details?: Record<string, unknown>;\n}\n\nexport type ReevitAPIResult<T> = { data: T; error?: never } | { data?: never; error: PaymentError };\n\n// API Client configuration\nexport interface ReevitAPIClientConfig {\n /** Your Reevit public key */\n publicKey?: string;\n /** Base URL for the Reevit API (defaults to production) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n// Default API base URLs\nconst API_BASE_URL_PRODUCTION = 'https://api.reevit.io';\nconst DEFAULT_TIMEOUT = 30000; // 30 seconds\nlet hasWarnedAboutLiveBrowserIntents = false;\n\n/**\n * Determines if a public key is for sandbox mode\n */\nexport function isSandboxKey(publicKey: string): boolean {\n return publicKey.startsWith('pfk_test_');\n}\n\n/**\n * Creates a PaymentError from an API error response\n */\nexport function createPaymentError(response: Response, errorData: APIErrorResponse): PaymentError {\n return {\n code: errorData.code || 'api_error',\n message: errorData.message || 'An unexpected error occurred',\n recoverable: isRecoverableStatus(response.status),\n details: {\n httpStatus: response.status,\n requestId: response.headers.get('x-request-id') || response.headers.get('x-reevit-request-id') || undefined,\n ...errorData.details,\n },\n };\n}\n\nexport function isPaymentError(error: unknown): error is PaymentError {\n return typeof error === 'object' && error !== null && 'code' in error && 'message' in error;\n}\n\nfunction isRecoverableStatus(status: number): boolean {\n return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;\n}\n\n/**\n * Generates a deterministic idempotency key based on input parameters\n * Uses a simple hash function suitable for browser environments\n * Exported for use by SDK hooks (e.g., payment link flows)\n */\nexport function generateIdempotencyKey(params: Record<string, unknown>): string {\n // Create a stable string representation of the parameters\n const sortedKeys = Object.keys(params).sort();\n const stableString = sortedKeys\n .map(key => `${key}:${JSON.stringify(params[key])}`)\n .join('|');\n\n // Simple hash function (djb2 algorithm)\n let hash = 5381;\n for (let i = 0; i < stableString.length; i++) {\n hash = ((hash << 5) + hash) + stableString.charCodeAt(i);\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n // Convert to positive hex string\n const hashHex = (hash >>> 0).toString(16);\n\n // Add a time bucket (5-minute windows) to allow retries within a reasonable window\n // but prevent keys from being reused across completely different sessions\n const timeBucket = Math.floor(Date.now() / (5 * 60 * 1000));\n\n return `reevit_${timeBucket}_${hashHex}`;\n}\n\n/**\n * Reevit API Client\n */\nexport class ReevitAPIClient {\n private readonly publicKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(config: ReevitAPIClientConfig) {\n this.publicKey = config.publicKey || '';\n this.baseUrl = config.baseUrl || API_BASE_URL_PRODUCTION;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Makes an authenticated API request\n * @param idempotencyKey Optional deterministic idempotency key for the request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: unknown,\n idempotencyKey?: string\n ): Promise<ReevitAPIResult<T>> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Generate headers with idempotency key for mutating requests\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Reevit-Client': '@reevit/core',\n 'X-Reevit-Client-Version': '0.9.0',\n };\n if (this.publicKey) {\n headers['X-Reevit-Key'] = this.publicKey;\n }\n\n if (method === 'POST' || method === 'PATCH' || method === 'PUT') {\n // Use provided deterministic key, or generate one based on request body\n headers['Idempotency-Key'] = idempotencyKey ||\n (body ? generateIdempotencyKey(body as Record<string, unknown>) : `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`);\n }\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const responseData = await response.json().catch(() => ({}));\n\n if (!response.ok) {\n return {\n error: createPaymentError(response, responseData as APIErrorResponse),\n };\n }\n\n return { data: responseData as T };\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return {\n error: {\n code: 'request_timeout',\n message: 'The request timed out. Please try again.',\n recoverable: true,\n },\n };\n }\n\n if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {\n return {\n error: {\n code: 'network_error',\n message: 'Unable to connect to Reevit. Please check your internet connection.',\n recoverable: true,\n },\n };\n }\n }\n\n return {\n error: {\n code: 'unknown_error',\n message: 'An unexpected error occurred. Please try again.',\n recoverable: true,\n },\n };\n }\n }\n\n /**\n * Creates a payment intent\n */\n async createPaymentIntent(\n config: ReevitCheckoutConfig,\n method?: PaymentMethod,\n country: string = 'GH',\n options?: { preferredProviders?: string[]; allowedProviders?: string[] }\n ): Promise<{ data?: PaymentIntentResponse; error?: PaymentError }> {\n if (\n this.publicKey.startsWith('pfk_live_') &&\n !hasWarnedAboutLiveBrowserIntents &&\n typeof console !== 'undefined'\n ) {\n hasWarnedAboutLiveBrowserIntents = true;\n console.warn(\n 'Creating live payment intents from the browser is deprecated. Create a checkout session on your server and pass sessionSecret to the browser SDK instead.'\n );\n }\n\n if (typeof config.amount !== 'number' || !config.currency) {\n return {\n error: {\n code: 'invalid_checkout_config',\n message: 'amount and currency are required when creating a payment intent in the browser.',\n recoverable: false,\n },\n };\n }\n\n // Build metadata with customer_email for PSP providers that require it\n const metadata: Record<string, unknown> = { ...config.metadata };\n if (config.email) {\n metadata.customer_email = config.email;\n }\n if (config.phone) {\n metadata.customer_phone = config.phone;\n }\n\n const request: CreatePaymentIntentRequest = {\n amount: config.amount,\n currency: config.currency,\n country,\n customer_id: config.email || (config.metadata?.customerId as string | undefined),\n metadata,\n };\n\n if (method) {\n request.method = this.mapPaymentMethod(method);\n }\n\n if (options?.preferredProviders?.length || options?.allowedProviders?.length) {\n request.policy = {\n prefer: options?.preferredProviders,\n allowed_providers: options?.allowedProviders,\n };\n }\n\n // Generate a deterministic idempotency key based on payment parameters\n // This ensures that duplicate requests for the same payment return the same intent\n const idempotencyKey = config.idempotencyKey || generateIdempotencyKey({\n amount: config.amount,\n currency: config.currency,\n customer: config.email || config.metadata?.customerId || '',\n reference: config.reference || '',\n method: method || '',\n provider: options?.preferredProviders?.[0] || options?.allowedProviders?.[0] || '',\n publicKey: this.publicKey,\n });\n\n return this.request<PaymentIntentResponse>('POST', '/v1/payments/intents', request, idempotencyKey);\n }\n\n /**\n * Retrieves a payment intent by ID\n */\n async getPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('GET', `/v1/payments/${paymentId}`);\n }\n\n /**\n * Retrieves a server-created checkout session using its public session secret.\n */\n async getCheckoutSession(sessionSecret: string): Promise<{ data?: CheckoutSessionResponse; error?: PaymentError }> {\n return this.request<CheckoutSessionResponse>(\n 'GET',\n `/v1/checkout/sessions/${encodeURIComponent(sessionSecret)}`\n );\n }\n\n /**\n * Confirms a payment after PSP callback\n */\n async confirmPayment(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/confirm`);\n }\n\n /**\n * Confirms a payment intent using client secret (public endpoint)\n */\n async confirmPaymentIntent(paymentId: string, clientSecret: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>(\n 'POST',\n `/v1/payments/${paymentId}/confirm-intent?client_secret=${encodeURIComponent(clientSecret)}`\n );\n }\n\n /**\n * Cancels a payment intent\n */\n async cancelPaymentIntent(paymentId: string): Promise<{ data?: PaymentDetailResponse; error?: PaymentError }> {\n return this.request<PaymentDetailResponse>('POST', `/v1/payments/${paymentId}/cancel`);\n }\n\n /**\n * Creates a Hubtel session token for secure checkout\n * Returns a short-lived token that contains Hubtel credentials\n * Credentials are never exposed to the client directly\n */\n async createHubtelSession(\n paymentId: string,\n clientSecret?: string\n ): Promise<{ data?: HubtelSessionResponse; error?: PaymentError }> {\n const query = clientSecret ? `?client_secret=${encodeURIComponent(clientSecret)}` : '';\n return this.request<HubtelSessionResponse>('POST', `/v1/payments/hubtel/sessions/${paymentId}${query}`);\n }\n\n /**\n * Maps SDK payment method to backend format\n */\n private mapPaymentMethod(method: PaymentMethod): string {\n switch (method) {\n case 'card':\n return 'card';\n case 'mobile_money':\n return 'mobile_money';\n case 'bank_transfer':\n return 'bank_transfer';\n default:\n return method;\n }\n }\n}\n\n/**\n * Creates a new Reevit API client instance\n */\nexport function createReevitClient(config: ReevitAPIClientConfig): ReevitAPIClient {\n return new ReevitAPIClient(config);\n}\n","/**\n * Utility Functions\n * Shared utilities for Reevit SDKs\n */\n\nimport type { MobileMoneyNetwork, ReevitTheme } from './types';\n\n/**\n * Formats an amount from smallest currency unit to display format\n */\nexport function formatAmount(amount: number, currency: string): string {\n const majorUnit = amount / 100;\n\n const currencyFormats: Record<string, { locale: string; minimumFractionDigits: number }> = {\n GHS: { locale: 'en-GH', minimumFractionDigits: 2 },\n NGN: { locale: 'en-NG', minimumFractionDigits: 2 },\n KES: { locale: 'en-KE', minimumFractionDigits: 2 },\n USD: { locale: 'en-US', minimumFractionDigits: 2 },\n EUR: { locale: 'de-DE', minimumFractionDigits: 2 },\n GBP: { locale: 'en-GB', minimumFractionDigits: 2 },\n };\n\n const format = currencyFormats[currency.toUpperCase()] || { locale: 'en-US', minimumFractionDigits: 2 };\n\n try {\n return new Intl.NumberFormat(format.locale, {\n style: 'currency',\n currency: currency.toUpperCase(),\n minimumFractionDigits: format.minimumFractionDigits,\n }).format(majorUnit);\n } catch {\n // Fallback for unsupported currencies\n return `${currency} ${majorUnit.toFixed(2)}`;\n }\n}\n\n/**\n * Generates a unique payment reference\n */\nexport function generateReference(prefix: string = 'reevit'): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `${prefix}_${timestamp}_${random}`;\n}\n\n/**\n * Validates a phone number for mobile money\n */\nexport function validatePhone(phone: string, country: string = 'GH'): boolean {\n // Remove non-digit characters\n const digits = phone.replace(/\\D/g, '');\n\n const patterns: Record<string, RegExp> = {\n GH: /^(?:233|0)?[235][0-9]{8}$/, // Ghana\n NG: /^(?:234|0)?[789][01][0-9]{8}$/, // Nigeria\n KE: /^(?:254|0)?[17][0-9]{8}$/, // Kenya\n };\n\n const pattern = patterns[country.toUpperCase()];\n if (!pattern) return digits.length >= 10;\n\n return pattern.test(digits);\n}\n\n/**\n * Formats a phone number for display\n */\nexport function formatPhone(phone: string, country: string = 'GH'): string {\n const digits = phone.replace(/\\D/g, '');\n\n if (country === 'GH') {\n // Format as 0XX XXX XXXX\n if (digits.startsWith('233') && digits.length === 12) {\n const local = '0' + digits.slice(3);\n return `${local.slice(0, 3)} ${local.slice(3, 6)} ${local.slice(6)}`;\n }\n if (digits.length === 10 && digits.startsWith('0')) {\n return `${digits.slice(0, 3)} ${digits.slice(3, 6)} ${digits.slice(6)}`;\n }\n }\n\n return phone;\n}\n\n/**\n * Detects mobile money network from phone number (Ghana)\n */\nexport function detectNetwork(phone: string): MobileMoneyNetwork | null {\n const digits = phone.replace(/\\D/g, '');\n\n // Get the network prefix (first 3 digits after country code or 0)\n let prefix: string;\n if (digits.startsWith('233')) {\n prefix = digits.slice(3, 5);\n } else if (digits.startsWith('0')) {\n prefix = digits.slice(1, 3);\n } else {\n prefix = digits.slice(0, 2);\n }\n\n // Ghana network prefixes\n const mtnPrefixes = ['24', '25', '53', '54', '55', '59'];\n const telecelPrefixes = ['20', '50'];\n const airteltigoPrefixes = ['26', '27', '56', '57'];\n\n if (mtnPrefixes.includes(prefix)) return 'mtn';\n if (telecelPrefixes.includes(prefix)) return 'telecel';\n if (airteltigoPrefixes.includes(prefix)) return 'airteltigo';\n\n return null;\n}\n\n/**\n * Creates CSS custom property variables from theme\n */\nexport function createThemeVariables(theme: ReevitTheme): Record<string, string> {\n const variables: Record<string, string> = {};\n\n // Primary color = main text color\n if (theme.primaryColor) {\n variables['--reevit-text'] = theme.primaryColor;\n }\n\n // Primary foreground = description/secondary text color\n if (theme.primaryForegroundColor) {\n variables['--reevit-text-secondary'] = theme.primaryForegroundColor;\n variables['--reevit-muted'] = theme.primaryForegroundColor;\n }\n\n // Button colors\n if (theme.buttonBackgroundColor) {\n variables['--reevit-primary'] = theme.buttonBackgroundColor;\n variables['--reevit-primary-hover'] = theme.buttonBackgroundColor;\n }\n if (theme.buttonTextColor) {\n variables['--reevit-primary-foreground'] = theme.buttonTextColor;\n }\n\n // Background and surface colors\n if (theme.backgroundColor) {\n variables['--reevit-background'] = theme.backgroundColor;\n variables['--reevit-surface'] = theme.backgroundColor;\n }\n if (theme.surfaceColor) {\n variables['--reevit-surface'] = theme.surfaceColor;\n }\n\n // Border color\n if (theme.borderColor) {\n variables['--reevit-border'] = theme.borderColor;\n }\n\n // Legacy text color support\n if (theme.textColor) {\n variables['--reevit-text'] = theme.textColor;\n }\n if (theme.mutedTextColor) {\n variables['--reevit-text-secondary'] = theme.mutedTextColor;\n }\n\n // Border radius\n if (theme.borderRadius) {\n variables['--reevit-radius'] = theme.borderRadius;\n variables['--reevit-radius-sm'] = theme.borderRadius;\n variables['--reevit-radius-lg'] = theme.borderRadius;\n }\n\n // Font family\n if (theme.fontFamily) {\n variables['--reevit-font'] = theme.fontFamily;\n }\n\n return variables;\n}\n\nfunction getContrastingColor(color: string): string | null {\n const hex = color.trim();\n if (!hex.startsWith('#')) {\n return null;\n }\n\n const normalized = hex.length === 4\n ? `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`\n : hex;\n\n if (normalized.length !== 7) {\n return null;\n }\n\n const r = parseInt(normalized.slice(1, 3), 16);\n const g = parseInt(normalized.slice(3, 5), 16);\n const b = parseInt(normalized.slice(5, 7), 16);\n\n if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n return null;\n }\n\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 140 ? '#0b1120' : '#ffffff';\n}\n\n/**\n * Simple class name concatenation utility\n */\nexport function cn(...classes: (string | boolean | undefined | null)[]): string {\n return classes.filter(Boolean).join(' ');\n}\n\n/**\n * Detects country code from currency\n */\nexport function detectCountryFromCurrency(currency: string): string {\n const currencyToCountry: Record<string, string> = {\n GHS: 'GH',\n NGN: 'NG',\n KES: 'KE',\n UGX: 'UG',\n TZS: 'TZ',\n ZAR: 'ZA',\n XOF: 'CI',\n XAF: 'CM',\n USD: 'US',\n EUR: 'DE',\n GBP: 'GB',\n };\n\n return currencyToCountry[currency.toUpperCase()] || 'GH';\n}\n","/**\n * Intent identity + cache helpers\n */\n\nimport type { PaymentIntentResponse } from './api/client';\nimport { generateIdempotencyKey } from './api/client';\nimport type { PaymentMethod, ReevitCheckoutConfig } from './types';\nimport { generateReference } from './utils';\n\nconst INTENT_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface IntentIdentityOptions {\n config: ReevitCheckoutConfig;\n method?: PaymentMethod;\n preferredProvider?: string;\n allowedProviders?: string[];\n publicKey?: string;\n}\n\nexport interface IntentCacheEntry {\n promise?: Promise<PaymentIntentResponse>;\n response?: PaymentIntentResponse;\n expiresAt: number;\n reference?: string;\n}\n\nconst intentCache = new Map<string, IntentCacheEntry>();\n\nfunction pruneIntentCache(now: number = Date.now()): void {\n for (const [key, entry] of intentCache) {\n if (entry.expiresAt <= now) {\n intentCache.delete(key);\n }\n }\n}\n\nfunction getIntentCacheEntryInternal(key: string): IntentCacheEntry | undefined {\n const entry = intentCache.get(key);\n if (!entry) {\n return undefined;\n }\n if (entry.expiresAt <= Date.now()) {\n intentCache.delete(key);\n return undefined;\n }\n return entry;\n}\n\nfunction setIntentCacheEntryInternal(key: string, update: Partial<IntentCacheEntry>): IntentCacheEntry {\n const now = Date.now();\n const existing = getIntentCacheEntryInternal(key);\n const next: IntentCacheEntry = {\n ...existing,\n ...update,\n expiresAt: now + INTENT_CACHE_TTL_MS,\n };\n intentCache.set(key, next);\n return next;\n}\n\nfunction buildIdempotencyPayload(options: IntentIdentityOptions): Record<string, unknown> {\n const { config, method, preferredProvider, allowedProviders, publicKey } = options;\n if (config.sessionSecret) {\n return {\n sessionSecret: config.sessionSecret,\n publicKey: publicKey || config.publicKey || '',\n };\n }\n\n const payload: Record<string, unknown> = {\n amount: config.amount,\n currency: config.currency,\n email: config.email || '',\n phone: config.phone || '',\n customerName: config.customerName || '',\n paymentLinkCode: config.paymentLinkCode || '',\n paymentMethods: config.paymentMethods || [],\n metadata: config.metadata || {},\n customFields: config.customFields || {},\n method: method || '',\n preferredProvider: preferredProvider || '',\n allowedProviders: allowedProviders || [],\n publicKey: publicKey || config.publicKey || '',\n };\n\n if (config.reference) {\n payload.reference = config.reference;\n }\n\n return payload;\n}\n\nexport function resolveIntentIdentity(options: IntentIdentityOptions): {\n idempotencyKey: string;\n reference: string;\n cacheEntry?: IntentCacheEntry;\n} {\n pruneIntentCache();\n\n const idempotencyKey =\n options.config.idempotencyKey || generateIdempotencyKey(buildIdempotencyPayload(options));\n const existing = getIntentCacheEntryInternal(idempotencyKey);\n const reference = options.config.reference || existing?.reference || generateReference();\n\n const cacheEntry = setIntentCacheEntryInternal(idempotencyKey, { reference });\n\n return { idempotencyKey, reference, cacheEntry };\n}\n\nexport function getIntentCacheEntry(idempotencyKey: string): IntentCacheEntry | undefined {\n pruneIntentCache();\n return getIntentCacheEntryInternal(idempotencyKey);\n}\n\nexport function cacheIntentPromise(\n idempotencyKey: string,\n promise: Promise<PaymentIntentResponse>\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { promise });\n}\n\nexport function cacheIntentResponse(\n idempotencyKey: string,\n response: PaymentIntentResponse\n): IntentCacheEntry {\n return setIntentCacheEntryInternal(idempotencyKey, { response, promise: undefined });\n}\n\nexport function clearIntentCacheEntry(idempotencyKey: string): void {\n intentCache.delete(idempotencyKey);\n}\n","/**\n * Reevit State Machine\n * Shared state management logic for all SDKs\n */\n\nimport type { CheckoutState, PaymentIntent, PaymentMethod, PaymentResult, PaymentError } from './types';\n\n// State shape\nexport interface ReevitState {\n status: CheckoutState;\n paymentIntent: PaymentIntent | null;\n selectedMethod: PaymentMethod | null;\n error: PaymentError | null;\n result: PaymentResult | null;\n}\n\n// Actions\nexport type ReevitAction =\n | { type: 'INIT_START' }\n | { type: 'INIT_SUCCESS'; payload: PaymentIntent }\n | { type: 'INIT_ERROR'; payload: PaymentError }\n | { type: 'SELECT_METHOD'; payload: PaymentMethod }\n | { type: 'PROCESS_START' }\n | { type: 'PROCESS_SUCCESS'; payload: PaymentResult }\n | { type: 'PROCESS_ERROR'; payload: PaymentError }\n | { type: 'RESET' }\n | { type: 'CLOSE' };\n\n/**\n * Creates the initial state for the checkout\n */\nexport function createInitialState(): ReevitState {\n return {\n status: 'idle',\n paymentIntent: null,\n selectedMethod: null,\n error: null,\n result: null,\n };\n}\n\n/**\n * State reducer for checkout flow\n */\nexport function reevitReducer(state: ReevitState, action: ReevitAction): ReevitState {\n switch (action.type) {\n case 'INIT_START':\n return { ...state, status: 'loading', error: null };\n case 'INIT_SUCCESS':\n return {\n ...state,\n status: 'ready',\n paymentIntent: action.payload,\n selectedMethod:\n action.payload.availableMethods?.length === 1 ? action.payload.availableMethods[0] : null,\n };\n case 'INIT_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'SELECT_METHOD':\n return { ...state, status: 'method_selected', selectedMethod: action.payload };\n case 'PROCESS_START':\n return { ...state, status: 'processing', error: null };\n case 'PROCESS_SUCCESS':\n return { ...state, status: 'success', result: action.payload };\n case 'PROCESS_ERROR':\n return { ...state, status: 'failed', error: action.payload };\n case 'RESET':\n return { ...createInitialState(), status: 'ready', paymentIntent: state.paymentIntent };\n case 'CLOSE':\n return { ...state, status: 'closed' };\n default:\n return state;\n }\n}\n"],"mappings":";AAkHA,IAAM,0BAA0B;AAChC,IAAM,kBAAkB;AACxB,IAAI,mCAAmC;AAYhC,SAAS,mBAAmB,UAAoB,WAA2C;AAChG,SAAO;AAAA,IACL,MAAM,UAAU,QAAQ;AAAA,IACxB,SAAS,UAAU,WAAW;AAAA,IAC9B,aAAa,oBAAo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